static int aac_decode_frame_int(AVCodecContext *avctx, void *data,

                                int *got_frame_ptr, GetBitContext *gb, AVPacket *avpkt)

{

    AACContext *ac = avctx->priv_data;

    ChannelElement *che = NULL, *che_prev = NULL;

    enum RawDataBlockType elem_type, che_prev_type = TYPE_END;

    int err, elem_id;

    int samples = 0, multiplier, audio_found = 0, pce_found = 0;

    int is_dmono, sce_count = 0;

    int payload_alignment;

    ac->frame = data;

    if (show_bits(gb, 12) == 0xfff) {

        if ((err = parse_adts_frame_header(ac, gb)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");

            goto fail;

        }

        if (ac->oc[1].m4ac.sampling_index > 12) {

            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

    }

    if ((err = frame_configure_elements(avctx)) < 0)

        goto fail;

    // The FF_PROFILE_AAC_* defines are all object_type - 1

    // This may lead to an undefined profile being signaled

    ac->avctx->profile = ac->oc[1].m4ac.object_type - 1;

    payload_alignment = get_bits_count(gb);

    ac->tags_mapped = 0;

    // parse

    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {

        elem_id = get_bits(gb, 4);

        if (avctx->debug & FF_DEBUG_STARTCODE)

            av_log(avctx, AV_LOG_DEBUG, "Elem type:%x id:%x\n", elem_type, elem_id);

        if (!avctx->channels && elem_type != TYPE_PCE) {

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

        if (elem_type < TYPE_DSE) {

            if (!(che=get_che(ac, elem_type, elem_id))) {

                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",

                       elem_type, elem_id);

                err = AVERROR_INVALIDDATA;

                goto fail;

            }

            samples = 1024;

            che->present = 1;

        }

        switch (elem_type) {

        case TYPE_SCE:

            err = decode_ics(ac, &che->ch[0], gb, 0, 0);

            audio_found = 1;

            sce_count++;

            break;

        case TYPE_CPE:

            err = decode_cpe(ac, gb, che);

            audio_found = 1;

            break;

        case TYPE_CCE:

            err = decode_cce(ac, gb, che);

            break;

        case TYPE_LFE:

            err = decode_ics(ac, &che->ch[0], gb, 0, 0);

            audio_found = 1;

            break;

        case TYPE_DSE:

            err = skip_data_stream_element(ac, gb);

            break;

        case TYPE_PCE: {

            uint8_t layout_map[MAX_ELEM_ID*4][3];

            int tags;

            push_output_configuration(ac);

            tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb,

                              payload_alignment);

            if (tags < 0) {

                err = tags;

                break;

            }

            if (pce_found) {

                av_log(avctx, AV_LOG_ERROR,

                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");

                pop_output_configuration(ac);

            } else {

                err = output_configure(ac, layout_map, tags, OC_TRIAL_PCE, 1);

                if (!err)

                    ac->oc[1].m4ac.chan_config = 0;

                pce_found = 1;

            }

            break;

        }

        case TYPE_FIL:

            if (elem_id == 15)

                elem_id += get_bits(gb, 8) - 1;

            if (get_bits_left(gb) < 8 * elem_id) {

                    av_log(avctx, AV_LOG_ERROR, "TYPE_FIL: "overread_err);

                    err = AVERROR_INVALIDDATA;

                    goto fail;

            }

            while (elem_id > 0)

                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, che_prev_type);

            err = 0; /* FIXME */

            break;

        default:

            err = AVERROR_BUG; /* should not happen, but keeps compiler happy */

            break;

        }

        if (elem_type < TYPE_DSE) {

            che_prev      = che;

            che_prev_type = elem_type;

        }

        if (err)

            goto fail;

        if (get_bits_left(gb) < 3) {

            av_log(avctx, AV_LOG_ERROR, overread_err);

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

    }

    if (!avctx->channels) {

        *got_frame_ptr = 0;

        return 0;

    }

    multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;

    samples <<= multiplier;

    spectral_to_sample(ac, samples);

    if (ac->oc[1].status && audio_found) {

        avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;

        avctx->frame_size = samples;

        ac->oc[1].status = OC_LOCKED;

    }

    if (multiplier)

        avctx->internal->skip_samples_multiplier = 2;

    if (!ac->frame->data[0] && samples) {

        av_log(avctx, AV_LOG_ERROR, "no frame data found\n");

        err = AVERROR_INVALIDDATA;

        goto fail;

    }

    if (samples) {

        ac->frame->nb_samples = samples;

        ac->frame->sample_rate = avctx->sample_rate;

    } else

        av_frame_unref(ac->frame);

    *got_frame_ptr = !!samples;

    /* for dual-mono audio (SCE + SCE) */

    is_dmono = ac->dmono_mode && sce_count == 2 &&

               ac->oc[1].channel_layout == (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT);

    if (is_dmono) {

        if (ac->dmono_mode == 1)

            ((AVFrame *)data)->data[1] =((AVFrame *)data)->data[0];

        else if (ac->dmono_mode == 2)

            ((AVFrame *)data)->data[0] =((AVFrame *)data)->data[1];

    }

    return 0;

fail:

    pop_output_configuration(ac);

    return err;

}


static void spatial_compose97i_dy_buffered(dwt_compose_t *cs, slice_buffer * sb, int width, int height, int stride_line){

    int y = cs->y;

    int mirror0 = mirror(y - 1, height - 1);

    int mirror1 = mirror(y + 0, height - 1);

    int mirror2 = mirror(y + 1, height - 1);

    int mirror3 = mirror(y + 2, height - 1);

    int mirror4 = mirror(y + 3, height - 1);

    int mirror5 = mirror(y + 4, height - 1);

    DWTELEM *b0= cs->b0;

    DWTELEM *b1= cs->b1;

    DWTELEM *b2= cs->b2;

    DWTELEM *b3= cs->b3;

    DWTELEM *b4= slice_buffer_get_line(sb, mirror4 * stride_line);

    DWTELEM *b5= slice_buffer_get_line(sb, mirror5 * stride_line);

{START_TIMER

    if(y>0 && y+4<height){

        vertical_compose97i(b0, b1, b2, b3, b4, b5, width);

    }else{

        if(mirror3 <= mirror5) vertical_compose97iL1(b3, b4, b5, width);

        if(mirror2 <= mirror4) vertical_compose97iH1(b2, b3, b4, width);

        if(mirror1 <= mirror3) vertical_compose97iL0(b1, b2, b3, width);

        if(mirror0 <= mirror2) vertical_compose97iH0(b0, b1, b2, width);

    }

if(width>400){

STOP_TIMER("vertical_compose97i")}}

{START_TIMER

        if(y-1>=  0) horizontal_compose97i(b0, width);

        if(mirror0 <= mirror2) horizontal_compose97i(b1, width);

if(width>400 && mirror0 <= mirror2){

STOP_TIMER("horizontal_compose97i")}}

    cs->b0=b2;

    cs->b1=b3;

    cs->b2=b4;

    cs->b3=b5;

    cs->y += 2;

}


static void read_table(AVFormatContext *avctx, AVStream *st,

                       int (*parse)(AVFormatContext *avctx, AVStream *st,

                                    const char *name, int size))

{

    int count, i;

    AVIOContext *pb = avctx->pb;

    avio_skip(pb, 4);

    count = avio_rb32(pb);

    avio_skip(pb, 4);

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

        char name[17];

        int size;

        avio_read(pb, name, 16);

        name[sizeof(name) - 1] = 0;

        size = avio_rb32(pb);

        if (parse(avctx, st, name, size) < 0) {

            avpriv_request_sample(avctx, "Variable %s", name);

            avio_skip(pb, size);

        }

    }

}


static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, long src_size)

{

    const uint8_t *s = src;

    const uint8_t *end;

#if COMPILE_TEMPLATE_MMX

    const uint8_t *mm_end;

#endif

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");

    __asm__ volatile(

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

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

        ::"m"(red_15mask),"m"(green_15mask));

    mm_end = end - 15;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"   32%1            \n\t"

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

            "movd        3%1, %%mm3     \n\t"

            "punpckldq   6%1, %%mm0     \n\t"

            "punpckldq   9%1, %%mm3     \n\t"

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

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

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

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

            "psllq        $7, %%mm0     \n\t"

            "psllq        $7, %%mm3     \n\t"

            "pand      %%mm7, %%mm0     \n\t"

            "pand      %%mm7, %%mm3     \n\t"

            "psrlq        $6, %%mm1     \n\t"

            "psrlq        $6, %%mm4     \n\t"

            "pand      %%mm6, %%mm1     \n\t"

            "pand      %%mm6, %%mm4     \n\t"

            "psrlq       $19, %%mm2     \n\t"

            "psrlq       $19, %%mm5     \n\t"

            "pand         %2, %%mm2     \n\t"

            "pand         %2, %%mm5     \n\t"

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

            "por       %%mm4, %%mm3     \n\t"

            "por       %%mm2, %%mm0     \n\t"

            "por       %%mm5, %%mm3     \n\t"

            "psllq       $16, %%mm3     \n\t"

            "por       %%mm3, %%mm0     \n\t"

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

            :"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

        d += 4;

        s += 12;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

#endif

    while (s < end) {

        const int r = *s++;

        const int g = *s++;

        const int b = *s++;

        *d++ = (b>>3) | ((g&0xF8)<<2) | ((r&0xF8)<<7);

    }

}


static int avi_extract_stream_metadata(AVFormatContext *s, AVStream *st)

{

    GetByteContext gb;

    uint8_t *data = st->codecpar->extradata;

    int data_size = st->codecpar->extradata_size;

    int tag, offset;

    if (!data || data_size < 8) {

        return AVERROR_INVALIDDATA;

    }

    bytestream2_init(&gb, data, data_size);

    tag = bytestream2_get_le32(&gb);

    switch (tag) {

    case MKTAG('A', 'V', 'I', 'F'):

        // skip 4 byte padding

        bytestream2_skip(&gb, 4);

        offset = bytestream2_tell(&gb);

        bytestream2_init(&gb, data + offset, data_size - offset);

        // decode EXIF tags from IFD, AVI is always little-endian

        return avpriv_exif_decode_ifd(s, &gb, 1, 0, &st->metadata);

        break;

    case MKTAG('C', 'A', 'S', 'I'):

        avpriv_request_sample(s, "RIFF stream data tag type CASI (%u)", tag);

        break;

    case MKTAG('Z', 'o', 'r', 'a'):

        avpriv_request_sample(s, "RIFF stream data tag type Zora (%u)", tag);

        break;

    default:

        break;

    }

    return 0;

}


static void virtio_vmstate_change(void *opaque, int running, RunState state)

{

    VirtIODevice *vdev = opaque;

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

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);

    if (running) {

        vdev->vm_running = running;

    }

    if (backend_run) {

        virtio_set_status(vdev, vdev->status);

    }

    if (k->vmstate_change) {

        k->vmstate_change(qbus->parent, backend_run);

    }

    if (!backend_run) {

        virtio_set_status(vdev, vdev->status);

    }

    if (!running) {

        vdev->vm_running = running;

    }

}


static int qcow2_set_key(BlockDriverState *bs, const char *key)

{

    BDRVQcow2State *s = bs->opaque;

    uint8_t keybuf[16];

    int len, i;

    Error *err = NULL;

    memset(keybuf, 0, 16);

    len = strlen(key);

    if (len > 16)

        len = 16;

    /* XXX: we could compress the chars to 7 bits to increase

       entropy */

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

        keybuf[i] = key[i];

    }

    assert(bs->encrypted);

    qcrypto_cipher_free(s->cipher);

    s->cipher = qcrypto_cipher_new(

        QCRYPTO_CIPHER_ALG_AES_128,

        QCRYPTO_CIPHER_MODE_CBC,

        keybuf, G_N_ELEMENTS(keybuf),

        &err);

    if (!s->cipher) {

        /* XXX would be nice if errors in this method could

         * be properly propagate to the caller. Would need

         * the bdrv_set_key() API signature to be fixed. */

        error_free(err);

        return -1;

    }

    return 0;

}


void helper_set_cp15(CPUState *env, uint32_t insn, uint32_t val)

{

    uint32_t op2;

    uint32_t crm;

    op2 = (insn >> 5) & 7;

    crm = insn & 0xf;

    switch ((insn >> 16) & 0xf) {

    case 0: /* ID codes.  */

        if (arm_feature(env, ARM_FEATURE_XSCALE))

            break;

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            break;

        goto bad_reg;

    case 1: /* System configuration.  */

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            op2 = 0;

        switch (op2) {

        case 0:

            if (!arm_feature(env, ARM_FEATURE_XSCALE) || crm == 0)

                env->cp15.c1_sys = val;

            /* ??? Lots of these bits are not implemented.  */

            /* This may enable/disable the MMU, so do a TLB flush.  */

            tlb_flush(env, 1);

            break;

        case 1:

            if (arm_feature(env, ARM_FEATURE_XSCALE)) {

                env->cp15.c1_xscaleauxcr = val;

                break;

            }

            goto bad_reg;

        case 2:

            if (arm_feature(env, ARM_FEATURE_XSCALE))

                goto bad_reg;

            env->cp15.c1_coproc = val;

            /* ??? Is this safe when called from within a TB?  */

            tb_flush(env);

            break;

        default:

            goto bad_reg;

        }

        break;

    case 2: /* MMU Page table control / MPU cache control.  */

        if (arm_feature(env, ARM_FEATURE_MPU)) {

            switch (op2) {

            case 0:

                env->cp15.c2_data = val;

                break;

            case 1:

                env->cp15.c2_insn = val;

                break;

            default:

                goto bad_reg;

            }

        } else {

            env->cp15.c2_base = val;

        }

        break;

    case 3: /* MMU Domain access control / MPU write buffer control.  */

        env->cp15.c3 = val;

        break;

    case 4: /* Reserved.  */

        goto bad_reg;

    case 5: /* MMU Fault status / MPU access permission.  */

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            op2 = 0;

        switch (op2) {

        case 0:

            if (arm_feature(env, ARM_FEATURE_MPU))

                val = extended_mpu_ap_bits(val);

            env->cp15.c5_data = val;

            break;

        case 1:

            if (arm_feature(env, ARM_FEATURE_MPU))

                val = extended_mpu_ap_bits(val);

            env->cp15.c5_insn = val;

            break;

        case 2:

            if (!arm_feature(env, ARM_FEATURE_MPU))

                goto bad_reg;

            env->cp15.c5_data = val;

            break;

        case 3:

            if (!arm_feature(env, ARM_FEATURE_MPU))

                goto bad_reg;

            env->cp15.c5_insn = val;

            break;

        default:

            goto bad_reg;

        }

        break;

    case 6: /* MMU Fault address / MPU base/size.  */

        if (arm_feature(env, ARM_FEATURE_MPU)) {

            if (crm >= 8)

                goto bad_reg;

            env->cp15.c6_region[crm] = val;

        } else {

            if (arm_feature(env, ARM_FEATURE_OMAPCP))

                op2 = 0;

            switch (op2) {

            case 0:

                env->cp15.c6_data = val;

                break;

            case 1:

                env->cp15.c6_insn = val;

                break;

            default:

                goto bad_reg;

            }

        }

        break;

    case 7: /* Cache control.  */

        env->cp15.c15_i_max = 0x000;

        env->cp15.c15_i_min = 0xff0;

        /* No cache, so nothing to do.  */

        break;

    case 8: /* MMU TLB control.  */

        switch (op2) {

        case 0: /* Invalidate all.  */

            tlb_flush(env, 0);

            break;

        case 1: /* Invalidate single TLB entry.  */

#if 0

            /* ??? This is wrong for large pages and sections.  */

            /* As an ugly hack to make linux work we always flush a 4K

               pages.  */

            val &= 0xfffff000;

            tlb_flush_page(env, val);

            tlb_flush_page(env, val + 0x400);

            tlb_flush_page(env, val + 0x800);

            tlb_flush_page(env, val + 0xc00);

#else

            tlb_flush(env, 1);

#endif

            break;

        default:

            goto bad_reg;

        }

        break;

    case 9:

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            break;

        switch (crm) {

        case 0: /* Cache lockdown.  */

            switch (op2) {

            case 0:

                env->cp15.c9_data = val;

                break;

            case 1:

                env->cp15.c9_insn = val;

                break;

            default:

                goto bad_reg;

            }

            break;

        case 1: /* TCM memory region registers.  */

            /* Not implemented.  */

            goto bad_reg;

        default:

            goto bad_reg;

        }

        break;

    case 10: /* MMU TLB lockdown.  */

        /* ??? TLB lockdown not implemented.  */

        break;

    case 12: /* Reserved.  */

        goto bad_reg;

    case 13: /* Process ID.  */

        switch (op2) {

        case 0:

            if (!arm_feature(env, ARM_FEATURE_MPU))

                goto bad_reg;

            /* Unlike real hardware the qemu TLB uses virtual addresses,

               not modified virtual addresses, so this causes a TLB flush.

             */

            if (env->cp15.c13_fcse != val)

              tlb_flush(env, 1);

            env->cp15.c13_fcse = val;

            break;

        case 1:

            /* This changes the ASID, so do a TLB flush.  */

            if (env->cp15.c13_context != val

                && !arm_feature(env, ARM_FEATURE_MPU))

              tlb_flush(env, 0);

            env->cp15.c13_context = val;

            break;

        default:

            goto bad_reg;

        }

        break;

    case 14: /* Reserved.  */

        goto bad_reg;

    case 15: /* Implementation specific.  */

        if (arm_feature(env, ARM_FEATURE_XSCALE)) {

            if (op2 == 0 && crm == 1) {

                if (env->cp15.c15_cpar != (val & 0x3fff)) {

                    /* Changes cp0 to cp13 behavior, so needs a TB flush.  */

                    tb_flush(env);

                    env->cp15.c15_cpar = val & 0x3fff;

                }

                break;

            }

            goto bad_reg;

        }

        if (arm_feature(env, ARM_FEATURE_OMAPCP)) {

            switch (crm) {

            case 0:

                break;

            case 1: /* Set TI925T configuration.  */

                env->cp15.c15_ticonfig = val & 0xe7;

                env->cp15.c0_cpuid = (val & (1 << 5)) ? /* OS_TYPE bit */

                        ARM_CPUID_TI915T : ARM_CPUID_TI925T;

                break;

            case 2: /* Set I_max.  */

                env->cp15.c15_i_max = val;

                break;

            case 3: /* Set I_min.  */

                env->cp15.c15_i_min = val;

                break;

            case 4: /* Set thread-ID.  */

                env->cp15.c15_threadid = val & 0xffff;

                break;

            case 8: /* Wait-for-interrupt (deprecated).  */

                cpu_interrupt(env, CPU_INTERRUPT_HALT);

                break;

            default:

                goto bad_reg;

            }

        }

        break;

    }

    return;

bad_reg:

    /* ??? For debugging only.  Should raise illegal instruction exception.  */

    cpu_abort(env, "Unimplemented cp15 register write\n");

}


static size_t stream_process_s2mem(struct Stream *s, unsigned char *buf,

                                   size_t len, uint32_t *app)

{

    uint32_t prev_d;

    unsigned int rxlen;

    size_t pos = 0;

    int sof = 1;

    if (!stream_running(s) || stream_idle(s)) {

        return 0;

    }

    while (len) {

        stream_desc_load(s, s->regs[R_CURDESC]);

        if (s->desc.status & SDESC_STATUS_COMPLETE) {

            s->regs[R_DMASR] |= DMASR_HALTED;

            break;

        }

        rxlen = s->desc.control & SDESC_CTRL_LEN_MASK;

        if (rxlen > len) {

            /* It fits.  */

            rxlen = len;

        }

        cpu_physical_memory_write(s->desc.buffer_address, buf + pos, rxlen);

        len -= rxlen;

        pos += rxlen;

        /* Update the descriptor.  */

        if (!len) {

            int i;

            stream_complete(s);

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

                s->desc.app[i] = app[i];

            }

            s->desc.status |= SDESC_STATUS_EOF;

        }

        s->desc.status |= sof << SDESC_STATUS_SOF_BIT;

        s->desc.status |= SDESC_STATUS_COMPLETE;

        stream_desc_store(s, s->regs[R_CURDESC]);

        sof = 0;

        /* Advance.  */

        prev_d = s->regs[R_CURDESC];

        s->regs[R_CURDESC] = s->desc.nxtdesc;

        if (prev_d == s->regs[R_TAILDESC]) {

            s->regs[R_DMASR] |= DMASR_IDLE;

            break;

        }

    }

    return pos;

}


static void gen_arith(DisasContext *ctx, uint32_t opc,

                      int rd, int rs, int rt)

{

    const char *opn = "arith";

    if (rd == 0 && opc != OPC_ADD && opc != OPC_SUB

       && opc != OPC_DADD && opc != OPC_DSUB) {

        /* If no destination, treat it as a NOP.

           For add & sub, we must generate the overflow exception when needed. */

        MIPS_DEBUG("NOP");

        return;

    }

    switch (opc) {

    case OPC_ADD:

        {

            TCGv t0 = tcg_temp_local_new();

            TCGv t1 = tcg_temp_new();

            TCGv t2 = tcg_temp_new();

            int l1 = gen_new_label();

            gen_load_gpr(t1, rs);

            gen_load_gpr(t2, rt);

            tcg_gen_add_tl(t0, t1, t2);

            tcg_gen_ext32s_tl(t0, t0);

            tcg_gen_xor_tl(t1, t1, t2);

            tcg_gen_xor_tl(t2, t0, t2);

            tcg_gen_andc_tl(t1, t2, t1);

            tcg_temp_free(t2);

            tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1);

            tcg_temp_free(t1);

            /* operands of same sign, result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            gen_store_gpr(t0, rd);

            tcg_temp_free(t0);

        }

        opn = "add";

        break;

    case OPC_ADDU:

        if (rs != 0 && rt != 0) {

            tcg_gen_add_tl(cpu_gpr[rd], cpu_gpr[rs], cpu_gpr[rt]);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

        } else if (rs == 0 && rt != 0) {

            tcg_gen_mov_tl(cpu_gpr[rd], cpu_gpr[rt]);

        } else if (rs != 0 && rt == 0) {

            tcg_gen_mov_tl(cpu_gpr[rd], cpu_gpr[rs]);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

        }

        opn = "addu";

        break;

    case OPC_SUB:

        {

            TCGv t0 = tcg_temp_local_new();

            TCGv t1 = tcg_temp_new();

            TCGv t2 = tcg_temp_new();

            int l1 = gen_new_label();

            gen_load_gpr(t1, rs);

            gen_load_gpr(t2, rt);

            tcg_gen_sub_tl(t0, t1, t2);

            tcg_gen_ext32s_tl(t0, t0);

            tcg_gen_xor_tl(t2, t1, t2);

            tcg_gen_xor_tl(t1, t0, t1);

            tcg_gen_and_tl(t1, t1, t2);

            tcg_temp_free(t2);

            tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1);

            tcg_temp_free(t1);

            /* operands of different sign, first operand and result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            gen_store_gpr(t0, rd);

            tcg_temp_free(t0);

        }

        opn = "sub";

        break;

    case OPC_SUBU:

        if (rs != 0 && rt != 0) {

            tcg_gen_sub_tl(cpu_gpr[rd], cpu_gpr[rs], cpu_gpr[rt]);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

        } else if (rs == 0 && rt != 0) {

            tcg_gen_neg_tl(cpu_gpr[rd], cpu_gpr[rt]);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

        } else if (rs != 0 && rt == 0) {

            tcg_gen_mov_tl(cpu_gpr[rd], cpu_gpr[rs]);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

        }

        opn = "subu";

        break;

#if defined(TARGET_MIPS64)

    case OPC_DADD:

        {

            TCGv t0 = tcg_temp_local_new();

            TCGv t1 = tcg_temp_new();

            TCGv t2 = tcg_temp_new();

            int l1 = gen_new_label();

            gen_load_gpr(t1, rs);

            gen_load_gpr(t2, rt);

            tcg_gen_add_tl(t0, t1, t2);

            tcg_gen_xor_tl(t1, t1, t2);

            tcg_gen_xor_tl(t2, t0, t2);

            tcg_gen_andc_tl(t1, t2, t1);

            tcg_temp_free(t2);

            tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1);

            tcg_temp_free(t1);

            /* operands of same sign, result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            gen_store_gpr(t0, rd);

            tcg_temp_free(t0);

        }

        opn = "dadd";

        break;

    case OPC_DADDU:

        if (rs != 0 && rt != 0) {

            tcg_gen_add_tl(cpu_gpr[rd], cpu_gpr[rs], cpu_gpr[rt]);

        } else if (rs == 0 && rt != 0) {

            tcg_gen_mov_tl(cpu_gpr[rd], cpu_gpr[rt]);

        } else if (rs != 0 && rt == 0) {

            tcg_gen_mov_tl(cpu_gpr[rd], cpu_gpr[rs]);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

        }

        opn = "daddu";

        break;

    case OPC_DSUB:

        {

            TCGv t0 = tcg_temp_local_new();

            TCGv t1 = tcg_temp_new();

            TCGv t2 = tcg_temp_new();

            int l1 = gen_new_label();

            gen_load_gpr(t1, rs);

            gen_load_gpr(t2, rt);

            tcg_gen_sub_tl(t0, t1, t2);

            tcg_gen_xor_tl(t2, t1, t2);

            tcg_gen_xor_tl(t1, t0, t1);

            tcg_gen_and_tl(t1, t1, t2);

            tcg_temp_free(t2);

            tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1);

            tcg_temp_free(t1);

            /* operands of different sign, first operand and result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            gen_store_gpr(t0, rd);

            tcg_temp_free(t0);

        }

        opn = "dsub";

        break;

    case OPC_DSUBU:

        if (rs != 0 && rt != 0) {

            tcg_gen_sub_tl(cpu_gpr[rd], cpu_gpr[rs], cpu_gpr[rt]);

        } else if (rs == 0 && rt != 0) {

            tcg_gen_neg_tl(cpu_gpr[rd], cpu_gpr[rt]);

        } else if (rs != 0 && rt == 0) {

            tcg_gen_mov_tl(cpu_gpr[rd], cpu_gpr[rs]);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

        }

        opn = "dsubu";

        break;

#endif

    case OPC_MUL:

        if (likely(rs != 0 && rt != 0)) {

            tcg_gen_mul_tl(cpu_gpr[rd], cpu_gpr[rs], cpu_gpr[rt]);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

        } else {

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

        }

        opn = "mul";

        break;

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s, %s, %s", opn, regnames[rd], regnames[rs], regnames[rt]);

}


static inline void gen_op_eval_fbl(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_xori_tl(cpu_tmp0, cpu_tmp0, 0x1);

    tcg_gen_and_tl(dst, dst, cpu_tmp0);

}


void qemu_clock_register_reset_notifier(QEMUClockType type,

                                        Notifier *notifier)

{

    QEMUClock *clock = qemu_clock_ptr(type);

    notifier_list_add(&clock->reset_notifiers, notifier);

}


DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)

{

    const char *value;

    DriveInfo *dinfo = NULL;

    QDict *bs_opts;

    QemuOpts *legacy_opts;

    DriveMediaType media = MEDIA_DISK;

    BlockInterfaceType type;

    int cyls, heads, secs, translation;

    int max_devs, bus_id, unit_id, index;

    const char *devaddr;

    bool read_only = false;

    bool copy_on_read;

    const char *filename;

    Error *local_err = NULL;

    /* Change legacy command line options into QMP ones */

    qemu_opt_rename(all_opts, "iops", "throttling.iops-total");

    qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");

    qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");

    qemu_opt_rename(all_opts, "bps", "throttling.bps-total");

    qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");

    qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");

    qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");

    qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");

    qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");

    qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");

    qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");

    qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");

    qemu_opt_rename(all_opts,

                    "iops_size", "throttling.iops-size");

    qemu_opt_rename(all_opts, "readonly", "read-only");

    value = qemu_opt_get(all_opts, "cache");

    if (value) {

        int flags = 0;

        if (bdrv_parse_cache_flags(value, &flags) != 0) {

            error_report("invalid cache option");

            return NULL;

        }

        /* Specific options take precedence */

        if (!qemu_opt_get(all_opts, "cache.writeback")) {

            qemu_opt_set_bool(all_opts, "cache.writeback",

                              !!(flags & BDRV_O_CACHE_WB));

        }

        if (!qemu_opt_get(all_opts, "cache.direct")) {

            qemu_opt_set_bool(all_opts, "cache.direct",

                              !!(flags & BDRV_O_NOCACHE));

        }

        if (!qemu_opt_get(all_opts, "cache.no-flush")) {

            qemu_opt_set_bool(all_opts, "cache.no-flush",

                              !!(flags & BDRV_O_NO_FLUSH));

        }

        qemu_opt_unset(all_opts, "cache");

    }

    /* Get a QDict for processing the options */

    bs_opts = qdict_new();

    qemu_opts_to_qdict(all_opts, bs_opts);

    legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,

                                   &error_abort);

    qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);

    if (error_is_set(&local_err)) {

        qerror_report_err(local_err);

        error_free(local_err);

        goto fail;

    }

    /* Deprecated option boot=[on|off] */

    if (qemu_opt_get(legacy_opts, "boot") != NULL) {

        fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "

                "ignored. Future versions will reject this parameter. Please "

                "update your scripts.\n");

    }

    /* Media type */

    value = qemu_opt_get(legacy_opts, "media");

    if (value) {

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

            media = MEDIA_DISK;

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

            media = MEDIA_CDROM;

            read_only = true;

        } else {

            error_report("'%s' invalid media", value);

            goto fail;

        }

    }

    /* copy-on-read is disabled with a warning for read-only devices */

    read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);

    copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);

    if (read_only && copy_on_read) {

        error_report("warning: disabling copy-on-read on read-only drive");

        copy_on_read = false;

    }

    qdict_put(bs_opts, "read-only",

              qstring_from_str(read_only ? "on" : "off"));

    qdict_put(bs_opts, "copy-on-read",

              qstring_from_str(copy_on_read ? "on" :"off"));

    /* Controller type */

    value = qemu_opt_get(legacy_opts, "if");

    if (value) {

        for (type = 0;

             type < IF_COUNT && strcmp(value, if_name[type]);

             type++) {

        }

        if (type == IF_COUNT) {

            error_report("unsupported bus type '%s'", value);

            goto fail;

        }

    } else {

        type = block_default_type;

    }

    /* Geometry */

    cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);

    heads = qemu_opt_get_number(legacy_opts, "heads", 0);

    secs  = qemu_opt_get_number(legacy_opts, "secs", 0);

    if (cyls || heads || secs) {

        if (cyls < 1) {

            error_report("invalid physical cyls number");

            goto fail;

        }

        if (heads < 1) {

            error_report("invalid physical heads number");

            goto fail;

        }

        if (secs < 1) {

            error_report("invalid physical secs number");

            goto fail;

        }

    }

    translation = BIOS_ATA_TRANSLATION_AUTO;

    value = qemu_opt_get(legacy_opts, "trans");

    if (value != NULL) {

        if (!cyls) {

            error_report("'%s' trans must be used with cyls, heads and secs",

                         value);

            goto fail;

        }

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

            translation = BIOS_ATA_TRANSLATION_NONE;

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

            translation = BIOS_ATA_TRANSLATION_LBA;

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

            translation = BIOS_ATA_TRANSLATION_AUTO;

        } else {

            error_report("'%s' invalid translation type", value);

            goto fail;

        }

    }

    if (media == MEDIA_CDROM) {

        if (cyls || secs || heads) {

            error_report("CHS can't be set with media=cdrom");

            goto fail;

        }

    }

    /* Device address specified by bus/unit or index.

     * If none was specified, try to find the first free one. */

    bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);

    unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);

    index   = qemu_opt_get_number(legacy_opts, "index", -1);

    max_devs = if_max_devs[type];

    if (index != -1) {

        if (bus_id != 0 || unit_id != -1) {

            error_report("index cannot be used with bus and unit");

            goto fail;

        }

        bus_id = drive_index_to_bus_id(type, index);

        unit_id = drive_index_to_unit_id(type, index);

    }

    if (unit_id == -1) {

       unit_id = 0;

       while (drive_get(type, bus_id, unit_id) != NULL) {

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    if (max_devs && unit_id >= max_devs) {

        error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);

        goto fail;

    }

    if (drive_get(type, bus_id, unit_id) != NULL) {

        error_report("drive with bus=%d, unit=%d (index=%d) exists",

                     bus_id, unit_id, index);

        goto fail;

    }

    /* no id supplied -> create one */

    if (qemu_opts_id(all_opts) == NULL) {

        char *new_id;

        const char *mediastr = "";

        if (type == IF_IDE || type == IF_SCSI) {

            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";

        }

        if (max_devs) {

            new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,

                                     mediastr, unit_id);

        } else {

            new_id = g_strdup_printf("%s%s%i", if_name[type],

                                     mediastr, unit_id);

        }

        qdict_put(bs_opts, "id", qstring_from_str(new_id));

        g_free(new_id);

    }

    /* Add virtio block device */

    devaddr = qemu_opt_get(legacy_opts, "addr");

    if (devaddr && type != IF_VIRTIO) {

        error_report("addr is not supported by this bus type");

        goto fail;

    }

    if (type == IF_VIRTIO) {

        QemuOpts *devopts;

        devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,

                                   &error_abort);

        if (arch_type == QEMU_ARCH_S390X) {

            qemu_opt_set(devopts, "driver", "virtio-blk-s390");

        } else {

            qemu_opt_set(devopts, "driver", "virtio-blk-pci");

        }

        qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));

        if (devaddr) {

            qemu_opt_set(devopts, "addr", devaddr);

        }

    }

    filename = qemu_opt_get(legacy_opts, "file");

    /* Actual block device init: Functionality shared with blockdev-add */

    dinfo = blockdev_init(filename, bs_opts, type, &local_err);

    if (dinfo == NULL) {

        if (error_is_set(&local_err)) {

            qerror_report_err(local_err);

            error_free(local_err);

        }

        goto fail;

    } else {

        assert(!error_is_set(&local_err));

    }

    /* Set legacy DriveInfo fields */

    dinfo->enable_auto_del = true;

    dinfo->opts = all_opts;

    dinfo->cyls = cyls;

    dinfo->heads = heads;

    dinfo->secs = secs;

    dinfo->trans = translation;

    dinfo->bus = bus_id;

    dinfo->unit = unit_id;

    dinfo->devaddr = devaddr;

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

    case IF_NONE:

        dinfo->media_cd = media == MEDIA_CDROM;

        break;

    default:

        break;

    }

fail:

    qemu_opts_del(legacy_opts);

    return dinfo;

}


static int cd_read_sector(IDEState *s, int lba, uint8_t *buf, int sector_size)

{

    int ret;

    switch(sector_size) {

    case 2048:

        block_acct_start(bdrv_get_stats(s->bs), &s->acct,

                         4 * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);

        ret = bdrv_read(s->bs, (int64_t)lba << 2, buf, 4);

        block_acct_done(bdrv_get_stats(s->bs), &s->acct);

        break;

    case 2352:

        block_acct_start(bdrv_get_stats(s->bs), &s->acct,

                         4 * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);

        ret = bdrv_read(s->bs, (int64_t)lba << 2, buf + 16, 4);

        block_acct_done(bdrv_get_stats(s->bs), &s->acct);

        if (ret < 0)

            return ret;

        cd_data_to_raw(buf, lba);

        break;

    default:

        ret = -EIO;

        break;

    }

    return ret;

}


static void av_always_inline filter_mb_edgecv( uint8_t *pix, int stride, const int16_t bS[4], unsigned int qp, H264Context *h, int intra ) {

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

    const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 || !intra ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]]+1;

        tc[1] = tc0_table[index_a][bS[1]]+1;

        tc[2] = tc0_table[index_a][bS[2]]+1;

        tc[3] = tc0_table[index_a][bS[3]]+1;

        h->h264dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);

    }

}


e1000_can_receive(void *opaque)

{

    E1000State *s = opaque;

    return (s->mac_reg[RCTL] & E1000_RCTL_EN);

}


static uint32_t intel_hda_mmio_readl(void *opaque, target_phys_addr_t addr)

{

    IntelHDAState *d = opaque;

    const IntelHDAReg *reg = intel_hda_reg_find(d, addr);

    return intel_hda_reg_read(d, reg, 0xffffffff);

}


void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)

{

    if (backing_hd) {

        bdrv_ref(backing_hd);

    }

    if (bs->backing) {

        assert(bs->backing_blocker);

        bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);

        bdrv_unref_child(bs, bs->backing);

    } else if (backing_hd) {

        error_setg(&bs->backing_blocker,

                   "node is used as backing hd of '%s'",

                   bdrv_get_device_or_node_name(bs));

    }

    if (!backing_hd) {

        error_free(bs->backing_blocker);

        bs->backing_blocker = NULL;

        bs->backing = NULL;

        goto out;

    }

    bs->backing = bdrv_attach_child(bs, backing_hd, &child_backing);

    bs->open_flags &= ~BDRV_O_NO_BACKING;

    pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);

    pstrcpy(bs->backing_format, sizeof(bs->backing_format),

            backing_hd->drv ? backing_hd->drv->format_name : "");

    bdrv_op_block_all(backing_hd, bs->backing_blocker);

    /* Otherwise we won't be able to commit due to check in bdrv_commit */

    bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,

                    bs->backing_blocker);

out:

    bdrv_refresh_limits(bs, NULL);

}


void bdrv_parent_drained_end(BlockDriverState *bs)

{

    BdrvChild *c;

    QLIST_FOREACH(c, &bs->parents, next_parent) {

        if (c->role->drained_end) {

            c->role->drained_end(c);

        }

    }

}


static void virtio_ccw_crypto_instance_init(Object *obj)

{

    VirtIOCryptoCcw *dev = VIRTIO_CRYPTO_CCW(obj);

    VirtioCcwDevice *ccw_dev = VIRTIO_CCW_DEVICE(obj);

    ccw_dev->force_revision_1 = true;

    virtio_instance_init_common(obj, &dev->vdev, sizeof(dev->vdev),

                                TYPE_VIRTIO_CRYPTO);

    object_property_add_alias(obj, "cryptodev", OBJECT(&dev->vdev),

                              "cryptodev", &error_abort);

}


static void gen_bxx(DisasContext *dc, uint32_t code, uint32_t flags)

{

    I_TYPE(instr, code);

    TCGLabel *l1 = gen_new_label();

    tcg_gen_brcond_tl(flags, dc->cpu_R[instr.a], dc->cpu_R[instr.b], l1);

    gen_goto_tb(dc, 0, dc->pc + 4);

    gen_set_label(l1);

    gen_goto_tb(dc, 1, dc->pc + 4 + (instr.imm16s & -4));

    dc->is_jmp = DISAS_TB_JUMP;

}


static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                                  void *data, int *got_frame,
                                  const uint8_t *buf, int buf_size)
{
    FlicDecodeContext *s = avctx->priv_data;
    GetByteContext g2;
    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, ret;
    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;
    int byte_run;
    int pixel_skip;
    int pixel_countdown;
    unsigned char *pixels;
    unsigned int pixel_limit;
    bytestream2_init(&g2, buf, buf_size);
    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0)
        return ret;
    pixels = s->frame->data[0];
    pixel_limit = s->avctx->height * s->frame->linesize[0];
    if (buf_size < 16 || buf_size > INT_MAX - (3 * 256 + AV_INPUT_BUFFER_PADDING_SIZE))
    frame_size = bytestream2_get_le32(&g2);
    if (frame_size > buf_size)
        frame_size = buf_size;
    bytestream2_skip(&g2, 2); /* skip the magic number */
    num_chunks = bytestream2_get_le16(&g2);
    bytestream2_skip(&g2, 8);  /* skip padding */
    frame_size -= 16;
    /* iterate through the chunks */
    while ((frame_size >= 6) && (num_chunks > 0) &&
            bytestream2_get_bytes_left(&g2) >= 4) {
        int stream_ptr_after_chunk;
        chunk_size = bytestream2_get_le32(&g2);
        if (chunk_size > frame_size) {
            av_log(avctx, AV_LOG_WARNING,
                   "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size);
            chunk_size = frame_size;
        }
        stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size;
        chunk_type = bytestream2_get_le16(&g2);
        switch (chunk_type) {
        case FLI_256_COLOR:
        case FLI_COLOR:
            /* 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 != FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE))
                color_shift = 0;
            else
                color_shift = 2;
            /* set up the palette */
            color_packets = bytestream2_get_le16(&g2);
            palette_ptr = 0;
            for (i = 0; i < color_packets; i++) {
                /* first byte is how many colors to skip */
                palette_ptr += bytestream2_get_byte(&g2);
                /* next byte indicates how many entries to change */
                color_changes = bytestream2_get_byte(&g2);
                /* if there are 0 color changes, there are actually 256 */
                if (color_changes == 0)
                    color_changes = 256;
                if (bytestream2_tell(&g2) + color_changes * 3 > stream_ptr_after_chunk)
                    break;
                for (j = 0; j < color_changes; j++) {
                    unsigned int entry;
                    /* wrap around, for good measure */
                    if ((unsigned)palette_ptr >= 256)
                        palette_ptr = 0;
                    r = bytestream2_get_byte(&g2) << color_shift;
                    g = bytestream2_get_byte(&g2) << color_shift;
                    b = bytestream2_get_byte(&g2) << color_shift;
                    entry = 0xFFU << 24 | r << 16 | g << 8 | b;
                    if (color_shift == 2)
                        entry |= entry >> 6 & 0x30303;
                    if (s->palette[palette_ptr] != entry)
                        s->new_palette = 1;
                    s->palette[palette_ptr++] = entry;
                }
            }
            break;
        case FLI_DELTA:
            y_ptr = 0;
            compressed_lines = bytestream2_get_le16(&g2);
            while (compressed_lines > 0) {
                if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)
                    break;
                line_packets = bytestream2_get_le16(&g2);
                if ((line_packets & 0xC000) == 0xC000) {
                    // line skip opcode
                    line_packets = -line_packets;
                    y_ptr += line_packets * s->frame->linesize[0];
                } else if ((line_packets & 0xC000) == 0x4000) {
                    av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets);
                } else if ((line_packets & 0xC000) == 0x8000) {
                    // "last byte" opcode
                    pixel_ptr= y_ptr + s->frame->linesize[0] - 1;
                    CHECK_PIXEL_PTR(0);
                    pixels[pixel_ptr] = line_packets & 0xff;
                } else {
                    compressed_lines--;
                    pixel_ptr = y_ptr;
                    CHECK_PIXEL_PTR(0);
                    pixel_countdown = s->avctx->width;
                    for (i = 0; i < line_packets; i++) {
                        if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)
                            break;
                        /* account for the skip bytes */
                        pixel_skip = bytestream2_get_byte(&g2);
                        pixel_ptr += pixel_skip;
                        pixel_countdown -= pixel_skip;
                        byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                        if (byte_run < 0) {
                            byte_run = -byte_run;
                            palette_idx1 = bytestream2_get_byte(&g2);
                            palette_idx2 = bytestream2_get_byte(&g2);
                            CHECK_PIXEL_PTR(byte_run * 2);
                            for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                pixels[pixel_ptr++] = palette_idx1;
                                pixels[pixel_ptr++] = palette_idx2;
                            }
                        } else {
                            CHECK_PIXEL_PTR(byte_run * 2);
                            if (bytestream2_tell(&g2) + byte_run * 2 > stream_ptr_after_chunk)
                                break;
                            for (j = 0; j < byte_run * 2; j++, pixel_countdown--) {
                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);
                            }
                        }
                    }
                    y_ptr += s->frame->linesize[0];
                }
            }
            break;
        case FLI_LC:
            /* line compressed */
            starting_line = bytestream2_get_le16(&g2);
            y_ptr = 0;
            y_ptr += starting_line * s->frame->linesize[0];
            compressed_lines = bytestream2_get_le16(&g2);
            while (compressed_lines > 0) {
                pixel_ptr = y_ptr;
                CHECK_PIXEL_PTR(0);
                pixel_countdown = s->avctx->width;
                if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)
                    break;
                line_packets = bytestream2_get_byte(&g2);
                if (line_packets > 0) {
                    for (i = 0; i < line_packets; i++) {
                        /* account for the skip bytes */
                        if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)
                            break;
                        pixel_skip = bytestream2_get_byte(&g2);
                        pixel_ptr += pixel_skip;
                        pixel_countdown -= pixel_skip;
                        byte_run = sign_extend(bytestream2_get_byte(&g2),8);
                        if (byte_run > 0) {
                            CHECK_PIXEL_PTR(byte_run);
                            if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)
                                break;
                            for (j = 0; j < byte_run; j++, pixel_countdown--) {
                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);
                            }
                        } else if (byte_run < 0) {
                            byte_run = -byte_run;
                            palette_idx1 = bytestream2_get_byte(&g2);
                            CHECK_PIXEL_PTR(byte_run);
                            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 */
                 bytestream2_skip(&g2, 1);
                pixel_countdown = s->avctx->width;
                while (pixel_countdown > 0) {
                    if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)
                        break;
                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                    if (!byte_run) {
                        av_log(avctx, AV_LOG_ERROR, "Invalid byte run value.\n");
                    }
                    if (byte_run > 0) {
                        palette_idx1 = bytestream2_get_byte(&g2);
                        CHECK_PIXEL_PTR(byte_run);
                        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) at line %d\n",
                                       pixel_countdown, lines);
                        }
                    } else {  /* copy bytes if byte_run < 0 */
                        byte_run = -byte_run;
                        CHECK_PIXEL_PTR(byte_run);
                        if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)
                            break;
                        for (j = 0; j < byte_run; j++) {
                            pixels[pixel_ptr++] = bytestream2_get_byte(&g2);
                            pixel_countdown--;
                            if (pixel_countdown < 0)
                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",
                                       pixel_countdown, lines);
                        }
                    }
                }
                y_ptr += s->frame->linesize[0];
            }
            break;
        case FLI_COPY:
            /* copy the chunk (uncompressed frame) */
            if (chunk_size - 6 != FFALIGN(s->avctx->width, 4) * s->avctx->height) {
                av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \
                       "has incorrect size, skipping chunk\n", chunk_size - 6);
                bytestream2_skip(&g2, chunk_size - 6);
            } else {
                for (y_ptr = 0; y_ptr < s->frame->linesize[0] * s->avctx->height;
                     y_ptr += s->frame->linesize[0]) {
                    bytestream2_get_buffer(&g2, &pixels[y_ptr],
                                           s->avctx->width);
                    if (s->avctx->width & 3)
                        bytestream2_skip(&g2, 4 - (s->avctx->width & 3));
                }
            }
            break;
        case FLI_MINI:
            /* some sort of a thumbnail? disregard this chunk... */
            break;
        default:
            av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type);
            break;
        }
        if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) {
            bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2));
        } else {
            av_log(avctx, AV_LOG_ERROR, "Chunk overread\n");
            break;
        }
        frame_size -= chunk_size;
        num_chunks--;
    }
    /* by the end of the chunk, the stream ptr should equal the frame
     * size (minus 1 or 2, possibly); if it doesn't, issue a warning */
    if (bytestream2_get_bytes_left(&g2) > 2)
        av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \
               "and final chunk ptr = %d\n", buf_size,
               buf_size - bytestream2_get_bytes_left(&g2));
    /* make the palette available on the way out */
    memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE);
    if (s->new_palette) {
        s->frame->palette_has_changed = 1;
        s->new_palette = 0;
    }
    if ((ret = av_frame_ref(data, s->frame)) < 0)
        return ret;
    *got_frame = 1;
    return buf_size;
}


static void print_type_size(Visitor *v, const char *name, uint64_t *obj,

                            Error **errp)

{

    StringOutputVisitor *sov = to_sov(v);

    static const char suffixes[] = { 'B', 'K', 'M', 'G', 'T', 'P', 'E' };

    uint64_t div, val;

    char *out;

    int i;

    if (!sov->human) {

        out = g_strdup_printf("%"PRIu64, *obj);

        string_output_set(sov, out);

        return;

    }

    val = *obj;

    /* The exponent (returned in i) minus one gives us

     * floor(log2(val * 1024 / 1000).  The correction makes us

     * switch to the higher power when the integer part is >= 1000.

     */

    frexp(val / (1000.0 / 1024.0), &i);

    i = (i - 1) / 10;

    assert(i < ARRAY_SIZE(suffixes));

    div = 1ULL << (i * 10);

    out = g_strdup_printf("%"PRIu64" (%0.3g %c%s)", val,

                          (double)val/div, suffixes[i], i ? "iB" : "");

    string_output_set(sov, out);

}


static int cmp_color(const void *a, const void *b)

{

    const struct range_box *box1 = a;

    const struct range_box *box2 = b;

    return box1->color - box2->color;

}


static void iommu_config_write(void *opaque, hwaddr addr,

                               uint64_t val, unsigned size)

{

    IOMMUState *is = opaque;

    IOMMU_DPRINTF("IOMMU config write: 0x%" HWADDR_PRIx " val: %" PRIx64

                  " size: %d\n", addr, val, size);

    switch (addr) {

    case IOMMU_CTRL:

        if (size == 4) {

            is->regs[IOMMU_CTRL >> 3] &= 0xffffffffULL;

            is->regs[IOMMU_CTRL >> 3] |= val << 32;

        } else {

            is->regs[IOMMU_CTRL] = val;

        }

        break;

    case IOMMU_CTRL + 0x4:

        is->regs[IOMMU_CTRL >> 3] &= 0xffffffff00000000ULL;

        is->regs[IOMMU_CTRL >> 3] |= val & 0xffffffffULL;

        break;

    case IOMMU_BASE:

        if (size == 4) {

            is->regs[IOMMU_BASE >> 3] &= 0xffffffffULL;

            is->regs[IOMMU_BASE >> 3] |= val << 32;

        } else {

            is->regs[IOMMU_BASE] = val;

        }

        break;

    case IOMMU_BASE + 0x4:

        is->regs[IOMMU_BASE >> 3] &= 0xffffffff00000000ULL;

        is->regs[IOMMU_BASE >> 3] |= val & 0xffffffffULL;

        break;

    default:

        qemu_log_mask(LOG_UNIMP,

                  "apb iommu: Unimplemented register write "

                  "reg 0x%" HWADDR_PRIx " size 0x%x value 0x%" PRIx64 "\n",

                  addr, size, val);

        break;

    }

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->no_hotplug = 1;

    k->init = pci_piix_ide_initfn;

    k->exit = pci_piix_ide_exitfn;

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_82371SB_1;

    k->class_id = PCI_CLASS_STORAGE_IDE;

    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);

    dc->no_user = 1;

}


static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],

                                  int16_t *buffer_out,

                                  int numchannels, int numsamples,

                                  uint8_t interlacing_shift,

                                  uint8_t interlacing_leftweight)

{

    int i;

    if (numsamples <= 0)

        return;

    /* weighted interlacing */

    if (interlacing_leftweight) {

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

            int32_t a, b;

            a = buffer[0][i];

            b = buffer[1][i];

            a -= (b * interlacing_leftweight) >> interlacing_shift;

            b += a;

            buffer_out[i*numchannels] = b;

            buffer_out[i*numchannels + 1] = a;

        }

        return;

    }

    /* otherwise basic interlacing took place */

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

        int16_t left, right;

        left = buffer[0][i];

        right = buffer[1][i];

        buffer_out[i*numchannels] = left;

        buffer_out[i*numchannels + 1] = right;

    }

}


av_cold void ff_vp9_init_static(AVCodec *codec)

{

    if (    vpx_codec_version_major() < 1

        || (vpx_codec_version_major() == 1 && vpx_codec_version_minor() < 3))

        codec->capabilities |= AV_CODEC_CAP_EXPERIMENTAL;

    codec->pix_fmts = vp9_pix_fmts_def;

#if CONFIG_LIBVPX_VP9_ENCODER

    if (    vpx_codec_version_major() > 1

        || (vpx_codec_version_major() == 1 && vpx_codec_version_minor() >= 4)) {

#ifdef VPX_CODEC_CAP_HIGHBITDEPTH

        vpx_codec_caps_t codec_caps = vpx_codec_get_caps(vpx_codec_vp9_cx());

        if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH)

            codec->pix_fmts = vp9_pix_fmts_highbd;

        else

#endif

            codec->pix_fmts = vp9_pix_fmts_highcol;

    }

#endif

}


void ioinst_handle_rsch(S390CPU *cpu, uint64_t reg1)

{

    int cssid, ssid, schid, m;

    SubchDev *sch;

    int ret = -ENODEV;

    int cc;

    if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid)) {

        program_interrupt(&cpu->env, PGM_OPERAND, 2);

        return;

    }

    trace_ioinst_sch_id("rsch", cssid, ssid, schid);

    sch = css_find_subch(m, cssid, ssid, schid);

    if (sch && css_subch_visible(sch)) {

        ret = css_do_rsch(sch);

    }

    switch (ret) {

    case -ENODEV:

        cc = 3;

        break;

    case -EINVAL:

        cc = 2;

        break;

    case 0:

        cc = 0;

        break;

    default:

        cc = 1;

        break;

    }

    setcc(cpu, cc);

}


int kvm_arch_process_irqchip_events(CPUState *env)

{

    return 0;

}


static void decode_tones_amplitude(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,

                                   int ch_num, int band_has_tones[])

{

    int mode, sb, j, i, diff, maxdiff, fi, delta, pred;

    Atrac3pWaveParam *wsrc, *wref;

    int refwaves[48];

    Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;

    Atrac3pWavesData *ref = ctx->channels[0].tones_info;

    if (ch_num) {

        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {

            if (!band_has_tones[sb] || !dst[sb].num_wavs)

                continue;

            wsrc = &ctx->waves_info->waves[dst[sb].start_index];

            wref = &ctx->waves_info->waves[ref[sb].start_index];

            for (j = 0; j < dst[sb].num_wavs; j++) {

                for (i = 0, fi = 0, maxdiff = 1024; i < ref[sb].num_wavs; i++) {

                    diff = FFABS(wsrc[j].freq_index - wref[i].freq_index);

                    if (diff < maxdiff) {

                        maxdiff = diff;

                        fi      = i;

                    }

                }

                if (maxdiff < 8)

                    refwaves[dst[sb].start_index + j] = fi + ref[sb].start_index;

                else if (j < ref[sb].num_wavs)

                    refwaves[dst[sb].start_index + j] = j + ref[sb].start_index;

                else

                    refwaves[dst[sb].start_index + j] = -1;

            }

        }

    }

    mode = get_bits(gb, ch_num + 1);

    switch (mode) {

    case 0: /** fixed-length coding */

        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {

            if (!band_has_tones[sb] || !dst[sb].num_wavs)

                continue;

            if (ctx->waves_info->amplitude_mode)

                for (i = 0; i < dst[sb].num_wavs; i++)

                    ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = get_bits(gb, 6);

            else

                ctx->waves_info->waves[dst[sb].start_index].amp_sf = get_bits(gb, 6);

        }

        break;

    case 1: /** min + VLC delta */

        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {

            if (!band_has_tones[sb] || !dst[sb].num_wavs)

                continue;

            if (ctx->waves_info->amplitude_mode)

                for (i = 0; i < dst[sb].num_wavs; i++)

                    ctx->waves_info->waves[dst[sb].start_index + i].amp_sf =

                        get_vlc2(gb, tone_vlc_tabs[3].table,

                                 tone_vlc_tabs[3].bits, 1) + 20;

            else

                ctx->waves_info->waves[dst[sb].start_index].amp_sf =

                    get_vlc2(gb, tone_vlc_tabs[4].table,

                             tone_vlc_tabs[4].bits, 1) + 24;

        }

        break;

    case 2: /** VLC modulo delta to master (slave only) */

        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {

            if (!band_has_tones[sb] || !dst[sb].num_wavs)

                continue;

            for (i = 0; i < dst[sb].num_wavs; i++) {

                delta = get_vlc2(gb, tone_vlc_tabs[5].table,

                                 tone_vlc_tabs[5].bits, 1);

                delta = sign_extend(delta, 5);

                pred  = refwaves[dst[sb].start_index + i] >= 0 ?

                        ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf : 34;

                ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = (pred + delta) & 0x3F;

            }

        }

        break;

    case 3: /** clone master (slave only) */

        for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {

            if (!band_has_tones[sb])

                continue;

            for (i = 0; i < dst[sb].num_wavs; i++)

                ctx->waves_info->waves[dst[sb].start_index + i].amp_sf =

                    refwaves[dst[sb].start_index + i] >= 0

                    ? ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf

                    : 32;

        }

        break;

    }

}


static int vhost_net_set_vnet_endian(VirtIODevice *dev, NetClientState *peer,

                                     bool set)

{

    int r = 0;

    if (virtio_has_feature(dev, VIRTIO_F_VERSION_1) ||

        (virtio_legacy_is_cross_endian(dev) && !virtio_is_big_endian(dev))) {

        r = qemu_set_vnet_le(peer, set);

        if (r) {

            error_report("backend does not support LE vnet headers");

        }

    } else if (virtio_legacy_is_cross_endian(dev)) {

        r = qemu_set_vnet_be(peer, set);

        if (r) {

            error_report("backend does not support BE vnet headers");

        }

    }

    return r;

}


static void virtio_net_add_queue(VirtIONet *n, int index)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    n->vqs[index].rx_vq = virtio_add_queue(vdev, n->net_conf.rx_queue_size,

                                           virtio_net_handle_rx);

    if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {

        n->vqs[index].tx_vq =

            virtio_add_queue(vdev, 256, virtio_net_handle_tx_timer);

        n->vqs[index].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                              virtio_net_tx_timer,

                                              &n->vqs[index]);

    } else {

        n->vqs[index].tx_vq =

            virtio_add_queue(vdev, 256, virtio_net_handle_tx_bh);

        n->vqs[index].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[index]);

    }

    n->vqs[index].tx_waiting = 0;

    n->vqs[index].n = n;

}


int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,

                          unsigned int out_bytes)

{

    unsigned int in_total, out_total;

    virtqueue_get_avail_bytes(vq, &in_total, &out_total);

    if ((in_bytes && in_bytes < in_total)

        || (out_bytes && out_bytes < out_total)) {

        return 1;

    }

    return 0;

}


static always_inline void gen_load_spr(TCGv t, int reg)

{

    tcg_gen_ld_tl(t, cpu_env, offsetof(CPUState, spr[reg]));

}


void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,

                   BlockCompletionFunc *cb, void *opaque)

{

    BlockAIOCB *acb;

    acb = g_slice_alloc(aiocb_info->aiocb_size);

    acb->aiocb_info = aiocb_info;

    acb->bs = bs;

    acb->cb = cb;

    acb->opaque = opaque;

    acb->refcnt = 1;

    return acb;

}


char *socket_address_to_string(struct SocketAddress *addr, Error **errp)

{

    char *buf;

    InetSocketAddress *inet;

    switch (addr->type) {

    case SOCKET_ADDRESS_KIND_INET:

        inet = addr->u.inet.data;

        if (strchr(inet->host, ':') == NULL) {

            buf = g_strdup_printf("%s:%s", inet->host, inet->port);

        } else {

            buf = g_strdup_printf("[%s]:%s", inet->host, inet->port);

        }

        break;

    case SOCKET_ADDRESS_KIND_UNIX:

        buf = g_strdup(addr->u.q_unix.data->path);

        break;

    case SOCKET_ADDRESS_KIND_FD:

        buf = g_strdup(addr->u.fd.data->str);

        break;

    case SOCKET_ADDRESS_KIND_VSOCK:

        buf = g_strdup_printf("%s:%s",

                              addr->u.vsock.data->cid,

                              addr->u.vsock.data->port);

        break;

    default:

        abort();

    }

    return buf;

}


static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path,

                       const char *name, FsCred *credp)

{

    char *path;

    int err = -1;

    int serrno = 0;

    V9fsString fullname;

    char buffer[PATH_MAX];

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    path = fullname.data;

    /* Determine the security model */

    if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        err = mkdir(rpath(fs_ctx, path, buffer), SM_LOCAL_DIR_MODE_BITS);

        if (err == -1) {

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFDIR;

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

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        err = mkdir(rpath(fs_ctx, path, buffer), SM_LOCAL_DIR_MODE_BITS);

        if (err == -1) {

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFDIR;

        err = local_set_mapped_file_attr(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||

               (fs_ctx->export_flags & V9FS_SM_NONE)) {

        err = mkdir(rpath(fs_ctx, path, buffer), credp->fc_mode);

        if (err == -1) {

            goto out;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    goto out;

err_end:

    remove(rpath(fs_ctx, path, buffer));

    errno = serrno;

out:

    v9fs_string_free(&fullname);

    return err;

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,

                                              int *got_picture_ptr,

                                              const AVPacket *avpkt)

{

    AVCodecInternal *avci = avctx->internal;

    int ret;

    // copy to ensure we do not change avpkt

    AVPacket tmp = *avpkt;

    if (!avctx->codec)

        return AVERROR(EINVAL);

    if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");

        return AVERROR(EINVAL);

    }

    *got_picture_ptr = 0;

    if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))

        return AVERROR(EINVAL);

    avcodec_get_frame_defaults(picture);

    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {

        int did_split = av_packet_split_side_data(&tmp);

        ret = apply_param_change(avctx, &tmp);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");

            if (avctx->err_recognition & AV_EF_EXPLODE)

                goto fail;

        }

        avctx->internal->pkt = &tmp;

        if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)

            ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,

                                         &tmp);

        else {

            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,

                                       &tmp);

            picture->pkt_dts = avpkt->dts;

            if(!avctx->has_b_frames){

                av_frame_set_pkt_pos(picture, avpkt->pos);

            }

            //FIXME these should be under if(!avctx->has_b_frames)

            /* get_buffer is supposed to set frame parameters */

            if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {

                if (!picture->sample_aspect_ratio.num)    picture->sample_aspect_ratio = avctx->sample_aspect_ratio;

                if (!picture->width)                      picture->width               = avctx->width;

                if (!picture->height)                     picture->height              = avctx->height;

                if (picture->format == AV_PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;

            }

        }

        add_metadata_from_side_data(avctx, picture);

fail:

        emms_c(); //needed to avoid an emms_c() call before every return;

        avctx->internal->pkt = NULL;

        if (did_split) {

            av_packet_free_side_data(&tmp);

            if(ret == tmp.size)

                ret = avpkt->size;

        }

        if (*got_picture_ptr) {

            if (!avctx->refcounted_frames) {

                int err = unrefcount_frame(avci, picture);

                if (err < 0)

                    return err;

            }

            avctx->frame_number++;

            av_frame_set_best_effort_timestamp(picture,

                                               guess_correct_pts(avctx,

                                                                 picture->pkt_pts,

                                                                 picture->pkt_dts));

        } else

            av_frame_unref(picture);

    } else

        ret = 0;

    /* many decoders assign whole AVFrames, thus overwriting extended_data;

     * make sure it's set correctly */

    picture->extended_data = picture->data;

    return ret;

}


static void blk_mig_cleanup(Monitor *mon)

{

    BlkMigDevState *bmds;

    BlkMigBlock *blk;

    set_dirty_tracking(0);

    while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {

        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);

        bdrv_set_in_use(bmds->bs, 0);

        drive_put_ref(drive_get_by_blockdev(bmds->bs));

        g_free(bmds->aio_bitmap);

        g_free(bmds);

    }

    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {

        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);

        g_free(blk->buf);

        g_free(blk);

    }

    monitor_printf(mon, "\n");

}


void ram_control_load_hook(QEMUFile *f, uint64_t flags)

{

    int ret = 0;

    if (f->ops->hook_ram_load) {

        ret = f->ops->hook_ram_load(f, f->opaque, flags);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

        }

    } else {

        qemu_file_set_error(f, ret);

    }

}


static void usb_host_handle_destroy(USBDevice *udev)

{

    USBHostDevice *s = USB_HOST_DEVICE(udev);

    qemu_remove_exit_notifier(&s->exit);

    QTAILQ_REMOVE(&hostdevs, s, next);

    usb_host_close(s);

}


static void *qpa_thread_out (void *arg)

{

    PAVoiceOut *pa = arg;

    HWVoiceOut *hw = &pa->hw;

    int threshold;

    threshold = conf.divisor ? hw->samples / conf.divisor : 0;

    if (audio_pt_lock (&pa->pt, AUDIO_FUNC)) {

        return NULL;

    }

    for (;;) {

        int decr, to_mix, rpos;

        for (;;) {

            if (pa->done) {

                goto exit;

            }

            if (pa->live > threshold) {

                break;

            }

            if (audio_pt_wait (&pa->pt, AUDIO_FUNC)) {

                goto exit;

            }

        }

        decr = to_mix = pa->live;

        rpos = hw->rpos;

        if (audio_pt_unlock (&pa->pt, AUDIO_FUNC)) {

            return NULL;

        }

        while (to_mix) {

            int error;

            int chunk = audio_MIN (to_mix, hw->samples - rpos);

            struct st_sample *src = hw->mix_buf + rpos;

            hw->clip (pa->pcm_buf, src, chunk);

            if (pa_simple_write (pa->s, pa->pcm_buf,

                                 chunk << hw->info.shift, &error) < 0) {

                qpa_logerr (error, "pa_simple_write failed\n");

                return NULL;

            }

            rpos = (rpos + chunk) % hw->samples;

            to_mix -= chunk;

        }

        if (audio_pt_lock (&pa->pt, AUDIO_FUNC)) {

            return NULL;

        }

        pa->live = 0;

        pa->rpos = rpos;

        pa->decr += decr;

    }

 exit:

    audio_pt_unlock (&pa->pt, AUDIO_FUNC);

    return NULL;

}


static void bench_undrained_flush_cb(void *opaque, int ret)

{

    if (ret < 0) {

        error_report("Failed flush request: %s\n", strerror(-ret));

        exit(EXIT_FAILURE);

    }

}


static uint32_t nabm_readw (void *opaque, uint32_t addr)

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    AC97BusMasterRegs *r = NULL;

    uint32_t index = addr - s->base[1];

    uint32_t val = ~0U;

    switch (index) {

    case PI_SR:

    case PO_SR:

    case MC_SR:

        r = &s->bm_regs[GET_BM (index)];

        val = r->sr;

        dolog ("SR[%d] -> %#x\n", GET_BM (index), val);

        break;

    case PI_PICB:

    case PO_PICB:

    case MC_PICB:

        r = &s->bm_regs[GET_BM (index)];

        val = r->picb;

        dolog ("PICB[%d] -> %#x\n", GET_BM (index), val);

        break;

    default:

        dolog ("U nabm readw %#x -> %#x\n", addr, val);

        break;

    }

    return val;

}


static int ehci_state_executing(EHCIQueue *q, int async)

{

    int again = 0;

    int reload, nakcnt;

    ehci_execute_complete(q);

    if (q->usb_status == USB_RET_ASYNC) {

        goto out;

    }

    if (q->usb_status == USB_RET_PROCERR) {

        again = -1;

        goto out;

    }

    // 4.10.3

    if (!async) {

        int transactCtr = get_field(q->qh.epcap, QH_EPCAP_MULT);

        transactCtr--;

        set_field(&q->qh.epcap, transactCtr, QH_EPCAP_MULT);

        // 4.10.3, bottom of page 82, should exit this state when transaction

        // counter decrements to 0

    }

    reload = get_field(q->qh.epchar, QH_EPCHAR_RL);

    if (reload) {

        nakcnt = get_field(q->qh.altnext_qtd, QH_ALTNEXT_NAKCNT);

        if (q->usb_status == USB_RET_NAK) {

            if (nakcnt) {

                nakcnt--;

            }

        } else {

            nakcnt = reload;

        }

        set_field(&q->qh.altnext_qtd, nakcnt, QH_ALTNEXT_NAKCNT);

    }

    /* 4.10.5 */

    if ((q->usb_status == USB_RET_NAK) || (q->qh.token & QTD_TOKEN_ACTIVE)) {

        ehci_set_state(q->ehci, async, EST_HORIZONTALQH);

    } else {

        ehci_set_state(q->ehci, async, EST_WRITEBACK);

    }

    again = 1;

out:

    ehci_flush_qh(q);

    return again;

}


static void gd_change_page(GtkNotebook *nb, gpointer arg1, guint arg2,

                           gpointer data)

{

    GtkDisplayState *s = data;

    VirtualConsole *vc;

    gboolean on_vga;

    if (!gtk_widget_get_realized(s->notebook)) {

        return;

    }

    vc = gd_vc_find_by_page(s, arg2);

    if (!vc) {

        return;

    }

    gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(vc->menu_item),

                                   TRUE);

    on_vga = (vc->type == GD_VC_GFX);

    if (!on_vga) {

        gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(s->grab_item),

                                       FALSE);

    } else if (s->full_screen) {

        gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(s->grab_item),

                                       TRUE);

    }

    gtk_widget_set_sensitive(s->grab_item, on_vga);

    gd_update_cursor(vc);

}


static void address_space_update_topology(AddressSpace *as)

{

    FlatView *old_view = as->current_map;

    FlatView *new_view = generate_memory_topology(as->root);

    address_space_update_topology_pass(as, old_view, new_view, false);

    address_space_update_topology_pass(as, old_view, new_view, true);

    as->current_map = new_view;

    flatview_destroy(old_view);

    address_space_update_ioeventfds(as);

}


static void ptimer_reload(ptimer_state *s)

{

    if (s->delta == 0) {

        ptimer_trigger(s);

        s->delta = s->limit;

    }

    if (s->delta == 0 || s->period == 0) {

        fprintf(stderr, "Timer with period zero, disabling\n");

        s->enabled = 0;

        return;

    }

    s->last_event = s->next_event;

    s->next_event = s->last_event + s->delta * s->period;

    if (s->period_frac) {

        s->next_event += ((int64_t)s->period_frac * s->delta) >> 32;

    }

    timer_mod(s->timer, s->next_event);

}


static int init(AVFilterContext *ctx, const char *args, void *opaque)

{

    GraphContext *gctx = ctx->priv;

    if(!args)

        return 0;

    if(!(gctx->link_filter = avfilter_open(&vf_graph_dummy, NULL)))

        return -1;

    if(avfilter_init_filter(gctx->link_filter, NULL, ctx))

        goto fail;

    return graph_load_chain_from_string(ctx, args, NULL, NULL);

fail:

    avfilter_destroy(gctx->link_filter);

    return -1;

}


void kvm_arch_init_irq_routing(KVMState *s)

{

    if (!kvm_check_extension(s, KVM_CAP_IRQ_ROUTING)) {

        /* If kernel can't do irq routing, interrupt source

         * override 0->2 cannot be set up as required by HPET.

         * So we have to disable it.

         */

        no_hpet = 1;

    }

    /* We know at this point that we're using the in-kernel

     * irqchip, so we can use irqfds, and on x86 we know

     * we can use msi via irqfd and GSI routing.

     */

    kvm_irqfds_allowed = true;

    kvm_msi_via_irqfd_allowed = true;

    kvm_gsi_routing_allowed = true;

}


static void output_visitor_test_add(const char *testpath,

                                    TestOutputVisitorData *data,

                                    void (*test_func)(TestOutputVisitorData *data, const void *user_data))

{

    g_test_add(testpath, TestOutputVisitorData, data, visitor_output_setup,

               test_func, visitor_output_teardown);

}


void cpu_loop (CPUState *env)

{

    int trapnr;

    target_siginfo_t info;

    while (1) {

        trapnr = cpu_alpha_exec (env);

        switch (trapnr) {

        case EXCP_RESET:

            fprintf(stderr, "Reset requested. Exit\n");

            exit(1);

            break;

        case EXCP_MCHK:

            fprintf(stderr, "Machine check exception. Exit\n");

            exit(1);

            break;

        case EXCP_ARITH:

            fprintf(stderr, "Arithmetic trap.\n");

            exit(1);

            break;

        case EXCP_HW_INTERRUPT:

            fprintf(stderr, "External interrupt. Exit\n");

            exit(1);

            break;

        case EXCP_DFAULT:

            fprintf(stderr, "MMU data fault\n");

            exit(1);

            break;

        case EXCP_DTB_MISS_PAL:

            fprintf(stderr, "MMU data TLB miss in PALcode\n");

            exit(1);

            break;

        case EXCP_ITB_MISS:

            fprintf(stderr, "MMU instruction TLB miss\n");

            exit(1);

            break;

        case EXCP_ITB_ACV:

            fprintf(stderr, "MMU instruction access violation\n");

            exit(1);

            break;

        case EXCP_DTB_MISS_NATIVE:

            fprintf(stderr, "MMU data TLB miss\n");

            exit(1);

            break;

        case EXCP_UNALIGN:

            fprintf(stderr, "Unaligned access\n");

            exit(1);

            break;

        case EXCP_OPCDEC:

            fprintf(stderr, "Invalid instruction\n");

            exit(1);

            break;

        case EXCP_FEN:

            fprintf(stderr, "Floating-point not allowed\n");

            exit(1);

            break;

        case EXCP_CALL_PAL ... (EXCP_CALL_PALP - 1):

            call_pal(env, (trapnr >> 6) | 0x80);

            break;

        case EXCP_CALL_PALP ... (EXCP_CALL_PALE - 1):

            fprintf(stderr, "Privileged call to PALcode\n");

            exit(1);

            break;

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig (env, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

                    queue_signal(env, info.si_signo, &info);

                  }

            }

            break;

        default:

            printf ("Unhandled trap: 0x%x\n", trapnr);

            cpu_dump_state(env, stderr, fprintf, 0);

            exit (1);

        }

        process_pending_signals (env);

    }

}


int rom_load_all(void)

{

    target_phys_addr_t addr = 0;

    MemoryRegionSection section;

    Rom *rom;

    QTAILQ_FOREACH(rom, &roms, next) {

        if (rom->fw_file) {

            continue;

        }

        if (addr > rom->addr) {

            fprintf(stderr, "rom: requested regions overlap "

                    "(rom %s. free=0x" TARGET_FMT_plx

                    ", addr=0x" TARGET_FMT_plx ")\n",

                    rom->name, addr, rom->addr);

            return -1;

        }

        addr  = rom->addr;

        addr += rom->romsize;

        section = memory_region_find(get_system_memory(), rom->addr, 1);

        rom->isrom = section.size && memory_region_is_rom(section.mr);

    }

    qemu_register_reset(rom_reset, NULL);

    roms_loaded = 1;

    return 0;

}


static int alsa_init_in (HWVoiceIn *hw, audsettings_t *as)

{

    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;

    struct alsa_params_req req;

    struct alsa_params_obt obt;

    snd_pcm_t *handle;

    audsettings_t obt_as;

    req.fmt = aud_to_alsafmt (as->fmt);

    req.freq = as->freq;

    req.nchannels = as->nchannels;

    req.period_size = conf.period_size_in;

    req.buffer_size = conf.buffer_size_in;

    req.size_in_usec = conf.size_in_usec_in;

    req.override_mask = !!conf.period_size_in_overridden

        | (!!conf.buffer_size_in_overridden << 1);

    if (alsa_open (1, &req, &obt, &handle)) {

        return -1;

    }

    obt_as.freq = obt.freq;

    obt_as.nchannels = obt.nchannels;

    obt_as.fmt = obt.fmt;

    obt_as.endianness = obt.endianness;

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = obt.samples;

    alsa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!alsa->pcm_buf) {

        dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",

               hw->samples, 1 << hw->info.shift);

        alsa_anal_close (&handle);

        return -1;

    }

    alsa->handle = handle;

    return 0;

}


static void rtas_power_off(sPAPREnvironment *spapr,

                           uint32_t token, uint32_t nargs, target_ulong args,

                           uint32_t nret, target_ulong rets)

{

    if (nargs != 2 || nret != 1) {

        rtas_st(rets, 0, -3);

        return;

    }

    qemu_system_shutdown_request();

    rtas_st(rets, 0, 0);

}


static uint64_t omap_id_read(void *opaque, target_phys_addr_t addr,

                             unsigned size)

{

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

    if (size != 4) {

        return omap_badwidth_read32(opaque, addr);

    }

    switch (addr) {

    case 0xfffe1800:	/* DIE_ID_LSB */

        return 0xc9581f0e;

    case 0xfffe1804:	/* DIE_ID_MSB */

        return 0xa8858bfa;

    case 0xfffe2000:	/* PRODUCT_ID_LSB */

        return 0x00aaaafc;

    case 0xfffe2004:	/* PRODUCT_ID_MSB */

        return 0xcafeb574;

    case 0xfffed400:	/* JTAG_ID_LSB */

        switch (s->mpu_model) {

        case omap310:

            return 0x03310315;

        case omap1510:

            return 0x03310115;

        default:

            hw_error("%s: bad mpu model\n", __FUNCTION__);

        }

        break;

    case 0xfffed404:	/* JTAG_ID_MSB */

        switch (s->mpu_model) {

        case omap310:

            return 0xfb57402f;

        case omap1510:

            return 0xfb47002f;

        default:

            hw_error("%s: bad mpu model\n", __FUNCTION__);

        }

        break;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


ram_addr_t xen_ram_addr_from_mapcache(void *ptr)

{

    MapCacheEntry *entry = NULL;

    MapCacheRev *reventry;

    hwaddr paddr_index;

    hwaddr size;

    int found = 0;

    QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {

        if (reventry->vaddr_req == ptr) {

            paddr_index = reventry->paddr_index;

            size = reventry->size;

            found = 1;

            break;

        }

    }

    if (!found) {

        fprintf(stderr, "%s, could not find %p\n", __func__, ptr);

        QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {

            DPRINTF("   "TARGET_FMT_plx" -> %p is present\n", reventry->paddr_index,

                    reventry->vaddr_req);

        }

        abort();

        return 0;

    }

    entry = &mapcache->entry[paddr_index % mapcache->nr_buckets];

    while (entry && (entry->paddr_index != paddr_index || entry->size != size)) {

        entry = entry->next;

    }

    if (!entry) {

        DPRINTF("Trying to find address %p that is not in the mapcache!\n", ptr);

        return 0;

    }

    return (reventry->paddr_index << MCACHE_BUCKET_SHIFT) +

        ((unsigned long) ptr - (unsigned long) entry->vaddr_base);

}


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

                        unsigned size)

{

    MilkymistHpdmcState *s = opaque;

    trace_milkymist_hpdmc_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_SYSTEM:

    case R_BYPASS:

    case R_TIMING:

        s->regs[addr] = value;

        break;

    case R_IODELAY:

        /* ignore writes */

        break;

    default:

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

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


static int write_elf32_note(DumpState *s)

{

    target_phys_addr_t begin = s->memory_offset - s->note_size;

    Elf32_Phdr phdr;

    int endian = s->dump_info.d_endian;

    int ret;

    memset(&phdr, 0, sizeof(Elf32_Phdr));

    phdr.p_type = cpu_convert_to_target32(PT_NOTE, endian);

    phdr.p_offset = cpu_convert_to_target32(begin, endian);

    phdr.p_paddr = 0;

    phdr.p_filesz = cpu_convert_to_target32(s->note_size, endian);

    phdr.p_memsz = cpu_convert_to_target32(s->note_size, endian);

    phdr.p_vaddr = 0;

    ret = fd_write_vmcore(&phdr, sizeof(Elf32_Phdr), s);

    if (ret < 0) {

        dump_error(s, "dump: failed to write program header table.\n");

        return -1;

    }

    return 0;

}


int rom_add_vga(const char *file)

{

    if (!rom_enable_driver_roms)

        return 0;

    return rom_add_file(file, "vgaroms", file, 0);

}


static void external_snapshot_prepare(BlkActionState *common,

                                      Error **errp)

{

    int flags = 0, ret;

    QDict *options = NULL;

    Error *local_err = NULL;

    /* Device and node name of the image to generate the snapshot from */

    const char *device;

    const char *node_name;

    /* Reference to the new image (for 'blockdev-snapshot') */

    const char *snapshot_ref;

    /* File name of the new image (for 'blockdev-snapshot-sync') */

    const char *new_image_file;

    ExternalSnapshotState *state =

                             DO_UPCAST(ExternalSnapshotState, common, common);

    TransactionAction *action = common->action;

    /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar

     * purpose but a different set of parameters */

    switch (action->type) {

    case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:

        {

            BlockdevSnapshot *s = action->u.blockdev_snapshot;

            device = s->node;

            node_name = s->node;

            new_image_file = NULL;

            snapshot_ref = s->overlay;

        }

        break;

    case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:

        {

            BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;

            device = s->has_device ? s->device : NULL;

            node_name = s->has_node_name ? s->node_name : NULL;

            new_image_file = s->snapshot_file;

            snapshot_ref = NULL;

        }

        break;

    default:

        g_assert_not_reached();

    }

    /* start processing */

    if (action_check_completion_mode(common, errp) < 0) {

        return;

    }

    state->old_bs = bdrv_lookup_bs(device, node_name, errp);

    if (!state->old_bs) {

        return;

    }

    /* Acquire AioContext now so any threads operating on old_bs stop */

    state->aio_context = bdrv_get_aio_context(state->old_bs);

    aio_context_acquire(state->aio_context);

    bdrv_drained_begin(state->old_bs);

    if (!bdrv_is_inserted(state->old_bs)) {

        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (bdrv_op_is_blocked(state->old_bs,

                           BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {

        return;

    }

    if (!bdrv_is_read_only(state->old_bs)) {

        if (bdrv_flush(state->old_bs)) {

            error_setg(errp, QERR_IO_ERROR);

            return;

        }

    }

    if (!bdrv_is_first_non_filter(state->old_bs)) {

        error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");

        return;

    }

    if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {

        BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;

        const char *format = s->has_format ? s->format : "qcow2";

        enum NewImageMode mode;

        const char *snapshot_node_name =

            s->has_snapshot_node_name ? s->snapshot_node_name : NULL;

        if (node_name && !snapshot_node_name) {

            error_setg(errp, "New snapshot node name missing");

            return;

        }

        if (snapshot_node_name &&

            bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {

            error_setg(errp, "New snapshot node name already in use");

            return;

        }

        flags = state->old_bs->open_flags;

        /* create new image w/backing file */

        mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;

        if (mode != NEW_IMAGE_MODE_EXISTING) {

            int64_t size = bdrv_getlength(state->old_bs);

            if (size < 0) {

                error_setg_errno(errp, -size, "bdrv_getlength failed");

                return;

            }

            bdrv_img_create(new_image_file, format,

                            state->old_bs->filename,

                            state->old_bs->drv->format_name,

                            NULL, size, flags, &local_err, false);

            if (local_err) {

                error_propagate(errp, local_err);

                return;

            }

        }

        options = qdict_new();

        if (s->has_snapshot_node_name) {

            qdict_put(options, "node-name",

                      qstring_from_str(snapshot_node_name));

        }

        qdict_put(options, "driver", qstring_from_str(format));

        flags |= BDRV_O_NO_BACKING;

    }

    assert(state->new_bs == NULL);

    ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,

                    flags, errp);

    /* We will manually add the backing_hd field to the bs later */

    if (ret != 0) {

        return;

    }

    if (state->new_bs->blk != NULL) {

        error_setg(errp, "The snapshot is already in use by %s",

                   blk_name(state->new_bs->blk));

        return;

    }

    if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,

                           errp)) {

        return;

    }

    if (state->new_bs->backing != NULL) {

        error_setg(errp, "The snapshot already has a backing image");

        return;

    }

    if (!state->new_bs->drv->supports_backing) {

        error_setg(errp, "The snapshot does not support backing images");

    }

}


void helper_ldl_data(uint64_t t0, uint64_t t1)

{

    ldl_data(t1, t0);

}