int ff_h263_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                         AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MpegEncContext *s  = avctx->priv_data;

    int ret;

    AVFrame *pict = data;

    s->flags  = avctx->flags;

    s->flags2 = avctx->flags2;

    /* no supplementary picture */

    if (buf_size == 0) {

        /* special case for last picture */

        if (s->low_delay == 0 && s->next_picture_ptr) {

            if ((ret = av_frame_ref(pict, &s->next_picture_ptr->f)) < 0)

                return ret;

            s->next_picture_ptr = NULL;

            *got_frame = 1;

        }

        return 0;

    }

    if (s->flags & CODEC_FLAG_TRUNCATED) {

        int next;

        if (CONFIG_MPEG4_DECODER && s->codec_id == AV_CODEC_ID_MPEG4) {

            next = ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);

        } else if (CONFIG_H263_DECODER && s->codec_id == AV_CODEC_ID_H263) {

            next = ff_h263_find_frame_end(&s->parse_context, buf, buf_size);

        } else {

            av_log(s->avctx, AV_LOG_ERROR,

                   "this codec does not support truncated bitstreams\n");

            return AVERROR(ENOSYS);

        }

        if (ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf,

                             &buf_size) < 0)

            return buf_size;

    }

    if (s->bitstream_buffer_size && (s->divx_packed || buf_size < 20)) // divx 5.01+/xvid frame reorder

        ret = init_get_bits8(&s->gb, s->bitstream_buffer,

                             s->bitstream_buffer_size);

    else

        ret = init_get_bits8(&s->gb, buf, buf_size);

    s->bitstream_buffer_size = 0;

    if (ret < 0)

        return ret;

    if (!s->context_initialized)

        // we need the idct permutaton for reading a custom matrix

        if ((ret = ff_MPV_common_init(s)) < 0)

            return ret;

    /* We need to set current_picture_ptr before reading the header,

     * otherwise we cannot store anyting in there */

    if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {

        int i = ff_find_unused_picture(s, 0);

        if (i < 0)

            return i;

        s->current_picture_ptr = &s->picture[i];

    }

    /* let's go :-) */

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) {

        ret = ff_wmv2_decode_picture_header(s);

    } else if (CONFIG_MSMPEG4_DECODER && s->msmpeg4_version) {

        ret = ff_msmpeg4_decode_picture_header(s);

    } else if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4) {

        if (s->avctx->extradata_size && s->picture_number == 0) {

            GetBitContext gb;

            ret = init_get_bits8(&gb, s->avctx->extradata,

                                 s->avctx->extradata_size);

            if (ret < 0)

                return ret;

            ff_mpeg4_decode_picture_header(avctx->priv_data, &gb);

        }

        ret = ff_mpeg4_decode_picture_header(avctx->priv_data, &s->gb);

    } else if (CONFIG_H263I_DECODER && s->codec_id == AV_CODEC_ID_H263I) {

        ret = ff_intel_h263_decode_picture_header(s);

    } else if (CONFIG_FLV_DECODER && s->h263_flv) {

        ret = ff_flv_decode_picture_header(s);

    } else {

        ret = ff_h263_decode_picture_header(s);

    }

    if (ret == FRAME_SKIPPED)

        return get_consumed_bytes(s, buf_size);

    /* skip if the header was thrashed */

    if (ret < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");

        return ret;

    }

    avctx->has_b_frames = !s->low_delay;

#define SET_QPEL_FUNC(postfix1, postfix2)                           \

    s->dsp.put_        ## postfix1 = ff_put_        ## postfix2;    \

    s->dsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;    \

    s->dsp.avg_        ## postfix1 = ff_avg_        ## postfix2;

    if (s->workaround_bugs & FF_BUG_STD_QPEL) {

        SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)

    }

    /* After H263 & mpeg4 header decode we have the height, width,

     * and other parameters. So then we could init the picture.

     * FIXME: By the way H263 decoder is evolving it should have

     * an H263EncContext */

    if (s->width  != avctx->coded_width  ||

        s->height != avctx->coded_height ||

        s->context_reinit) {

        /* H.263 could change picture size any time */

        s->context_reinit = 0;

        ret = ff_set_dimensions(avctx, s->width, s->height);

        if (ret < 0)

            return ret;

        if ((ret = ff_MPV_common_frame_size_change(s)))

            return ret;

    }

    if (s->codec_id == AV_CODEC_ID_H263  ||

        s->codec_id == AV_CODEC_ID_H263P ||

        s->codec_id == AV_CODEC_ID_H263I)

        s->gob_index = ff_h263_get_gob_height(s);

    // for skipping the frame

    s->current_picture.f.pict_type = s->pict_type;

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    /* skip B-frames if we don't have reference frames */

    if (s->last_picture_ptr == NULL &&

        (s->pict_type == AV_PICTURE_TYPE_B || s->droppable))

        return get_consumed_bytes(s, buf_size);

    if ((avctx->skip_frame >= AVDISCARD_NONREF &&

         s->pict_type == AV_PICTURE_TYPE_B)    ||

        (avctx->skip_frame >= AVDISCARD_NONKEY &&

         s->pict_type != AV_PICTURE_TYPE_I)    ||

        avctx->skip_frame >= AVDISCARD_ALL)

        return get_consumed_bytes(s, buf_size);

    if (s->next_p_frame_damaged) {

        if (s->pict_type == AV_PICTURE_TYPE_B)

            return get_consumed_bytes(s, buf_size);

        else

            s->next_p_frame_damaged = 0;

    }

    if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {

        s->me.qpel_put = s->dsp.put_qpel_pixels_tab;

        s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;

    } else {

        s->me.qpel_put = s->dsp.put_no_rnd_qpel_pixels_tab;

        s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;

    }

    if ((ret = ff_MPV_frame_start(s, avctx)) < 0)

        return ret;

    if (!s->divx_packed && !avctx->hwaccel)

        ff_thread_finish_setup(avctx);

    if (avctx->hwaccel) {

        ret = avctx->hwaccel->start_frame(avctx, s->gb.buffer,

                                          s->gb.buffer_end - s->gb.buffer);

        if (ret < 0 )

            return ret;

    }

    ff_mpeg_er_frame_start(s);

    /* the second part of the wmv2 header contains the MB skip bits which

     * are stored in current_picture->mb_type which is not available before

     * ff_MPV_frame_start() */

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version == 5) {

        ret = ff_wmv2_decode_secondary_picture_header(s);

        if (ret < 0)

            return ret;

        if (ret == 1)

            goto intrax8_decoded;

    }

    /* decode each macroblock */

    s->mb_x = 0;

    s->mb_y = 0;

    ret = decode_slice(s);

    while (s->mb_y < s->mb_height) {

        if (s->msmpeg4_version) {

            if (s->slice_height == 0 || s->mb_x != 0 ||

                (s->mb_y % s->slice_height) != 0 || get_bits_left(&s->gb) < 0)

                break;

        } else {

            int prev_x = s->mb_x, prev_y = s->mb_y;

            if (ff_h263_resync(s) < 0)

                break;

            if (prev_y * s->mb_width + prev_x < s->mb_y * s->mb_width + s->mb_x)

                s->er.error_occurred = 1;

        }

        if (s->msmpeg4_version < 4 && s->h263_pred)

            ff_mpeg4_clean_buffers(s);

        if (decode_slice(s) < 0)

            ret = AVERROR_INVALIDDATA;

    }

    if (s->msmpeg4_version && s->msmpeg4_version < 4 &&

        s->pict_type == AV_PICTURE_TYPE_I)

        if (!CONFIG_MSMPEG4_DECODER ||

            ff_msmpeg4_decode_ext_header(s, buf_size) < 0)

            s->er.error_status_table[s->mb_num - 1] = ER_MB_ERROR;

    assert(s->bitstream_buffer_size == 0);

    if (CONFIG_MPEG4_DECODER && avctx->codec_id == AV_CODEC_ID_MPEG4)

        ff_mpeg4_frame_end(avctx, buf, buf_size);

intrax8_decoded:

    ff_er_frame_end(&s->er);

    if (avctx->hwaccel) {

        ret = avctx->hwaccel->end_frame(avctx);

        if (ret < 0)

            return ret;

    }

    ff_MPV_frame_end(s);

    if (!s->divx_packed && avctx->hwaccel)

        ff_thread_finish_setup(avctx);

    assert(s->current_picture.f.pict_type ==

           s->current_picture_ptr->f.pict_type);

    assert(s->current_picture.f.pict_type == s->pict_type);

    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {

        if ((ret = av_frame_ref(pict, &s->current_picture_ptr->f)) < 0)

            return ret;

        ff_print_debug_info(s, s->current_picture_ptr);

    } else if (s->last_picture_ptr != NULL) {

        if ((ret = av_frame_ref(pict, &s->last_picture_ptr->f)) < 0)

            return ret;

        ff_print_debug_info(s, s->last_picture_ptr);

    }

    if (s->last_picture_ptr || s->low_delay)

        *got_frame = 1;

    if (ret && (avctx->err_recognition & AV_EF_EXPLODE))

        return ret;

    else

        return get_consumed_bytes(s, buf_size);

}


void sm501_init(MemoryRegion *address_space_mem, uint32_t base,

                uint32_t local_mem_bytes, qemu_irq irq, CharDriverState *chr)

{

    SM501State * s;

    DeviceState *dev;

    MemoryRegion *sm501_system_config = g_new(MemoryRegion, 1);

    MemoryRegion *sm501_disp_ctrl = g_new(MemoryRegion, 1);

    MemoryRegion *sm501_2d_engine = g_new(MemoryRegion, 1);

    /* allocate management data region */

    s = (SM501State *)g_malloc0(sizeof(SM501State));

    s->base = base;

    s->local_mem_size_index

	= get_local_mem_size_index(local_mem_bytes);

    SM501_DPRINTF("local mem size=%x. index=%d\n", get_local_mem_size(s),

		  s->local_mem_size_index);

    s->system_control = 0x00100000;

    s->misc_control = 0x00001000; /* assumes SH, active=low */

    s->dc_panel_control = 0x00010000;

    s->dc_crt_control = 0x00010000;

    /* allocate local memory */

    memory_region_init_ram(&s->local_mem_region, NULL, "sm501.local",

                           local_mem_bytes, &error_abort);

    vmstate_register_ram_global(&s->local_mem_region);

    memory_region_set_log(&s->local_mem_region, true, DIRTY_MEMORY_VGA);

    s->local_mem = memory_region_get_ram_ptr(&s->local_mem_region);

    memory_region_add_subregion(address_space_mem, base, &s->local_mem_region);

    /* map mmio */

    memory_region_init_io(sm501_system_config, NULL, &sm501_system_config_ops, s,

                          "sm501-system-config", 0x6c);

    memory_region_add_subregion(address_space_mem, base + MMIO_BASE_OFFSET,

                                sm501_system_config);

    memory_region_init_io(sm501_disp_ctrl, NULL, &sm501_disp_ctrl_ops, s,

                          "sm501-disp-ctrl", 0x1000);

    memory_region_add_subregion(address_space_mem,

                                base + MMIO_BASE_OFFSET + SM501_DC,

                                sm501_disp_ctrl);

    memory_region_init_io(sm501_2d_engine, NULL, &sm501_2d_engine_ops, s,

                          "sm501-2d-engine", 0x54);

    memory_region_add_subregion(address_space_mem,

                                base + MMIO_BASE_OFFSET + SM501_2D_ENGINE,

                                sm501_2d_engine);

    /* bridge to usb host emulation module */

    dev = qdev_create(NULL, "sysbus-ohci");

    qdev_prop_set_uint32(dev, "num-ports", 2);

    qdev_prop_set_uint64(dev, "dma-offset", base);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0,

                    base + MMIO_BASE_OFFSET + SM501_USB_HOST);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq);

    /* bridge to serial emulation module */

    if (chr) {

        serial_mm_init(address_space_mem,

                       base + MMIO_BASE_OFFSET + SM501_UART0, 2,

                       NULL, /* TODO : chain irq to IRL */

                       115200, chr, DEVICE_NATIVE_ENDIAN);

    }

    /* create qemu graphic console */

    s->con = graphic_console_init(DEVICE(dev), 0, &sm501_ops, s);

}


static void nbd_parse_filename(const char *filename, QDict *options,

                               Error **errp)

{

    char *file;

    char *export_name;

    const char *host_spec;

    const char *unixpath;

    if (qdict_haskey(options, "host")

        || qdict_haskey(options, "port")

        || qdict_haskey(options, "path"))

    {

        error_setg(errp, "host/port/path and a file name may not be specified "

                         "at the same time");

        return;

    }

    if (strstr(filename, "://")) {

        int ret = nbd_parse_uri(filename, options);

        if (ret < 0) {

            error_setg(errp, "No valid URL specified");

        }

        return;

    }

    file = g_strdup(filename);

    export_name = strstr(file, EN_OPTSTR);

    if (export_name) {

        if (export_name[strlen(EN_OPTSTR)] == 0) {

            goto out;

        }

        export_name[0] = 0; /* truncate 'file' */

        export_name += strlen(EN_OPTSTR);

        qdict_put(options, "export", qstring_from_str(export_name));

    }

    /* extract the host_spec - fail if it's not nbd:... */

    if (!strstart(file, "nbd:", &host_spec)) {

        error_setg(errp, "File name string for NBD must start with 'nbd:'");

        goto out;

    }

    if (!*host_spec) {

        goto out;

    }

    /* are we a UNIX or TCP socket? */

    if (strstart(host_spec, "unix:", &unixpath)) {

        qdict_put(options, "path", qstring_from_str(unixpath));

    } else {

        InetSocketAddress *addr = NULL;

        addr = inet_parse(host_spec, errp);

        if (error_is_set(errp)) {

            goto out;

        }

        qdict_put(options, "host", qstring_from_str(addr->host));

        qdict_put(options, "port", qstring_from_str(addr->port));

        qapi_free_InetSocketAddress(addr);

    }

out:

    g_free(file);

}


static int64_t get_pts(const char **buf, int *duration,

                       int32_t *x1, int32_t *y1, int32_t *x2, int32_t *y2)

{

    int i;

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

        int hh1, mm1, ss1, ms1;

        int hh2, mm2, ss2, ms2;

        if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d"

                   "%*[ ]X1:%u X2:%u Y1:%u Y2:%u",

                   &hh1, &mm1, &ss1, &ms1,

                   &hh2, &mm2, &ss2, &ms2,

                   x1, x2, y1, y2) >= 8) {

            int64_t start = (hh1*3600LL + mm1*60LL + ss1) * 1000LL + ms1;

            int64_t end   = (hh2*3600LL + mm2*60LL + ss2) * 1000LL + ms2;

            *duration = end - start;

            *buf += strcspn(*buf, "\n") + 1;

            return start;

        }

        *buf += strcspn(*buf, "\n") + 1;

    }

    return AV_NOPTS_VALUE;

}


static int handle_hypercall(CPUState *env, struct kvm_run *run)

{

    int r;

    cpu_synchronize_state(env);

    r = s390_virtio_hypercall(env);

    kvm_arch_put_registers(env);

    return r;

}


static void disas_ldst_reg_imm9(DisasContext *s, uint32_t insn,

                                int opc,

                                int size,

                                int rt,

                                bool is_vector)

{

    int rn = extract32(insn, 5, 5);

    int imm9 = sextract32(insn, 12, 9);

    int idx = extract32(insn, 10, 2);

    bool is_signed = false;

    bool is_store = false;

    bool is_extended = false;

    bool is_unpriv = (idx == 2);

    bool iss_valid = !is_vector;

    bool post_index;

    bool writeback;

    TCGv_i64 tcg_addr;

    if (is_vector) {

        size |= (opc & 2) << 1;

        if (size > 4 || is_unpriv) {

            unallocated_encoding(s);

            return;

        }

        is_store = ((opc & 1) == 0);

        if (!fp_access_check(s)) {

            return;

        }

    } else {

        if (size == 3 && opc == 2) {

            /* PRFM - prefetch */

            if (is_unpriv) {

                unallocated_encoding(s);

                return;

            }

            return;

        }

        if (opc == 3 && size > 1) {

            unallocated_encoding(s);

            return;

        }

        is_store = (opc == 0);

        is_signed = extract32(opc, 1, 1);

        is_extended = (size < 3) && extract32(opc, 0, 1);

    }

    switch (idx) {

    case 0:

    case 2:

        post_index = false;

        writeback = false;

        break;

    case 1:

        post_index = true;

        writeback = true;

        break;

    case 3:

        post_index = false;

        writeback = true;

        break;

    }

    if (rn == 31) {

        gen_check_sp_alignment(s);

    }

    tcg_addr = read_cpu_reg_sp(s, rn, 1);

    if (!post_index) {

        tcg_gen_addi_i64(tcg_addr, tcg_addr, imm9);

    }

    if (is_vector) {

        if (is_store) {

            do_fp_st(s, rt, tcg_addr, size);

        } else {

            do_fp_ld(s, rt, tcg_addr, size);

        }

    } else {

        TCGv_i64 tcg_rt = cpu_reg(s, rt);

        int memidx = is_unpriv ? get_a64_user_mem_index(s) : get_mem_index(s);

        bool iss_sf = disas_ldst_compute_iss_sf(size, is_signed, opc);

        if (is_store) {

            do_gpr_st_memidx(s, tcg_rt, tcg_addr, size, memidx,

                             iss_valid, rt, iss_sf, false);

        } else {

            do_gpr_ld_memidx(s, tcg_rt, tcg_addr, size,

                             is_signed, is_extended, memidx,

                             iss_valid, rt, iss_sf, false);

        }

    }

    if (writeback) {

        TCGv_i64 tcg_rn = cpu_reg_sp(s, rn);

        if (post_index) {

            tcg_gen_addi_i64(tcg_addr, tcg_addr, imm9);

        }

        tcg_gen_mov_i64(tcg_rn, tcg_addr);

    }

}


static int hevc_find_frame_end(AVCodecParserContext *s, const uint8_t *buf,

                               int buf_size)

{

    HEVCParserContext *ctx = s->priv_data;

    ParseContext       *pc = &ctx->pc;

    int i;

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

        int nut;

        pc->state64 = (pc->state64 << 8) | buf[i];

        if (((pc->state64 >> 3 * 8) & 0xFFFFFF) != START_CODE)

            continue;

        nut = (pc->state64 >> 2 * 8 + 1) & 0x3F;

        // Beginning of access unit

        if ((nut >= HEVC_NAL_VPS && nut <= HEVC_NAL_AUD) || nut == HEVC_NAL_SEI_PREFIX ||

            (nut >= 41 && nut <= 44) || (nut >= 48 && nut <= 55)) {

            if (pc->frame_start_found) {

                pc->frame_start_found = 0;

                return i - 5;

            }

        } else if (nut <= HEVC_NAL_RASL_R ||

                   (nut >= HEVC_NAL_BLA_W_LP && nut <= HEVC_NAL_CRA_NUT)) {

            int first_slice_segment_in_pic_flag = buf[i] >> 7;

            if (first_slice_segment_in_pic_flag) {

                if (!pc->frame_start_found) {

                    pc->frame_start_found = 1;

                } else { // First slice of next frame found

                    pc->frame_start_found = 0;

                    return i - 5;

                }

            }

        }

    }

    return END_NOT_FOUND;

}


static void vnc_debug_gnutls_log(int level, const char* str) {

    VNC_DEBUG("%d %s", level, str);

}


static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)

{

    int pos = url_ftell(pb);

    put_be32(pb, 0); /* size */

    if(track->enc->codec_id == CODEC_ID_PCM_MULAW)

      put_tag(pb, "ulaw");

    else if(track->enc->codec_id == CODEC_ID_PCM_ALAW)

      put_tag(pb, "alaw");

    else if(track->enc->codec_id == CODEC_ID_ADPCM_IMA_QT)

      put_tag(pb, "ima4");

    else if(track->enc->codec_id == CODEC_ID_MACE3)

      put_tag(pb, "MAC3");

    else if(track->enc->codec_id == CODEC_ID_MACE6)

      put_tag(pb, "MAC6");

    else if(track->enc->codec_id == CODEC_ID_AAC)

      put_tag(pb, "mp4a");

    else if(track->enc->codec_id == CODEC_ID_AMR_NB)

      put_tag(pb, "samr");

    else

      put_tag(pb, "    ");

    put_be32(pb, 0); /* Reserved */

    put_be16(pb, 0); /* Reserved */

    put_be16(pb, 1); /* Data-reference index, XXX  == 1 */

    /* SoundDescription */

    put_be16(pb, 0); /* Version */

    put_be16(pb, 0); /* Revision level */

    put_be32(pb, 0); /* Reserved */

    put_be16(pb, track->enc->channels); /* Number of channels */

    /* TODO: Currently hard-coded to 16-bit, there doesn't seem

                 to be a good way to get number of bits of audio */

    put_be16(pb, 0x10); /* Reserved */

    put_be16(pb, 0); /* compression ID (= 0) */

    put_be16(pb, 0); /* packet size (= 0) */

    put_be16(pb, track->timescale); /* Time scale */

    put_be16(pb, 0); /* Reserved */

    if(track->enc->codec_id == CODEC_ID_AAC)

        mov_write_esds_tag(pb, track);

    if(track->enc->codec_id == CODEC_ID_AMR_NB)

        mov_write_damr_tag(pb);

    return updateSize (pb, pos);

}


static void usbredir_alt_setting_status(void *priv, uint32_t id,

    struct usb_redir_alt_setting_status_header *alt_setting_status)

{

    USBRedirDevice *dev = priv;

    AsyncURB *aurb;

    int len = 0;

    DPRINTF("alt status %d intf %d alt %d id: %u\n",

            alt_setting_status->status,

            alt_setting_status->interface,

            alt_setting_status->alt, id);

    aurb = async_find(dev, id);

    if (!aurb) {

        return;

    }

    if (aurb->packet) {

        if (aurb->get) {

            dev->dev.data_buf[0] = alt_setting_status->alt;

            len = 1;

        }

        aurb->packet->len =

            usbredir_handle_status(dev, alt_setting_status->status, len);

        usb_generic_async_ctrl_complete(&dev->dev, aurb->packet);

    }

    async_free(dev, aurb);

}


PPC_OP(setcrfbit)

{

    T1 = (T1 & PARAM(1)) | (T0 << PARAM(2));

    RETURN();

}


PPC_OP(test_ctr_false)

{

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

    RETURN();

}


void blk_io_limits_disable(BlockBackend *blk)

{

    assert(blk->public.throttle_group_member.throttle_state);

    bdrv_drained_begin(blk_bs(blk));

    throttle_group_unregister_tgm(&blk->public.throttle_group_member);

    bdrv_drained_end(blk_bs(blk));

}


void ff_framequeue_skip_samples(FFFrameQueue *fq, size_t samples, AVRational time_base)

{

    FFFrameBucket *b;

    size_t bytes;

    int planar, planes, i;

    check_consistency(fq);

    av_assert1(fq->queued);

    b = bucket(fq, 0);

    av_assert1(samples < b->frame->nb_samples);

    planar = av_sample_fmt_is_planar(b->frame->format);

    planes = planar ? b->frame->channels : 1;

    bytes = samples * av_get_bytes_per_sample(b->frame->format);

    if (!planar)

        bytes *= b->frame->channels;

    if (b->frame->pts != AV_NOPTS_VALUE)

        b->frame->pts += av_rescale_q(samples, av_make_q(1, b->frame->sample_rate), time_base);

    b->frame->nb_samples -= samples;

    b->frame->linesize[0] -= bytes;

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

        b->frame->extended_data[i] += bytes;

    for (i = 0; i < planes && i < AV_NUM_DATA_POINTERS; i++)

        b->frame->data[i] = b->frame->extended_data[i];

    fq->total_samples_tail += samples;

    ff_framequeue_update_peeked(fq, 0);

}


static void tcg_out_qemu_st(TCGContext *s, const TCGArg *args,
                            int opc)
{
    int addr_reg, data_reg, arg0, arg1, arg2, mem_index, s_bits;
#if defined(CONFIG_SOFTMMU)
    uint32_t *label1_ptr, *label2_ptr;
    data_reg = *args++;
    addr_reg = *args++;
    mem_index = *args;
    s_bits = opc;
    arg0 = TCG_REG_O0;
    arg1 = TCG_REG_O1;
    arg2 = TCG_REG_O2;
#if defined(CONFIG_SOFTMMU)
    /* srl addr_reg, x, arg1 */
    tcg_out_arithi(s, arg1, addr_reg, TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS,
                   SHIFT_SRL);
    tcg_out_arithi(s, arg0, addr_reg, TARGET_PAGE_MASK | ((1 << s_bits) - 1),
                   ARITH_AND);
    /* and arg1, x, arg1 */
    tcg_out_andi(s, arg1, (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS);
    /* add arg1, x, arg1 */
    tcg_out_addi(s, arg1, offsetof(CPUState,
                                   tlb_table[mem_index][0].addr_write));
    /* add env, arg1, arg1 */
    tcg_out_arith(s, arg1, TCG_AREG0, arg1, ARITH_ADD);
    /* ld [arg1], arg2 */
    tcg_out32(s, TARGET_LD_OP | INSN_RD(arg2) | INSN_RS1(arg1) |
              INSN_RS2(TCG_REG_G0));
    /* subcc arg0, arg2, %g0 */
    tcg_out_arith(s, TCG_REG_G0, arg0, arg2, ARITH_SUBCC);
    /* will become:
       be label1 */
    label1_ptr = (uint32_t *)s->code_ptr;
    tcg_out32(s, 0);
    /* mov (delay slot) */
    tcg_out_mov(s, arg0, addr_reg);
    /* mov */
    tcg_out_mov(s, arg1, data_reg);
    /* mov */
    tcg_out_movi(s, TCG_TYPE_I32, arg2, mem_index);
    /* XXX: move that code at the end of the TB */
    /* qemu_st_helper[s_bits](arg0, arg1, arg2) */
    tcg_out32(s, CALL | ((((tcg_target_ulong)qemu_st_helpers[s_bits]
                           - (tcg_target_ulong)s->code_ptr) >> 2)
                         & 0x3fffffff));
    /* Store AREG0 in stack to avoid ugly glibc bugs that mangle
       global registers */
    // delay slot
    tcg_out_ldst(s, TCG_AREG0, TCG_REG_CALL_STACK,
                 TCG_TARGET_CALL_STACK_OFFSET - sizeof(long), HOST_ST_OP);
    tcg_out_ldst(s, TCG_AREG0, TCG_REG_CALL_STACK,
                 TCG_TARGET_CALL_STACK_OFFSET - sizeof(long), HOST_LD_OP);
    /* will become:
       ba label2 */
    label2_ptr = (uint32_t *)s->code_ptr;
    tcg_out32(s, 0);
    /* nop (delay slot) */
    tcg_out_nop(s);
    /* label1: */
    *label1_ptr = (INSN_OP(0) | INSN_COND(COND_E, 0) | INSN_OP2(0x2) |
                   INSN_OFF22((unsigned long)s->code_ptr -
                              (unsigned long)label1_ptr));
    /* ld [arg1 + x], arg1 */
    tcg_out_ldst(s, arg1, arg1, offsetof(CPUTLBEntry, addend) -
                 offsetof(CPUTLBEntry, addr_write), HOST_LD_OP);
    /* add addr_reg, arg1, arg0 */
    tcg_out_arith(s, arg0, addr_reg, arg1, ARITH_ADD);
    arg0 = addr_reg;
    switch(opc) {
    case 0:
        /* stb data_reg, [arg0] */
        tcg_out_ldst(s, data_reg, arg0, 0, STB);
        break;
    case 1:
#ifdef TARGET_WORDS_BIGENDIAN
        /* sth data_reg, [arg0] */
        tcg_out_ldst(s, data_reg, arg0, 0, STH);
        /* stha data_reg, [arg0] ASI_PRIMARY_LITTLE */
        tcg_out_ldst_asi(s, data_reg, arg0, 0, STHA, ASI_PRIMARY_LITTLE);
        break;
    case 2:
#ifdef TARGET_WORDS_BIGENDIAN
        /* stw data_reg, [arg0] */
        tcg_out_ldst(s, data_reg, arg0, 0, STW);
        /* stwa data_reg, [arg0] ASI_PRIMARY_LITTLE */
        tcg_out_ldst_asi(s, data_reg, arg0, 0, STWA, ASI_PRIMARY_LITTLE);
        break;
    case 3:
#ifdef TARGET_WORDS_BIGENDIAN
        /* stx data_reg, [arg0] */
        tcg_out_ldst(s, data_reg, arg0, 0, STX);
        /* stxa data_reg, [arg0] ASI_PRIMARY_LITTLE */
        tcg_out_ldst_asi(s, data_reg, arg0, 0, STXA, ASI_PRIMARY_LITTLE);
        break;
    default:
        tcg_abort();
    }
#if defined(CONFIG_SOFTMMU)
    /* label2: */
    *label2_ptr = (INSN_OP(0) | INSN_COND(COND_A, 0) | INSN_OP2(0x2) |
                   INSN_OFF22((unsigned long)s->code_ptr -
                              (unsigned long)label2_ptr));
}


void vnc_jobs_consume_buffer(VncState *vs)
{
    bool flush;
    vnc_lock_output(vs);
    if (vs->jobs_buffer.offset) {
        if (vs->ioc != NULL && buffer_empty(&vs->output)) {
            if (vs->ioc_tag) {
                g_source_remove(vs->ioc_tag);
            vs->ioc_tag = qio_channel_add_watch(
                vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);
        buffer_move(&vs->output, &vs->jobs_buffer);
    flush = vs->ioc != NULL && vs->abort != true;
    vnc_unlock_output(vs);
    if (flush) {
      vnc_flush(vs);


ssize_t qsb_write_at(QEMUSizedBuffer *qsb, const uint8_t *source,

                     off_t pos, size_t count)

{

    ssize_t rc = qsb_grow(qsb, pos + count);

    size_t to_copy;

    size_t all_copy = count;

    const struct iovec *iov;

    ssize_t index;

    char *dest;

    off_t d_off, s_off = 0;

    if (rc < 0) {

        return rc;

    }

    if (pos + count > qsb->used) {

        qsb->used = pos + count;

    }

    index = qsb_get_iovec(qsb, pos, &d_off);

    if (index < 0) {

        return -EINVAL;

    }

    while (all_copy > 0) {

        iov = &qsb->iov[index];

        dest = iov->iov_base;

        to_copy = iov->iov_len - d_off;

        if (to_copy > all_copy) {

            to_copy = all_copy;

        }

        memcpy(&dest[d_off], &source[s_off], to_copy);

        s_off += to_copy;

        all_copy -= to_copy;

        d_off = 0;

        index++;

    }

    return count;

}


av_cold int ff_psy_init(FFPsyContext *ctx, AVCodecContext *avctx, int num_lens,

                        const uint8_t **bands, const int* num_bands,

                        int num_groups, const uint8_t *group_map)

{

    int i, j, k = 0;

    ctx->avctx = avctx;

    ctx->ch        = av_mallocz_array(sizeof(ctx->ch[0]), avctx->channels * 2);

    ctx->group     = av_mallocz_array(sizeof(ctx->group[0]), num_groups);

    ctx->bands     = av_malloc_array (sizeof(ctx->bands[0]),      num_lens);

    ctx->num_bands = av_malloc_array (sizeof(ctx->num_bands[0]),  num_lens);

    if (!ctx->ch || !ctx->group || !ctx->bands || !ctx->num_bands) {

        ff_psy_end(ctx);

        return AVERROR(ENOMEM);

    }

    memcpy(ctx->bands,     bands,     sizeof(ctx->bands[0])     *  num_lens);

    memcpy(ctx->num_bands, num_bands, sizeof(ctx->num_bands[0]) *  num_lens);

    /* assign channels to groups (with virtual channels for coupling) */

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

        /* NOTE: Add 1 to handle the AAC chan_config without modification.

         *       This has the side effect of allowing an array of 0s to map

         *       to one channel per group.

         */

        ctx->group[i].num_ch = group_map[i] + 1;

        for (j = 0; j < ctx->group[i].num_ch * 2; j++)

            ctx->group[i].ch[j]  = &ctx->ch[k++];

    }

    switch (ctx->avctx->codec_id) {

    case AV_CODEC_ID_AAC:

        ctx->model = &ff_aac_psy_model;

        break;

    }

    if (ctx->model->init)

        return ctx->model->init(ctx);

    return 0;

}


static int vpc_open(BlockDriverState *bs, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int i;

    struct vhd_footer* footer;

    struct vhd_dyndisk_header* dyndisk_header;

    uint8_t buf[HEADER_SIZE];

    uint32_t checksum;

    int err = -1;

    int disk_type = VHD_DYNAMIC;

    if (bdrv_pread(bs->file, 0, s->footer_buf, HEADER_SIZE) != HEADER_SIZE)

        goto fail;

    footer = (struct vhd_footer*) s->footer_buf;

    if (strncmp(footer->creator, "conectix", 8)) {

        int64_t offset = bdrv_getlength(bs->file);

        if (offset < HEADER_SIZE) {

            goto fail;

        }

        /* If a fixed disk, the footer is found only at the end of the file */

        if (bdrv_pread(bs->file, offset-HEADER_SIZE, s->footer_buf, HEADER_SIZE)

                != HEADER_SIZE) {

            goto fail;

        }

        if (strncmp(footer->creator, "conectix", 8)) {

            goto fail;

        }

        disk_type = VHD_FIXED;

    }

    checksum = be32_to_cpu(footer->checksum);

    footer->checksum = 0;

    if (vpc_checksum(s->footer_buf, HEADER_SIZE) != checksum)

        fprintf(stderr, "block-vpc: The header checksum of '%s' is "

            "incorrect.\n", bs->filename);

    /* Write 'checksum' back to footer, or else will leave it with zero. */

    footer->checksum = be32_to_cpu(checksum);

    // The visible size of a image in Virtual PC depends on the geometry

    // rather than on the size stored in the footer (the size in the footer

    // is too large usually)

    bs->total_sectors = (int64_t)

        be16_to_cpu(footer->cyls) * footer->heads * footer->secs_per_cyl;

    /* Allow a maximum disk size of approximately 2 TB */

    if (bs->total_sectors >= 65535LL * 255 * 255) {

        err = -EFBIG;

        goto fail;

    }

    if (disk_type == VHD_DYNAMIC) {

        if (bdrv_pread(bs->file, be64_to_cpu(footer->data_offset), buf,

                HEADER_SIZE) != HEADER_SIZE) {

            goto fail;

        }

        dyndisk_header = (struct vhd_dyndisk_header *) buf;

        if (strncmp(dyndisk_header->magic, "cxsparse", 8)) {

            goto fail;

        }

        s->block_size = be32_to_cpu(dyndisk_header->block_size);

        s->bitmap_size = ((s->block_size / (8 * 512)) + 511) & ~511;

        s->max_table_entries = be32_to_cpu(dyndisk_header->max_table_entries);

        s->pagetable = g_malloc(s->max_table_entries * 4);

        s->bat_offset = be64_to_cpu(dyndisk_header->table_offset);

        if (bdrv_pread(bs->file, s->bat_offset, s->pagetable,

                s->max_table_entries * 4) != s->max_table_entries * 4) {

            goto fail;

        }

        s->free_data_block_offset =

            (s->bat_offset + (s->max_table_entries * 4) + 511) & ~511;

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

            be32_to_cpus(&s->pagetable[i]);

            if (s->pagetable[i] != 0xFFFFFFFF) {

                int64_t next = (512 * (int64_t) s->pagetable[i]) +

                    s->bitmap_size + s->block_size;

                if (next > s->free_data_block_offset) {

                    s->free_data_block_offset = next;

                }

            }

        }

        s->last_bitmap_offset = (int64_t) -1;

#ifdef CACHE

        s->pageentry_u8 = g_malloc(512);

        s->pageentry_u32 = s->pageentry_u8;

        s->pageentry_u16 = s->pageentry_u8;

        s->last_pagetable = -1;

#endif

    }

    qemu_co_mutex_init(&s->lock);

    /* Disable migration when VHD images are used */

    error_set(&s->migration_blocker,

              QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,

              "vpc", bs->device_name, "live migration");

    migrate_add_blocker(s->migration_blocker);

    return 0;

 fail:

    return err;

}


static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr,

                         GetBitContext *gb, SBRData *ch_data)

{

    int i;

    ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env[1]];

    ch_data->bs_num_env[0] = ch_data->bs_num_env[1];

    ch_data->bs_amp_res = sbr->bs_amp_res_header;

    switch (ch_data->bs_frame_class = get_bits(gb, 2)) {

    case FIXFIX:

        ch_data->bs_num_env[1] = 1 << get_bits(gb, 2);

        if (ch_data->bs_num_env[1] == 1)

            ch_data->bs_amp_res = 0;

        ch_data->bs_pointer = 0;

        ch_data->bs_freq_res[1] = get_bits1(gb);

        for (i = 1; i < ch_data->bs_num_env[1]; i++)

            ch_data->bs_freq_res[i + 1] = ch_data->bs_freq_res[1];

        break;

    case FIXVAR:

        ch_data->bs_var_bord[1] = get_bits(gb, 2);

        ch_data->bs_num_rel[1]  = get_bits(gb, 2);

        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[1] + 1;

        for (i = 0; i < ch_data->bs_num_rel[1]; i++)

            ch_data->bs_rel_bord[1][i] = 2 * get_bits(gb, 2) + 2;

        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);

        for (i = 0; i < ch_data->bs_num_env[1]; i++)

            ch_data->bs_freq_res[ch_data->bs_num_env[1] - i] = get_bits1(gb);

        break;

    case VARFIX:

        ch_data->bs_var_bord[0] = get_bits(gb, 2);

        ch_data->bs_num_rel[0]  = get_bits(gb, 2);

        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[0] + 1;

        for (i = 0; i < ch_data->bs_num_rel[0]; i++)

            ch_data->bs_rel_bord[0][i] = 2 * get_bits(gb, 2) + 2;

        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);

        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env[1]);

        break;

    case VARVAR:

        ch_data->bs_var_bord[0] = get_bits(gb, 2);

        ch_data->bs_var_bord[1] = get_bits(gb, 2);

        ch_data->bs_num_rel[0]  = get_bits(gb, 2);

        ch_data->bs_num_rel[1]  = get_bits(gb, 2);

        ch_data->bs_num_env[1]  = ch_data->bs_num_rel[0] + ch_data->bs_num_rel[1] + 1;

        for (i = 0; i < ch_data->bs_num_rel[0]; i++)

            ch_data->bs_rel_bord[0][i] = 2 * get_bits(gb, 2) + 2;

        for (i = 0; i < ch_data->bs_num_rel[1]; i++)

            ch_data->bs_rel_bord[1][i] = 2 * get_bits(gb, 2) + 2;

        ch_data->bs_pointer = get_bits(gb, ceil_log2[ch_data->bs_num_env[1]]);

        get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env[1]);

        break;

    }

    if (ch_data->bs_pointer > ch_data->bs_num_env[1] + 1) {

        av_log(ac->avccontext, AV_LOG_ERROR,

               "Invalid bitstream, bs_pointer points to a middle noise border outside the time borders table: %d\n",

               ch_data->bs_pointer);

        return -1;

    }

    if (ch_data->bs_frame_class == FIXFIX && ch_data->bs_num_env[1] > 4) {

        av_log(ac->avccontext, AV_LOG_ERROR,

               "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n",

               ch_data->bs_num_env[1]);

        return -1;

    }

    if (ch_data->bs_frame_class == VARVAR && ch_data->bs_num_env[1] > 5) {

        av_log(ac->avccontext, AV_LOG_ERROR,

               "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n",

               ch_data->bs_num_env[1]);

        return -1;

    }

    ch_data->bs_num_noise = (ch_data->bs_num_env[1] > 1) + 1;

    return 0;

}


static void extract_exponents(AC3EncodeContext *s)

{

    int blk, ch, i;

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

        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {

            AC3Block *block = &s->blocks[blk];

            uint8_t *exp   = block->exp[ch];

            int32_t *coef = block->fixed_coef[ch];

            int exp_shift  = block->exp_shift[ch];

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

                int e;

                int v = abs(coef[i]);

                if (v == 0)

                    e = 24;

                else {

                    e = 23 - av_log2(v) + exp_shift;

                    if (e >= 24) {

                        e = 24;

                        coef[i] = 0;

                    }

                    av_assert2(e >= 0);

                }

                exp[i] = e;

            }

        }

    }

}


static float32 roundAndPackFloat32( flag zSign, int16 zExp, uint32_t zSig STATUS_PARAM)

{

    int8 roundingMode;

    flag roundNearestEven;

    int8 roundIncrement, roundBits;

    flag isTiny;

    roundingMode = STATUS(float_rounding_mode);

    roundNearestEven = ( roundingMode == float_round_nearest_even );

    roundIncrement = 0x40;

    if ( ! roundNearestEven ) {

        if ( roundingMode == float_round_to_zero ) {

            roundIncrement = 0;

        }

        else {

            roundIncrement = 0x7F;

            if ( zSign ) {

                if ( roundingMode == float_round_up ) roundIncrement = 0;

            }

            else {

                if ( roundingMode == float_round_down ) roundIncrement = 0;

            }

        }

    }

    roundBits = zSig & 0x7F;

    if ( 0xFD <= (uint16_t) zExp ) {

        if (    ( 0xFD < zExp )

             || (    ( zExp == 0xFD )

                  && ( (int32_t) ( zSig + roundIncrement ) < 0 ) )

           ) {

            float_raise( float_flag_overflow | float_flag_inexact STATUS_VAR);

            return packFloat32( zSign, 0xFF, - ( roundIncrement == 0 ));

        }

        if ( zExp < 0 ) {

            if ( STATUS(flush_to_zero) ) return packFloat32( zSign, 0, 0 );

            isTiny =

                   ( STATUS(float_detect_tininess) == float_tininess_before_rounding )

                || ( zExp < -1 )

                || ( zSig + roundIncrement < 0x80000000 );

            shift32RightJamming( zSig, - zExp, &zSig );

            zExp = 0;

            roundBits = zSig & 0x7F;

            if ( isTiny && roundBits ) float_raise( float_flag_underflow STATUS_VAR);

        }

    }

    if ( roundBits ) STATUS(float_exception_flags) |= float_flag_inexact;

    zSig = ( zSig + roundIncrement )>>7;

    zSig &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven );

    if ( zSig == 0 ) zExp = 0;

    return packFloat32( zSign, zExp, zSig );

}


static av_cold int oggvorbis_encode_close(AVCodecContext *avctx)

{

    OggVorbisContext *s = avctx->priv_data;

    /* notify vorbisenc this is EOF */

    vorbis_analysis_wrote(&s->vd, 0);

    vorbis_block_clear(&s->vb);

    vorbis_dsp_clear(&s->vd);

    vorbis_info_clear(&s->vi);

    av_freep(&avctx->coded_frame);

    av_freep(&avctx->extradata);

    return 0;

}


int av_parse_time(int64_t *timeval, const char *timestr, int duration)

{

    const char *p;

    int64_t t;

    struct tm dt = { 0 };

    int i;

    static const char * const date_fmt[] = {

        "%Y-%m-%d",

        "%Y%m%d",

    };

    static const char * const time_fmt[] = {

        "%H:%M:%S",

        "%H%M%S",

    };

    const char *q;

    int is_utc, len;

    char lastch;

    int negative = 0;

#undef time

    time_t now = time(0);

    len = strlen(timestr);

    if (len > 0)

        lastch = timestr[len - 1];

    else

        lastch = '\0';

    is_utc = (lastch == 'z' || lastch == 'Z');

    p = timestr;

    q = NULL;

    if (!duration) {

        if (!av_strncasecmp(timestr, "now", len)) {

            *timeval = (int64_t) now * 1000000;

            return 0;

        }

        /* parse the year-month-day part */

        for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {

            q = small_strptime(p, date_fmt[i], &dt);

            if (q) {

                break;

            }

        }

        /* if the year-month-day part is missing, then take the

         * current year-month-day time */

        if (!q) {

            if (is_utc) {

                dt = *gmtime(&now);

            } else {

                dt = *localtime(&now);

            }

            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;

        } else {

            p = q;

        }

        if (*p == 'T' || *p == 't' || *p == ' ')

            p++;

        /* parse the hour-minute-second part */

        for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {

            q = small_strptime(p, time_fmt[i], &dt);

            if (q) {

                break;

            }

        }

    } else {

        /* parse timestr as a duration */

        if (p[0] == '-') {

            negative = 1;

            ++p;

        }

        /* parse timestr as HH:MM:SS */

        q = small_strptime(p, time_fmt[0], &dt);

        if (!q) {

            /* parse timestr as S+ */

            dt.tm_sec = strtol(p, (void *)&q, 10);

            if (q == p) {

                /* the parsing didn't succeed */

                *timeval = INT64_MIN;

                return AVERROR(EINVAL);

            }

            dt.tm_min = 0;

            dt.tm_hour = 0;

        }

    }

    /* Now we have all the fields that we can get */

    if (!q) {

        *timeval = INT64_MIN;

        return AVERROR(EINVAL);

    }

    if (duration) {

        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;

    } else {

        dt.tm_isdst = -1;       /* unknown */

        if (is_utc) {

            t = av_timegm(&dt);

        } else {

            t = mktime(&dt);

        }

    }

    t *= 1000000;

    /* parse the .m... part */

    if (*q == '.') {

        int val, n;

        q++;

        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {

            if (!isdigit(*q))

                break;

            val += n * (*q - '0');

        }

        t += val;

    }

    *timeval = negative ? -t : t;

    return 0;

}


void *qemu_get_virtqueue_element(QEMUFile *f, size_t sz)

{

    VirtQueueElement *elem;

    VirtQueueElementOld data;

    int i;

    qemu_get_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));

    elem = virtqueue_alloc_element(sz, data.out_num, data.in_num);

    elem->index = data.index;

    for (i = 0; i < elem->in_num; i++) {

        elem->in_addr[i] = data.in_addr[i];

    }

    for (i = 0; i < elem->out_num; i++) {

        elem->out_addr[i] = data.out_addr[i];

    }

    for (i = 0; i < elem->in_num; i++) {

        /* Base is overwritten by virtqueue_map.  */

        elem->in_sg[i].iov_base = 0;

        elem->in_sg[i].iov_len = data.in_sg[i].iov_len;

    }

    for (i = 0; i < elem->out_num; i++) {

        /* Base is overwritten by virtqueue_map.  */

        elem->out_sg[i].iov_base = 0;

        elem->out_sg[i].iov_len = data.out_sg[i].iov_len;

    }

    virtqueue_map(elem);

    return elem;

}


void qdev_property_add_child(DeviceState *dev, const char *name,

                             DeviceState *child, Error **errp)

{

    gchar *type;

    type = g_strdup_printf("child<%s>", child->info->name);

    qdev_property_add(dev, name, type, qdev_get_child_property,

                      NULL, NULL, child, errp);

    qdev_ref(child);

    g_assert(child->parent == NULL);

    child->parent = dev;

    g_free(type);

}


static int copy_sectors(BlockDriverState *bs, uint64_t start_sect,

                        uint64_t cluster_offset, int n_start, int n_end)

{

    BDRVQcowState *s = bs->opaque;

    int n, ret;

    n = n_end - n_start;

    if (n <= 0)

        return 0;

    ret = qcow_read(bs, start_sect + n_start, s->cluster_data, n);

    if (ret < 0)

        return ret;

    if (s->crypt_method) {

        qcow2_encrypt_sectors(s, start_sect + n_start,

                        s->cluster_data,

                        s->cluster_data, n, 1,

                        &s->aes_encrypt_key);

    }

    ret = bdrv_write(s->hd, (cluster_offset >> 9) + n_start,

                     s->cluster_data, n);

    if (ret < 0)

        return ret;

    return 0;

}


static uint8_t send_read_command(void)

{

    uint8_t drive = 0;

    uint8_t head = 0;

    uint8_t cyl = 0;

    uint8_t sect_addr = 1;

    uint8_t sect_size = 2;

    uint8_t eot = 1;

    uint8_t gap = 0x1b;

    uint8_t gpl = 0xff;

    uint8_t msr = 0;

    uint8_t st0;

    uint8_t ret = 0;

    floppy_send(CMD_READ);

    floppy_send(head << 2 | drive);

    g_assert(!get_irq(FLOPPY_IRQ));

    floppy_send(cyl);

    floppy_send(head);

    floppy_send(sect_addr);

    floppy_send(sect_size);

    floppy_send(eot);

    floppy_send(gap);

    floppy_send(gpl);

    uint8_t i = 0;

    uint8_t n = 2;

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

        msr = inb(FLOPPY_BASE + reg_msr);

        if (msr == 0xd0) {

            break;

        }

        sleep(1);

    }

    if (i >= n) {

        return 1;

    }

    st0 = floppy_recv();

    if (st0 != 0x40) {

        ret = 1;

    }

    floppy_recv();

    floppy_recv();

    floppy_recv();

    floppy_recv();

    floppy_recv();

    floppy_recv();

    return ret;

}


static void unassigned_mem_write(void *opaque, target_phys_addr_t addr,

                                 uint64_t val, unsigned size)

{

#ifdef DEBUG_UNASSIGNED

    printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);

#endif

#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)

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

#endif

}


static void tcg_out_insn_3405(TCGContext *s, AArch64Insn insn, TCGType ext,

                              TCGReg rd, uint16_t half, unsigned shift)

{

    assert((shift & ~0x30) == 0);

    tcg_out32(s, insn | ext << 31 | shift << (21 - 4) | half << 5 | rd);

}


static inline int handle_cpu_signal(unsigned long pc, unsigned long address,

                                    int is_write, sigset_t *old_set,

                                    void *puc)

{

    TranslationBlock *tb;

    int ret;

    if (cpu_single_env)

        env = cpu_single_env; /* XXX: find a correct solution for multithread */

#if defined(DEBUG_SIGNAL)

    qemu_printf("qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n",

                pc, address, is_write, *(unsigned long *)old_set);

#endif

    /* XXX: locking issue */

    if (is_write && page_unprotect(address, pc, puc)) {

        return 1;

    }

    /* see if it is an MMU fault */

    ret = cpu_x86_handle_mmu_fault(env, address, is_write,

                                   ((env->hflags & HF_CPL_MASK) == 3), 0);

    if (ret < 0)

        return 0; /* not an MMU fault */

    if (ret == 0)

        return 1; /* the MMU fault was handled without causing real CPU fault */

    /* now we have a real cpu fault */

    tb = tb_find_pc(pc);

    if (tb) {

        /* the PC is inside the translated code. It means that we have

           a virtual CPU fault */

        cpu_restore_state(tb, env, pc, puc);

    }

    if (ret == 1) {

#if 0

        printf("PF exception: EIP=0x%08x CR2=0x%08x error=0x%x\n",

               env->eip, env->cr[2], env->error_code);

#endif

        /* we restore the process signal mask as the sigreturn should

           do it (XXX: use sigsetjmp) */

        sigprocmask(SIG_SETMASK, old_set, NULL);

        raise_exception_err(EXCP0E_PAGE, env->error_code);

    } else {

        /* activate soft MMU for this block */

        env->hflags |= HF_SOFTMMU_MASK;

        cpu_resume_from_signal(env, puc);

    }

    /* never comes here */

    return 1;

}


static void coroutine_fn v9fs_xattrcreate(void *opaque)

{

    int flags;

    int32_t fid;

    int64_t size;

    ssize_t err = 0;

    V9fsString name;

    size_t offset = 7;

    V9fsFidState *file_fidp;

    V9fsFidState *xattr_fidp;

    V9fsPDU *pdu = opaque;

    v9fs_string_init(&name);

    err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);

    if (err < 0) {

        goto out_nofid;

    }

    trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);

    file_fidp = get_fid(pdu, fid);

    if (file_fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* Make the file fid point to xattr */

    xattr_fidp = file_fidp;

    xattr_fidp->fid_type = P9_FID_XATTR;

    xattr_fidp->fs.xattr.copied_len = 0;

    xattr_fidp->fs.xattr.xattrwalk_fid = false;

    xattr_fidp->fs.xattr.len = size;

    xattr_fidp->fs.xattr.flags = flags;

    v9fs_string_init(&xattr_fidp->fs.xattr.name);

    v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);

    g_free(xattr_fidp->fs.xattr.value);

    xattr_fidp->fs.xattr.value = g_malloc0(size);

    err = offset;

    put_fid(pdu, file_fidp);

out_nofid:

    pdu_complete(pdu, err);

    v9fs_string_free(&name);

}


static void omap_sysctl_write(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

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

    switch (addr) {

    case 0x000:	/* CONTROL_REVISION */

    case 0x2a4:	/* CONTROL_MSUSPENDMUX_5 */

    case 0x2c0:	/* CONTROL_PSA_VALUE */

    case 0x2f8:	/* CONTROL_STATUS */

    case 0x2fc:	/* CONTROL_GENERAL_PURPOSE_STATUS */

    case 0x300:	/* CONTROL_RPUB_KEY_H_0 */

    case 0x304:	/* CONTROL_RPUB_KEY_H_1 */

    case 0x308:	/* CONTROL_RPUB_KEY_H_2 */

    case 0x30c:	/* CONTROL_RPUB_KEY_H_3 */

    case 0x310:	/* CONTROL_RAND_KEY_0 */

    case 0x314:	/* CONTROL_RAND_KEY_1 */

    case 0x318:	/* CONTROL_RAND_KEY_2 */

    case 0x31c:	/* CONTROL_RAND_KEY_3 */

    case 0x320:	/* CONTROL_CUST_KEY_0 */

    case 0x324:	/* CONTROL_CUST_KEY_1 */

    case 0x330:	/* CONTROL_TEST_KEY_0 */

    case 0x334:	/* CONTROL_TEST_KEY_1 */

    case 0x338:	/* CONTROL_TEST_KEY_2 */

    case 0x33c:	/* CONTROL_TEST_KEY_3 */

    case 0x340:	/* CONTROL_TEST_KEY_4 */

    case 0x344:	/* CONTROL_TEST_KEY_5 */

    case 0x348:	/* CONTROL_TEST_KEY_6 */

    case 0x34c:	/* CONTROL_TEST_KEY_7 */

    case 0x350:	/* CONTROL_TEST_KEY_8 */

    case 0x354:	/* CONTROL_TEST_KEY_9 */

        OMAP_RO_REG(addr);

        return;

    case 0x010:	/* CONTROL_SYSCONFIG */

        s->sysconfig = value & 0x1e;

        break;

    case 0x030 ... 0x140:	/* CONTROL_PADCONF - only used in the POP */

        /* XXX: should check constant bits */

        s->padconf[(addr - 0x30) >> 2] = value & 0x1f1f1f1f;

        break;

    case 0x270:	/* CONTROL_DEBOBS */

        s->obs = value & 0xff;

        break;

    case 0x274:	/* CONTROL_DEVCONF */

        s->devconfig = value & 0xffffc7ff;

        break;

    case 0x28c:	/* CONTROL_EMU_SUPPORT */

        break;

    case 0x290:	/* CONTROL_MSUSPENDMUX_0 */

        s->msuspendmux[0] = value & 0x3fffffff;

        break;

    case 0x294:	/* CONTROL_MSUSPENDMUX_1 */

        s->msuspendmux[1] = value & 0x3fffffff;

        break;

    case 0x298:	/* CONTROL_MSUSPENDMUX_2 */

        s->msuspendmux[2] = value & 0x3fffffff;

        break;

    case 0x29c:	/* CONTROL_MSUSPENDMUX_3 */

        s->msuspendmux[3] = value & 0x3fffffff;

        break;

    case 0x2a0:	/* CONTROL_MSUSPENDMUX_4 */

        s->msuspendmux[4] = value & 0x3fffffff;

        break;

    case 0x2b8:	/* CONTROL_PSA_CTRL */

        s->psaconfig = value & 0x1c;

        s->psaconfig |= (value & 0x20) ? 2 : 1;

        break;

    case 0x2bc:	/* CONTROL_PSA_CMD */

        break;

    case 0x2b0:	/* CONTROL_SEC_CTRL */

    case 0x2b4:	/* CONTROL_SEC_TEST */

    case 0x2d0:	/* CONTROL_SEC_EMU */

    case 0x2d4:	/* CONTROL_SEC_TAP */

    case 0x2d8:	/* CONTROL_OCM_RAM_PERM */

    case 0x2dc:	/* CONTROL_OCM_PUB_RAM_ADD */

    case 0x2e0:	/* CONTROL_EXT_SEC_RAM_START_ADD */

    case 0x2e4:	/* CONTROL_EXT_SEC_RAM_STOP_ADD */

    case 0x2f0:	/* CONTROL_SEC_STATUS */

    case 0x2f4:	/* CONTROL_SEC_ERR_STATUS */

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


ssize_t qemu_paio_return(struct qemu_paiocb *aiocb)

{

    ssize_t ret;

    pthread_mutex_lock(&lock);

    ret = aiocb->ret;

    pthread_mutex_unlock(&lock);

    return ret;

}


block_crypto_create_opts_init(QCryptoBlockFormat format,

                              QemuOpts *opts,

                              Error **errp)

{

    Visitor *v;

    QCryptoBlockCreateOptions *ret = NULL;

    Error *local_err = NULL;

    ret = g_new0(QCryptoBlockCreateOptions, 1);

    ret->format = format;

    v = opts_visitor_new(opts);

    visit_start_struct(v, NULL, NULL, 0, &local_err);

    if (local_err) {

        goto out;

    }

    switch (format) {

    case Q_CRYPTO_BLOCK_FORMAT_LUKS:

        visit_type_QCryptoBlockCreateOptionsLUKS_members(

            v, &ret->u.luks, &local_err);

        break;

    default:

        error_setg(&local_err, "Unsupported block format %d", format);

        break;

    }

    if (!local_err) {

        visit_check_struct(v, &local_err);

    }

    visit_end_struct(v, NULL);

 out:

    if (local_err) {

        error_propagate(errp, local_err);

        qapi_free_QCryptoBlockCreateOptions(ret);

        ret = NULL;

    }

    visit_free(v);

    return ret;

}


static void cris_evaluate_flags(DisasContext *dc)

{

	if (!dc->flags_uptodate) {

		cris_flush_cc_state(dc);

		switch (dc->cc_op)

		{

			case CC_OP_MCP:

				gen_helper_evaluate_flags_mcp();

				break;

			case CC_OP_MULS:

				gen_helper_evaluate_flags_muls();

				break;

			case CC_OP_MULU:

				gen_helper_evaluate_flags_mulu();

				break;

			case CC_OP_MOVE:

			case CC_OP_AND:

			case CC_OP_OR:

			case CC_OP_XOR:

			case CC_OP_ASR:

			case CC_OP_LSR:

			case CC_OP_LSL:

				switch (dc->cc_size)

				{

					case 4:

						gen_helper_evaluate_flags_move_4();

						break;

					case 2:

						gen_helper_evaluate_flags_move_2();

						break;

					default:

						gen_helper_evaluate_flags();

						break;

				}

				break;

			case CC_OP_FLAGS:

				/* live.  */

				break;

			default:

			{

				switch (dc->cc_size)

				{

					case 4:

						gen_helper_evaluate_flags_alu_4();

						break;

					default:

						gen_helper_evaluate_flags();

						break;

				}

			}

			break;

		}

		if (dc->flagx_known) {

			if (dc->flags_x)

				tcg_gen_ori_tl(cpu_PR[PR_CCS],

					       cpu_PR[PR_CCS], X_FLAG);

			else

				tcg_gen_andi_tl(cpu_PR[PR_CCS],

						cpu_PR[PR_CCS], ~X_FLAG);

	        }

		dc->flags_uptodate = 1;

	}

}


int nbd_disconnect(int fd)

{

    errno = ENOTSUP;

    return -1;

}


static void pl061_write(void *opaque, target_phys_addr_t offset,

                        uint32_t value)

{

    pl061_state *s = (pl061_state *)opaque;

    uint8_t mask;

    if (offset < 0x400) {

        mask = (offset >> 2) & s->dir;

        s->data = (s->data & ~mask) | (value & mask);

        pl061_update(s);

        return;

    }

    switch (offset) {

    case 0x400: /* Direction */

        s->dir = value;

        break;

    case 0x404: /* Interrupt sense */

        s->isense = value;

        break;

    case 0x408: /* Interrupt both edges */

        s->ibe = value;

        break;

    case 0x40c: /* Interrupt event */

        s->iev = value;

        break;

    case 0x410: /* Interrupt mask */

        s->im = value;

        break;

    case 0x41c: /* Interrupt clear */

        s->istate &= ~value;

        break;

    case 0x420: /* Alternate function select */

        mask = s->cr;

        s->afsel = (s->afsel & ~mask) | (value & mask);

        break;

    case 0x500: /* 2mA drive */

        s->dr2r = value;

        break;

    case 0x504: /* 4mA drive */

        s->dr4r = value;

        break;

    case 0x508: /* 8mA drive */

        s->dr8r = value;

        break;

    case 0x50c: /* Open drain */

        s->odr = value;

        break;

    case 0x510: /* Pull-up */

        s->pur = value;

        break;

    case 0x514: /* Pull-down */

        s->pdr = value;

        break;

    case 0x518: /* Slew rate control */

        s->slr = value;

        break;

    case 0x51c: /* Digital enable */

        s->den = value;

        break;

    case 0x520: /* Lock */

        s->locked = (value != 0xacce551);

        break;

    case 0x524: /* Commit */

        if (!s->locked)

            s->cr = value;

        break;

    default:

        hw_error("pl061_write: Bad offset %x\n", (int)offset);

    }

    pl061_update(s);

}


static int nvdec_vp8_start_frame(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)

{

    VP8Context *h = avctx->priv_data;

    NVDECContext      *ctx = avctx->internal->hwaccel_priv_data;

    CUVIDPICPARAMS     *pp = &ctx->pic_params;

    FrameDecodeData *fdd;

    NVDECFrame *cf;

    AVFrame *cur_frame = h->framep[VP56_FRAME_CURRENT]->tf.f;

    int ret;

    ret = ff_nvdec_start_frame(avctx, cur_frame);

    if (ret < 0)

        return ret;

    fdd = (FrameDecodeData*)cur_frame->private_ref->data;

    cf  = (NVDECFrame*)fdd->hwaccel_priv;

    *pp = (CUVIDPICPARAMS) {

        .PicWidthInMbs     = (cur_frame->width  + 15) / 16,

        .FrameHeightInMbs  = (cur_frame->height + 15) / 16,

        .CurrPicIdx        = cf->idx,

        .CodecSpecific.vp8 = {

            .width                       = cur_frame->width,

            .height                      = cur_frame->height,

            .first_partition_size        = h->header_partition_size,

            .LastRefIdx                  = safe_get_ref_idx(h->framep[VP56_FRAME_PREVIOUS]),

            .GoldenRefIdx                = safe_get_ref_idx(h->framep[VP56_FRAME_GOLDEN]),

            .AltRefIdx                   = safe_get_ref_idx(h->framep[VP56_FRAME_GOLDEN2]),

            /*

             * Explicit braces for anonymous inners to work around limitations

             * in ancient versions of gcc.

             */

            {

                {

                    .frame_type                  = !h->keyframe,

                    .version                     = h->profile,

                    .show_frame                  = !h->invisible,

                    .update_mb_segmentation_data = h->segmentation.enabled ?

                                                   h->segmentation.update_feature_data :

                                                   0,

                }

            }

       }

    };

    return 0;

}


AVFilterBufferRef *avfilter_default_get_video_buffer(AVFilterLink *link, int perms, int w, int h)

{

    AVFilterBuffer *pic = av_mallocz(sizeof(AVFilterBuffer));

    AVFilterBufferRef *ref = av_mallocz(sizeof(AVFilterBufferRef));

    int i, tempsize;

    char *buf;

    ref->buf         = pic;

    ref->video       = av_mallocz(sizeof(AVFilterBufferRefVideoProps));

    ref->video->w    = w;

    ref->video->h    = h;

    /* make sure the buffer gets read permission or it's useless for output */

    ref->perms = perms | AV_PERM_READ;

    pic->refcount = 1;

    ref->format   = link->format;

    pic->free     = avfilter_default_free_buffer;

    av_fill_image_linesizes(pic->linesize, ref->format, ref->video->w);

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

        pic->linesize[i] = FFALIGN(pic->linesize[i], 16);

    tempsize = av_fill_image_pointers(pic->data, ref->format, ref->video->h, NULL, pic->linesize);

    buf = av_malloc(tempsize + 16); // +2 is needed for swscaler, +16 to be

                                    // SIMD-friendly

    av_fill_image_pointers(pic->data, ref->format, ref->video->h, buf, pic->linesize);

    memcpy(ref->data,     pic->data,     sizeof(ref->data));

    memcpy(ref->linesize, pic->linesize, sizeof(ref->linesize));

    return ref;

}


static void blk_disconnect(struct XenDevice *xendev)

{

    struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev);

    if (blkdev->bs) {

        bdrv_detach_dev(blkdev->bs, blkdev);

        if (!blkdev->dinfo) {

            blk_unref(blk_by_name(blkdev->dev));

        }

        blkdev->bs = NULL;

    }

    xen_be_unbind_evtchn(&blkdev->xendev);

    if (blkdev->sring) {

        xc_gnttab_munmap(blkdev->xendev.gnttabdev, blkdev->sring, 1);

        blkdev->cnt_map--;

        blkdev->sring = NULL;

    }

}


static void raw_aio_remove(RawAIOCB *acb)

{

    RawAIOCB **pacb;

    /* remove the callback from the queue */

    pacb = &posix_aio_state->first_aio;

    for(;;) {

        if (*pacb == NULL) {

            fprintf(stderr, "raw_aio_remove: aio request not found!\n");

            break;

        } else if (*pacb == acb) {

            *pacb = acb->next;

            qemu_aio_release(acb);

            break;

        }

        pacb = &(*pacb)->next;

    }

}


static void nvic_writel(NVICState *s, uint32_t offset, uint32_t value)

{

    ARMCPU *cpu = s->cpu;

    switch (offset) {

    case 0xd04: /* Interrupt Control State.  */

        if (value & (1 << 31)) {

            armv7m_nvic_set_pending(s, ARMV7M_EXCP_NMI);

        }

        if (value & (1 << 28)) {

            armv7m_nvic_set_pending(s, ARMV7M_EXCP_PENDSV);

        } else if (value & (1 << 27)) {

            armv7m_nvic_clear_pending(s, ARMV7M_EXCP_PENDSV);

        }

        if (value & (1 << 26)) {

            armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK);

        } else if (value & (1 << 25)) {

            armv7m_nvic_clear_pending(s, ARMV7M_EXCP_SYSTICK);

        }

        break;

    case 0xd08: /* Vector Table Offset.  */

        cpu->env.v7m.vecbase = value & 0xffffff80;

        break;

    case 0xd0c: /* Application Interrupt/Reset Control.  */

        if ((value >> 16) == 0x05fa) {

            if (value & 4) {

                qemu_irq_pulse(s->sysresetreq);

            }

            if (value & 2) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Setting VECTCLRACTIVE when not in DEBUG mode "

                              "is UNPREDICTABLE\n");

            }

            if (value & 1) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Setting VECTRESET when not in DEBUG mode "

                              "is UNPREDICTABLE\n");

            }

            s->prigroup = extract32(value, 8, 3);

            nvic_irq_update(s);

        }

        break;

    case 0xd10: /* System Control.  */

        /* TODO: Implement control registers.  */

        qemu_log_mask(LOG_UNIMP, "NVIC: SCR unimplemented\n");

        break;

    case 0xd14: /* Configuration Control.  */

        /* Enforce RAZ/WI on reserved and must-RAZ/WI bits */

        value &= (R_V7M_CCR_STKALIGN_MASK |

                  R_V7M_CCR_BFHFNMIGN_MASK |

                  R_V7M_CCR_DIV_0_TRP_MASK |

                  R_V7M_CCR_UNALIGN_TRP_MASK |

                  R_V7M_CCR_USERSETMPEND_MASK |

                  R_V7M_CCR_NONBASETHRDENA_MASK);

        cpu->env.v7m.ccr = value;

        break;

    case 0xd24: /* System Handler Control.  */

        s->vectors[ARMV7M_EXCP_MEM].active = (value & (1 << 0)) != 0;

        s->vectors[ARMV7M_EXCP_BUS].active = (value & (1 << 1)) != 0;

        s->vectors[ARMV7M_EXCP_USAGE].active = (value & (1 << 3)) != 0;

        s->vectors[ARMV7M_EXCP_SVC].active = (value & (1 << 7)) != 0;

        s->vectors[ARMV7M_EXCP_DEBUG].active = (value & (1 << 8)) != 0;

        s->vectors[ARMV7M_EXCP_PENDSV].active = (value & (1 << 10)) != 0;

        s->vectors[ARMV7M_EXCP_SYSTICK].active = (value & (1 << 11)) != 0;

        s->vectors[ARMV7M_EXCP_USAGE].pending = (value & (1 << 12)) != 0;

        s->vectors[ARMV7M_EXCP_MEM].pending = (value & (1 << 13)) != 0;

        s->vectors[ARMV7M_EXCP_BUS].pending = (value & (1 << 14)) != 0;

        s->vectors[ARMV7M_EXCP_SVC].pending = (value & (1 << 15)) != 0;

        s->vectors[ARMV7M_EXCP_MEM].enabled = (value & (1 << 16)) != 0;

        s->vectors[ARMV7M_EXCP_BUS].enabled = (value & (1 << 17)) != 0;

        s->vectors[ARMV7M_EXCP_USAGE].enabled = (value & (1 << 18)) != 0;

        nvic_irq_update(s);

        break;

    case 0xd28: /* Configurable Fault Status.  */

        cpu->env.v7m.cfsr &= ~value; /* W1C */

        break;

    case 0xd2c: /* Hard Fault Status.  */

        cpu->env.v7m.hfsr &= ~value; /* W1C */

        break;

    case 0xd30: /* Debug Fault Status.  */

        cpu->env.v7m.dfsr &= ~value; /* W1C */

        break;

    case 0xd34: /* Mem Manage Address.  */

        cpu->env.v7m.mmfar = value;

        return;

    case 0xd38: /* Bus Fault Address.  */

        cpu->env.v7m.bfar = value;

        return;

    case 0xd3c: /* Aux Fault Status.  */

        qemu_log_mask(LOG_UNIMP,

                      "NVIC: Aux fault status registers unimplemented\n");

        break;

    case 0xd90: /* MPU_TYPE */

        return; /* RO */

    case 0xd94: /* MPU_CTRL */

        if ((value &

             (R_V7M_MPU_CTRL_HFNMIENA_MASK | R_V7M_MPU_CTRL_ENABLE_MASK))

            == R_V7M_MPU_CTRL_HFNMIENA_MASK) {

            qemu_log_mask(LOG_GUEST_ERROR, "MPU_CTRL: HFNMIENA and !ENABLE is "

                          "UNPREDICTABLE\n");

        }

        cpu->env.v7m.mpu_ctrl = value & (R_V7M_MPU_CTRL_ENABLE_MASK |

                                         R_V7M_MPU_CTRL_HFNMIENA_MASK |

                                         R_V7M_MPU_CTRL_PRIVDEFENA_MASK);

        tlb_flush(CPU(cpu));

        break;

    case 0xd98: /* MPU_RNR */

        if (value >= cpu->pmsav7_dregion) {

            qemu_log_mask(LOG_GUEST_ERROR, "MPU region out of range %"

                          PRIu32 "/%" PRIu32 "\n",

                          value, cpu->pmsav7_dregion);

        } else {

            cpu->env.pmsav7.rnr = value;

        }

        break;

    case 0xd9c: /* MPU_RBAR */

    case 0xda4: /* MPU_RBAR_A1 */

    case 0xdac: /* MPU_RBAR_A2 */

    case 0xdb4: /* MPU_RBAR_A3 */

    {

        int region;

        if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            /* PMSAv8M handling of the aliases is different from v7M:

             * aliases A1, A2, A3 override the low two bits of the region

             * number in MPU_RNR, and there is no 'region' field in the

             * RBAR register.

             */

            int aliasno = (offset - 0xd9c) / 8; /* 0..3 */

            region = cpu->env.pmsav7.rnr;

            if (aliasno) {

                region = deposit32(region, 0, 2, aliasno);

            }

            if (region >= cpu->pmsav7_dregion) {

                return;

            }

            cpu->env.pmsav8.rbar[region] = value;

            tlb_flush(CPU(cpu));

            return;

        }

        if (value & (1 << 4)) {

            /* VALID bit means use the region number specified in this

             * value and also update MPU_RNR.REGION with that value.

             */

            region = extract32(value, 0, 4);

            if (region >= cpu->pmsav7_dregion) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "MPU region out of range %u/%" PRIu32 "\n",

                              region, cpu->pmsav7_dregion);

                return;

            }

            cpu->env.pmsav7.rnr = region;

        } else {

            region = cpu->env.pmsav7.rnr;

        }

        if (region >= cpu->pmsav7_dregion) {

            return;

        }

        cpu->env.pmsav7.drbar[region] = value & ~0x1f;

        tlb_flush(CPU(cpu));

        break;

    }

    case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */

    case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */

    case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */

    case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */

    {

        int region = cpu->env.pmsav7.rnr;

        if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            /* PMSAv8M handling of the aliases is different from v7M:

             * aliases A1, A2, A3 override the low two bits of the region

             * number in MPU_RNR.

             */

            int aliasno = (offset - 0xd9c) / 8; /* 0..3 */

            region = cpu->env.pmsav7.rnr;

            if (aliasno) {

                region = deposit32(region, 0, 2, aliasno);

            }

            if (region >= cpu->pmsav7_dregion) {

                return;

            }

            cpu->env.pmsav8.rlar[region] = value;

            tlb_flush(CPU(cpu));

            return;

        }

        if (region >= cpu->pmsav7_dregion) {

            return;

        }

        cpu->env.pmsav7.drsr[region] = value & 0xff3f;

        cpu->env.pmsav7.dracr[region] = (value >> 16) & 0x173f;

        tlb_flush(CPU(cpu));

        break;

    }

    case 0xdc0: /* MPU_MAIR0 */

        if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            goto bad_offset;

        }

        if (cpu->pmsav7_dregion) {

            /* Register is RES0 if no MPU regions are implemented */

            cpu->env.pmsav8.mair0 = value;

        }

        /* We don't need to do anything else because memory attributes

         * only affect cacheability, and we don't implement caching.

         */

        break;

    case 0xdc4: /* MPU_MAIR1 */

        if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            goto bad_offset;

        }

        if (cpu->pmsav7_dregion) {

            /* Register is RES0 if no MPU regions are implemented */

            cpu->env.pmsav8.mair1 = value;

        }

        /* We don't need to do anything else because memory attributes

         * only affect cacheability, and we don't implement caching.

         */

        break;

    case 0xf00: /* Software Triggered Interrupt Register */

    {

        int excnum = (value & 0x1ff) + NVIC_FIRST_IRQ;

        if (excnum < s->num_irq) {

            armv7m_nvic_set_pending(s, excnum);

        }

        break;

    }

    default:

    bad_offset:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "NVIC: Bad write offset 0x%x\n", offset);

    }

}


static void virtio_blk_handle_write(BlockRequest *blkreq, int *num_writes,

    VirtIOBlockReq *req)

{

    if (req->out->sector & req->dev->sector_mask) {

        virtio_blk_rw_complete(req, -EIO);

        return;

    }

    if (*num_writes == 32) {

        do_multiwrite(req->dev->bs, blkreq, *num_writes);

        *num_writes = 0;

    }

    blkreq[*num_writes].sector = req->out->sector;

    blkreq[*num_writes].nb_sectors = req->qiov.size / BDRV_SECTOR_SIZE;

    blkreq[*num_writes].qiov = &req->qiov;

    blkreq[*num_writes].cb = virtio_blk_rw_complete;

    blkreq[*num_writes].opaque = req;

    blkreq[*num_writes].error = 0;

    (*num_writes)++;

}


static void nbd_restart_write(void *opaque)

{

    NbdClientSession *s = opaque;

    qemu_coroutine_enter(s->send_coroutine, NULL);

}


static void xen_domain_poll(void *opaque)

{

    struct xc_dominfo info;

    int rc;

    rc = xc_domain_getinfo(xen_xc, xen_domid, 1, &info);

    if ((rc != 1) || (info.domid != xen_domid)) {

        qemu_log("xen: domain %d is gone\n", xen_domid);

        goto quit;

    }

    if (info.dying) {

        qemu_log("xen: domain %d is dying (%s%s)\n", xen_domid,

                 info.crashed  ? "crashed"  : "",

                 info.shutdown ? "shutdown" : "");

        goto quit;

    }

    qemu_mod_timer(xen_poll, qemu_get_clock(rt_clock) + 1000);

    return;

quit:

    qemu_system_shutdown_request();

    return;

}


static void v9fs_unlinkat(void *opaque)

{

    int err = 0;

    V9fsString name;

    int32_t dfid, flags;

    size_t offset = 7;

    V9fsPath path;

    V9fsFidState *dfidp;

    V9fsPDU *pdu = opaque;

    pdu_unmarshal(pdu, offset, "dsd", &dfid, &name, &flags);

    dfidp = get_fid(pdu, dfid);

    if (dfidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /*

     * IF the file is unlinked, we cannot reopen

     * the file later. So don't reclaim fd

     */

    v9fs_path_init(&path);

    err = v9fs_co_name_to_path(pdu, &dfidp->path, name.data, &path);

    if (err < 0) {

        goto out_err;

    }

    err = v9fs_mark_fids_unreclaim(pdu, &path);

    if (err < 0) {

        goto out_err;

    }

    err = v9fs_co_unlinkat(pdu, &dfidp->path, &name, flags);

    if (!err) {

        err = offset;

    }

out_err:

    put_fid(pdu, dfidp);

    v9fs_path_free(&path);

out_nofid:

    complete_pdu(pdu->s, pdu, err);

    v9fs_string_free(&name);

}


void load_seg(int seg_reg, int selector, unsigned int cur_eip)

{

    uint32_t e1, e2;

    int cpl, dpl, rpl;

    SegmentCache *dt;

    int index;

    uint8_t *ptr;

    if ((selector & 0xfffc) == 0) {

        /* null selector case */

        if (seg_reg == R_SS) {

            EIP = cur_eip;

            raise_exception_err(EXCP0D_GPF, 0);

        } else {

            cpu_x86_load_seg_cache(env, seg_reg, selector, NULL, 0, 0);

        }

    } else {

        if (selector & 0x4)

            dt = &env->ldt;

        else

            dt = &env->gdt;

        index = selector & ~7;

        if ((index + 7) > dt->limit) {

            EIP = cur_eip;

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        }

        ptr = dt->base + index;

        e1 = ldl_kernel(ptr);

        e2 = ldl_kernel(ptr + 4);

        if (!(e2 & DESC_S_MASK)) {

            EIP = cur_eip;

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        }

        rpl = selector & 3;

        dpl = (e2 >> DESC_DPL_SHIFT) & 3;

        cpl = env->hflags & HF_CPL_MASK;

        if (seg_reg == R_SS) {

            /* must be writable segment */

            if ((e2 & DESC_CS_MASK) || !(e2 & DESC_W_MASK)) {

                EIP = cur_eip;

                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

            }

            if (rpl != cpl || dpl != cpl) {

                EIP = cur_eip;

                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

            }

        } else {

            /* must be readable segment */

            if ((e2 & (DESC_CS_MASK | DESC_R_MASK)) == DESC_CS_MASK) {

                EIP = cur_eip;

                raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

            }

            if (!(e2 & DESC_CS_MASK) || !(e2 & DESC_C_MASK)) {

                /* if not conforming code, test rights */

                if (dpl < cpl || dpl < rpl) {

                    EIP = cur_eip;

                    raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

                }

            }

        }

        if (!(e2 & DESC_P_MASK)) {

            EIP = cur_eip;

            if (seg_reg == R_SS)

                raise_exception_err(EXCP0C_STACK, selector & 0xfffc);

            else

                raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);

        }

        /* set the access bit if not already set */

        if (!(e2 & DESC_A_MASK)) {

            e2 |= DESC_A_MASK;

            stl_kernel(ptr + 4, e2);

        }

        cpu_x86_load_seg_cache(env, seg_reg, selector,

                       get_seg_base(e1, e2),

                       get_seg_limit(e1, e2),

                       e2);

#if 0

        fprintf(logfile, "load_seg: sel=0x%04x base=0x%08lx limit=0x%08lx flags=%08x\n",

                selector, (unsigned long)sc->base, sc->limit, sc->flags);

#endif

    }

}


static int decode_exponents(GetBitContext *gbc, int exp_strategy, int ngrps,

                            uint8_t absexp, int8_t *dexps)

{

    int i, j, grp, group_size;

    int dexp[256];

    int expacc, prevexp;

    /* unpack groups */

    group_size = exp_strategy + (exp_strategy == EXP_D45);

    for(grp=0,i=0; grp<ngrps; grp++) {

        expacc = get_bits(gbc, 7);

        dexp[i++] = ungroup_3_in_7_bits_tab[expacc][0];

        dexp[i++] = ungroup_3_in_7_bits_tab[expacc][1];

        dexp[i++] = ungroup_3_in_7_bits_tab[expacc][2];

    }

    /* convert to absolute exps and expand groups */

    prevexp = absexp;

    for(i=0,j=0; i<ngrps*3; i++) {

        prevexp += dexp[i] - 2;

        if (prevexp < 0 || prevexp > 24)

            return -1;

        switch (group_size) {

            case 4: dexps[j++] = prevexp;

                    dexps[j++] = prevexp;

            case 2: dexps[j++] = prevexp;

            case 1: dexps[j++] = prevexp;

        }

    }

    return 0;

}


static void unix_accept_incoming_migration(void *opaque)

{

    struct sockaddr_un addr;

    socklen_t addrlen = sizeof(addr);

    int s = (unsigned long)opaque;

    QEMUFile *f;

    int c, ret;

    do {

        c = qemu_accept(s, (struct sockaddr *)&addr, &addrlen);

    } while (c == -1 && socket_error() == EINTR);

    DPRINTF("accepted migration\n");

    if (c == -1) {

        fprintf(stderr, "could not accept migration connection\n");

        return;

    }

    f = qemu_fopen_socket(c);

    if (f == NULL) {

        fprintf(stderr, "could not qemu_fopen socket\n");

        goto out;

    }

    ret = qemu_loadvm_state(f);

    if (ret < 0) {

        fprintf(stderr, "load of migration failed\n");

        goto out_fopen;

    }

    qemu_announce_self();

    DPRINTF("successfully loaded vm state\n");

    /* we've successfully migrated, close the server socket */

    qemu_set_fd_handler2(s, NULL, NULL, NULL, NULL);

    close(s);

out_fopen:

    qemu_fclose(f);

out:

    close(c);

}


static int protocol_version(VncState *vs, uint8_t *version, size_t len)

{

    char local[13];

    memcpy(local, version, 12);

    local[12] = 0;

    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {

	VNC_DEBUG("Malformed protocol version %s\n", local);

	vnc_client_error(vs);

	return 0;

    }

    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);

    if (vs->major != 3 ||

	(vs->minor != 3 &&

	 vs->minor != 4 &&

	 vs->minor != 5 &&

	 vs->minor != 7 &&

	 vs->minor != 8)) {

	VNC_DEBUG("Unsupported client version\n");

	vnc_write_u32(vs, VNC_AUTH_INVALID);

	vnc_flush(vs);

	vnc_client_error(vs);

	return 0;

    }

    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated

     * as equivalent to v3.3 by servers

     */

    if (vs->minor == 4 || vs->minor == 5)

	vs->minor = 3;

    if (vs->minor == 3) {

	if (vs->vd->auth == VNC_AUTH_NONE) {

            VNC_DEBUG("Tell client auth none\n");

            vnc_write_u32(vs, vs->vd->auth);

            vnc_flush(vs);

            vnc_read_when(vs, protocol_client_init, 1);

       } else if (vs->vd->auth == VNC_AUTH_VNC) {

            VNC_DEBUG("Tell client VNC auth\n");

            vnc_write_u32(vs, vs->vd->auth);

            vnc_flush(vs);

            start_auth_vnc(vs);

       } else {

            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->vd->auth);

            vnc_write_u32(vs, VNC_AUTH_INVALID);

            vnc_flush(vs);

            vnc_client_error(vs);

       }

    } else {

	VNC_DEBUG("Telling client we support auth %d\n", vs->vd->auth);

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

	vnc_write_u8(vs, vs->vd->auth);

	vnc_read_when(vs, protocol_client_auth, 1);

	vnc_flush(vs);

    }

    return 0;

}


static void data_plane_set_up_op_blockers(VirtIOBlockDataPlane *s)

{

    assert(!s->blocker);

    error_setg(&s->blocker, "block device is in use by data plane");

    blk_op_block_all(s->conf->conf.blk, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_RESIZE, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_DRIVE_DEL, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_BACKUP_SOURCE, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_CHANGE, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_COMMIT_SOURCE, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_COMMIT_TARGET, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_EJECT, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,

                   s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT,

                   s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE,

                   s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_MIRROR_SOURCE, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_STREAM, s->blocker);

    blk_op_unblock(s->conf->conf.blk, BLOCK_OP_TYPE_REPLACE, s->blocker);

}


static inline void scoop_gpio_handler_update(ScoopInfo *s) {

    uint32_t level, diff;

    int bit;

    level = s->gpio_level & s->gpio_dir;

    for (diff = s->prev_level ^ level; diff; diff ^= 1 << bit) {

        bit = ffs(diff) - 1;

        qemu_set_irq(s->handler[bit], (level >> bit) & 1);

    }

    s->prev_level = level;

}


static void disas_simd_zip_trn(DisasContext *s, uint32_t insn)

{

    unsupported_encoding(s, insn);

}


static int run_ccw(struct subchannel_id schid, int cmd, void *ptr, int len)

{

    struct ccw1 ccw = {};

    struct cmd_orb orb = {};

    struct schib schib;

    int r;

    /* start command processing */

    stsch_err(schid, &schib);

    schib.scsw.ctrl = SCSW_FCTL_START_FUNC;

    msch(schid, &schib);

    /* start subchannel command */

    orb.fmt = 1;

    orb.cpa = (u32)(long)&ccw;

    orb.lpm = 0x80;

    ccw.cmd_code = cmd;

    ccw.cda = (long)ptr;

    ccw.count = len;

    r = ssch(schid, &orb);

    /*

     * XXX Wait until device is done processing the CCW. For now we can

     *     assume that a simple tsch will have finished the CCW processing,

     *     but the architecture allows for asynchronous operation

     */

    drain_irqs(schid);

    return r;

}


static struct omap_lpg_s *omap_lpg_init(target_phys_addr_t base, omap_clk clk)

{

    int iomemtype;

    struct omap_lpg_s *s = (struct omap_lpg_s *)

            qemu_mallocz(sizeof(struct omap_lpg_s));

    s->tm = qemu_new_timer(rt_clock, omap_lpg_tick, s);

    omap_lpg_reset(s);

    iomemtype = cpu_register_io_memory(omap_lpg_readfn,

                    omap_lpg_writefn, s, DEVICE_NATIVE_ENDIAN);

    cpu_register_physical_memory(base, 0x800, iomemtype);

    omap_clk_adduser(clk, qemu_allocate_irqs(omap_lpg_clk_update, s, 1)[0]);

    return s;

}


static QDictEntry *qdict_find(const QDict *qdict,

                              const char *key, unsigned int hash)

{

    QDictEntry *entry;

    LIST_FOREACH(entry, &qdict->table[hash], next)

        if (!strcmp(entry->key, key))

            return entry;

    return NULL;

}


int css_do_tsch(SubchDev *sch, IRB *target_irb)

{

    SCSW *s = &sch->curr_status.scsw;

    PMCW *p = &sch->curr_status.pmcw;

    uint16_t stctl;

    uint16_t fctl;

    uint16_t actl;

    IRB irb;

    int ret;

    if (!(p->flags & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA))) {

        ret = 3;

        goto out;

    }

    stctl = s->ctrl & SCSW_CTRL_MASK_STCTL;

    fctl = s->ctrl & SCSW_CTRL_MASK_FCTL;

    actl = s->ctrl & SCSW_CTRL_MASK_ACTL;

    /* Prepare the irb for the guest. */

    memset(&irb, 0, sizeof(IRB));

    /* Copy scsw from current status. */

    memcpy(&irb.scsw, s, sizeof(SCSW));

    if (stctl & SCSW_STCTL_STATUS_PEND) {

        if (s->cstat & (SCSW_CSTAT_DATA_CHECK |

                        SCSW_CSTAT_CHN_CTRL_CHK |

                        SCSW_CSTAT_INTF_CTRL_CHK)) {

            irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF;

            irb.esw[0] = 0x04804000;

        } else {

            irb.esw[0] = 0x00800000;

        }

        /* If a unit check is pending, copy sense data. */

        if ((s->dstat & SCSW_DSTAT_UNIT_CHECK) &&

            (p->chars & PMCW_CHARS_MASK_CSENSE)) {

            irb.scsw.flags |= SCSW_FLAGS_MASK_ESWF | SCSW_FLAGS_MASK_ECTL;

            memcpy(irb.ecw, sch->sense_data, sizeof(sch->sense_data));

            irb.esw[1] = 0x02000000 | (sizeof(sch->sense_data) << 8);

        }

    }

    /* Store the irb to the guest. */

    copy_irb_to_guest(target_irb, &irb);

    /* Clear conditions on subchannel, if applicable. */

    if (stctl & SCSW_STCTL_STATUS_PEND) {

        s->ctrl &= ~SCSW_CTRL_MASK_STCTL;

        if ((stctl != (SCSW_STCTL_INTERMEDIATE | SCSW_STCTL_STATUS_PEND)) ||

            ((fctl & SCSW_FCTL_HALT_FUNC) &&

             (actl & SCSW_ACTL_SUSP))) {

            s->ctrl &= ~SCSW_CTRL_MASK_FCTL;

        }

        if (stctl != (SCSW_STCTL_INTERMEDIATE | SCSW_STCTL_STATUS_PEND)) {

            s->flags &= ~SCSW_FLAGS_MASK_PNO;

            s->ctrl &= ~(SCSW_ACTL_RESUME_PEND |

                         SCSW_ACTL_START_PEND |

                         SCSW_ACTL_HALT_PEND |

                         SCSW_ACTL_CLEAR_PEND |

                         SCSW_ACTL_SUSP);

        } else {

            if ((actl & SCSW_ACTL_SUSP) &&

                (fctl & SCSW_FCTL_START_FUNC)) {

                s->flags &= ~SCSW_FLAGS_MASK_PNO;

                if (fctl & SCSW_FCTL_HALT_FUNC) {

                    s->ctrl &= ~(SCSW_ACTL_RESUME_PEND |

                                 SCSW_ACTL_START_PEND |

                                 SCSW_ACTL_HALT_PEND |

                                 SCSW_ACTL_CLEAR_PEND |

                                 SCSW_ACTL_SUSP);

                } else {

                    s->ctrl &= ~SCSW_ACTL_RESUME_PEND;

                }

            }

        }

        /* Clear pending sense data. */

        if (p->chars & PMCW_CHARS_MASK_CSENSE) {

            memset(sch->sense_data, 0 , sizeof(sch->sense_data));

        }

    }

    ret = ((stctl & SCSW_STCTL_STATUS_PEND) == 0);

out:

    return ret;

}


int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)

{

    Mpeg4DecContext *ctx = avctx->priv_data;

    MpegEncContext    *s = &ctx->m;

    /* divx 5.01+ bitstream reorder stuff */

    /* Since this clobbers the input buffer and hwaccel codecs still need the

     * data during hwaccel->end_frame we should not do this any earlier */

    if (s->divx_packed) {

        int current_pos     = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);

        int startcode_found = 0;

        if (buf_size - current_pos > 7) {

            int i;

            for (i = current_pos; i < buf_size - 4; i++)

                if (buf[i]     == 0 &&

                    buf[i + 1] == 0 &&

                    buf[i + 2] == 1 &&

                    buf[i + 3] == 0xB6) {

                    startcode_found = !(buf[i + 4] & 0x40);

                    break;

                }

        }

        if (startcode_found) {

            av_fast_malloc(&s->bitstream_buffer,

                           &s->allocated_bitstream_buffer_size,

                           buf_size - current_pos +

                           FF_INPUT_BUFFER_PADDING_SIZE);

            if (!s->bitstream_buffer)

                return AVERROR(ENOMEM);

            memcpy(s->bitstream_buffer, buf + current_pos,

                   buf_size - current_pos);

            s->bitstream_buffer_size = buf_size - current_pos;

        }

    }

    return 0;

}


static void pxb_host_class_init(ObjectClass *class, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(class);

    SysBusDeviceClass *sbc = SYS_BUS_DEVICE_CLASS(class);

    PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(class);

    dc->fw_name = "pci";

    sbc->explicit_ofw_unit_address = pxb_host_ofw_unit_address;

    hc->root_bus_path = pxb_host_root_bus_path;

}


static int vmsa_ttbcr_raw_write(CPUARMState *env, const ARMCPRegInfo *ri,

                                uint64_t value)

{

    if (arm_feature(env, ARM_FEATURE_LPAE)) {

        value &= ~((7 << 19) | (3 << 14) | (0xf << 3));

    } else {

        value &= 7;

    }

    /* Note that we always calculate c2_mask and c2_base_mask, but

     * they are only used for short-descriptor tables (ie if EAE is 0);

     * for long-descriptor tables the TTBCR fields are used differently

     * and the c2_mask and c2_base_mask values are meaningless.

     */

    env->cp15.c2_control = value;

    env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> value);

    env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> value);

    return 0;

}


av_cold int ff_dcaadpcm_init(DCAADPCMEncContext *s)
{
    if (!s)
        return -1;
    s->private_data = av_malloc(sizeof(premultiplied_coeffs) * DCA_ADPCM_VQCODEBOOK_SZ);
    precalc(s->private_data);
    return 0;
}


static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }


static int dirac_unpack_idwt_params(DiracContext *s)

{

    GetBitContext *gb = &s->gb;

    int i, level;

    unsigned tmp;

#define CHECKEDREAD(dst, cond, errmsg) \

    tmp = svq3_get_ue_golomb(gb); \

    if (cond) { \

        av_log(s->avctx, AV_LOG_ERROR, errmsg); \

        return -1; \

    }\

    dst = tmp;

    align_get_bits(gb);

    s->zero_res = s->num_refs ? get_bits1(gb) : 0;

    if (s->zero_res)

        return 0;

    /*[DIRAC_STD] 11.3.1 Transform parameters. transform_parameters() */

    CHECKEDREAD(s->wavelet_idx, tmp > 6, "wavelet_idx is too big\n")

    CHECKEDREAD(s->wavelet_depth, tmp > MAX_DWT_LEVELS || tmp < 1, "invalid number of DWT decompositions\n")

    if (!s->low_delay) {

        /* Codeblock parameters (core syntax only) */

        if (get_bits1(gb)) {

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

                CHECKEDREAD(s->codeblock[i].width , tmp < 1, "codeblock width invalid\n")

                CHECKEDREAD(s->codeblock[i].height, tmp < 1, "codeblock height invalid\n")

            }

            CHECKEDREAD(s->codeblock_mode, tmp > 1, "unknown codeblock mode\n")

        } else

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

                s->codeblock[i].width = s->codeblock[i].height = 1;

    } else {

        /* Slice parameters + quantization matrix*/

        /*[DIRAC_STD] 11.3.4 Slice coding Parameters (low delay syntax only). slice_parameters() */

        s->lowdelay.num_x     = svq3_get_ue_golomb(gb);

        s->lowdelay.num_y     = svq3_get_ue_golomb(gb);

        s->lowdelay.bytes.num = svq3_get_ue_golomb(gb);

        s->lowdelay.bytes.den = svq3_get_ue_golomb(gb);

        if (s->lowdelay.bytes.den <= 0) {

            av_log(s->avctx,AV_LOG_ERROR,"Invalid lowdelay.bytes.den\n");

            return AVERROR_INVALIDDATA;

        }

        /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */

        if (get_bits1(gb)) {

            av_log(s->avctx,AV_LOG_DEBUG,"Low Delay: Has Custom Quantization Matrix!\n");

            /* custom quantization matrix */

            s->lowdelay.quant[0][0] = svq3_get_ue_golomb(gb);

            for (level = 0; level < s->wavelet_depth; level++) {

                s->lowdelay.quant[level][1] = svq3_get_ue_golomb(gb);

                s->lowdelay.quant[level][2] = svq3_get_ue_golomb(gb);

                s->lowdelay.quant[level][3] = svq3_get_ue_golomb(gb);

            }

        } else {

            if (s->wavelet_depth > 4) {

                av_log(s->avctx,AV_LOG_ERROR,"Mandatory custom low delay matrix missing for depth %d\n", s->wavelet_depth);

                return AVERROR_INVALIDDATA;

            }

            /* default quantization matrix */

            for (level = 0; level < s->wavelet_depth; level++)

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

                    s->lowdelay.quant[level][i] = default_qmat[s->wavelet_idx][level][i];

                    /* haar with no shift differs for different depths */

                    if (s->wavelet_idx == 3)

                        s->lowdelay.quant[level][i] += 4*(s->wavelet_depth-1 - level);

                }

        }

    }

    return 0;

}


static int yop_probe(AVProbeData *probe_packet)

{

    if (AV_RB16(probe_packet->buf) == AV_RB16("YO")  &&

        probe_packet->buf[6]                         &&

        probe_packet->buf[7]                         &&

        !(probe_packet->buf[8] & 1)                  &&

        !(probe_packet->buf[10] & 1))

        return AVPROBE_SCORE_MAX * 3 / 4;

    return 0;

}


av_cold int ff_vp8_decode_init(AVCodecContext *avctx)

{

    VP8Context *s = avctx->priv_data;

    int ret;

    s->avctx = avctx;

    avctx->pix_fmt = AV_PIX_FMT_YUV420P;

    avctx->internal->allocate_progress = 1;

    ff_videodsp_init(&s->vdsp, 8);

    ff_h264_pred_init(&s->hpc, AV_CODEC_ID_VP8, 8, 1);

    ff_vp8dsp_init(&s->vp8dsp);

    if ((ret = vp8_init_frames(s)) < 0) {

        ff_vp8_decode_free(avctx);

        return ret;

    }

    return 0;

}


static int decode_unk6(uint8_t *frame, int width, int height,

                       const uint8_t *src, const uint8_t *src_end)

{

    return -1;

}


int ga_install_service(const char *path, const char *logfile,

                       const char *state_dir)

{

    int ret = EXIT_FAILURE;

    SC_HANDLE manager;

    SC_HANDLE service;

    TCHAR module_fname[MAX_PATH];

    GString *cmdline;

    SERVICE_DESCRIPTION desc = { (char *)QGA_SERVICE_DESCRIPTION };

    if (GetModuleFileName(NULL, module_fname, MAX_PATH) == 0) {

        printf_win_error("No full path to service's executable");

        return EXIT_FAILURE;

    }

    cmdline = g_string_new(module_fname);

    g_string_append(cmdline, " -d");

    if (path) {

        g_string_append_printf(cmdline, " -p %s", path);

    }

    if (logfile) {

        g_string_append_printf(cmdline, " -l %s -v", logfile);

    }

    if (state_dir) {

        g_string_append_printf(cmdline, " -t %s", state_dir);

    }

    g_debug("service's cmdline: %s", cmdline->str);

    manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (manager == NULL) {

        printf_win_error("No handle to service control manager");

        goto out_strings;

    }

    service = CreateService(manager, QGA_SERVICE_NAME, QGA_SERVICE_DISPLAY_NAME,

        SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,

        SERVICE_ERROR_NORMAL, cmdline->str, NULL, NULL, NULL, NULL, NULL);

    if (service == NULL) {

        printf_win_error("Failed to install service");

        goto out_manager;

    }

    ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &desc);

    fprintf(stderr, "Service was installed successfully.\n");

    ret = EXIT_SUCCESS;

    CloseServiceHandle(service);

out_manager:

    CloseServiceHandle(manager);

out_strings:

    g_string_free(cmdline, TRUE);

    return ret;

}


static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque)

{

    CURLState *s = ((CURLState*)opaque);

    size_t realsize = size * nmemb;

    int i;

    DPRINTF("CURL: Just reading %zd bytes\n", realsize);

    if (!s || !s->orig_buf)

        goto read_end;

    memcpy(s->orig_buf + s->buf_off, ptr, realsize);

    s->buf_off += realsize;

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

        CURLAIOCB *acb = s->acb[i];

        if (!acb)

            continue;

        if ((s->buf_off >= acb->end)) {

            qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start,

                                acb->end - acb->start);

            acb->common.cb(acb->common.opaque, 0);

            qemu_aio_release(acb);

            s->acb[i] = NULL;

read_end:

    return realsize;


void qemu_sem_post(QemuSemaphore *sem)

{

    int rc;

#if defined(__APPLE__) || defined(__NetBSD__)

    pthread_mutex_lock(&sem->lock);

    if (sem->count == INT_MAX) {

        rc = EINVAL;

    } else if (sem->count++ < 0) {

        rc = pthread_cond_signal(&sem->cond);

    } else {

        rc = 0;

    }

    pthread_mutex_unlock(&sem->lock);

    if (rc != 0) {

        error_exit(rc, __func__);

    }

#else

    rc = sem_post(&sem->sem);

    if (rc < 0) {

        error_exit(errno, __func__);

    }

#endif

}


int scsi_convert_sense(uint8_t *in_buf, int in_len,

                       uint8_t *buf, int len, bool fixed)

{

    SCSISense sense;

    bool fixed_in;

    fixed_in = (in_buf[0] & 2) == 0;

    if (in_len && fixed == fixed_in) {

        memcpy(buf, in_buf, MIN(len, in_len));

        return MIN(len, in_len);

    }

    if (in_len == 0) {

        sense = SENSE_CODE(NO_SENSE);

    } else {

        sense = scsi_parse_sense_buf(in_buf, in_len);

    }

    return scsi_build_sense_buf(buf, len, sense, fixed);

}


static int encode_codebook(CinepakEncContext *s, int *codebook, int size, int chunk_type_yuv, int chunk_type_gray, unsigned char *buf)

{

    int x, y, ret, entry_size = s->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4;

    ret = write_chunk_header(buf, s->pix_fmt == AV_PIX_FMT_YUV420P ? chunk_type_yuv : chunk_type_gray, entry_size * size);

    for(x = 0; x < size; x++)

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

            buf[ret++] = codebook[y + x*entry_size] ^ (y >= 4 ? 0x80 : 0);

    return ret;

}