static void dec_misc(DisasContext *dc, uint32_t insn)

{

    uint32_t op0, op1;

    uint32_t ra, rb, rd;

    uint32_t L6, K5, K16, K5_11;

    int32_t I16, I5_11, N26;

    TCGMemOp mop;

    TCGv t0;

    op0 = extract32(insn, 26, 6);

    op1 = extract32(insn, 24, 2);

    ra = extract32(insn, 16, 5);

    rb = extract32(insn, 11, 5);

    rd = extract32(insn, 21, 5);

    L6 = extract32(insn, 5, 6);

    K5 = extract32(insn, 0, 5);

    K16 = extract32(insn, 0, 16);

    I16 = (int16_t)K16;

    N26 = sextract32(insn, 0, 26);

    K5_11 = (extract32(insn, 21, 5) << 11) | extract32(insn, 0, 11);

    I5_11 = (int16_t)K5_11;

    switch (op0) {

    case 0x00:    /* l.j */

        LOG_DIS("l.j %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x01:    /* l.jal */

        LOG_DIS("l.jal %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x03:    /* l.bnf */

        LOG_DIS("l.bnf %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x04:    /* l.bf */

        LOG_DIS("l.bf %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x05:

        switch (op1) {

        case 0x01:    /* l.nop */

            LOG_DIS("l.nop %d\n", I16);

            break;

        default:

            gen_illegal_exception(dc);

            break;

        }

        break;

    case 0x11:    /* l.jr */

        LOG_DIS("l.jr r%d\n", rb);

         gen_jump(dc, 0, rb, op0);

         break;

    case 0x12:    /* l.jalr */

        LOG_DIS("l.jalr r%d\n", rb);

        gen_jump(dc, 0, rb, op0);

        break;

    case 0x13:    /* l.maci */

        LOG_DIS("l.maci r%d, %d\n", ra, I16);

        t0 = tcg_const_tl(I16);

        gen_mac(dc, cpu_R[ra], t0);

        tcg_temp_free(t0);

        break;

    case 0x09:    /* l.rfe */

        LOG_DIS("l.rfe\n");

        {

#if defined(CONFIG_USER_ONLY)

            return;

#else

            if (dc->mem_idx == MMU_USER_IDX) {

                gen_illegal_exception(dc);

                return;

            }

            gen_helper_rfe(cpu_env);

            dc->is_jmp = DISAS_UPDATE;

#endif

        }

        break;

    case 0x1b: /* l.lwa */

        LOG_DIS("l.lwa r%d, r%d, %d\n", rd, ra, I16);

        gen_lwa(dc, cpu_R[rd], cpu_R[ra], I16);

        break;

    case 0x1c:    /* l.cust1 */

        LOG_DIS("l.cust1\n");

        break;

    case 0x1d:    /* l.cust2 */

        LOG_DIS("l.cust2\n");

        break;

    case 0x1e:    /* l.cust3 */

        LOG_DIS("l.cust3\n");

        break;

    case 0x1f:    /* l.cust4 */

        LOG_DIS("l.cust4\n");

        break;

    case 0x3c:    /* l.cust5 */

        LOG_DIS("l.cust5 r%d, r%d, r%d, %d, %d\n", rd, ra, rb, L6, K5);

        break;

    case 0x3d:    /* l.cust6 */

        LOG_DIS("l.cust6\n");

        break;

    case 0x3e:    /* l.cust7 */

        LOG_DIS("l.cust7\n");

        break;

    case 0x3f:    /* l.cust8 */

        LOG_DIS("l.cust8\n");

        break;

/* not used yet, open it when we need or64.  */

/*#ifdef TARGET_OPENRISC64

    case 0x20:     l.ld

        LOG_DIS("l.ld r%d, r%d, %d\n", rd, ra, I16);

        check_ob64s(dc);

        mop = MO_TEQ;

        goto do_load;

#endif*/

    case 0x21:    /* l.lwz */

        LOG_DIS("l.lwz r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TEUL;

        goto do_load;

    case 0x22:    /* l.lws */

        LOG_DIS("l.lws r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TESL;

        goto do_load;

    case 0x23:    /* l.lbz */

        LOG_DIS("l.lbz r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_UB;

        goto do_load;

    case 0x24:    /* l.lbs */

        LOG_DIS("l.lbs r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_SB;

        goto do_load;

    case 0x25:    /* l.lhz */

        LOG_DIS("l.lhz r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TEUW;

        goto do_load;

    case 0x26:    /* l.lhs */

        LOG_DIS("l.lhs r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TESW;

        goto do_load;

    do_load:

        {

            TCGv t0 = tcg_temp_new();

            tcg_gen_addi_tl(t0, cpu_R[ra], I16);

            tcg_gen_qemu_ld_tl(cpu_R[rd], t0, dc->mem_idx, mop);

            tcg_temp_free(t0);

        }

        break;

    case 0x27:    /* l.addi */

        LOG_DIS("l.addi r%d, r%d, %d\n", rd, ra, I16);

        t0 = tcg_const_tl(I16);

        gen_add(dc, cpu_R[rd], cpu_R[ra], t0);

        tcg_temp_free(t0);

        break;

    case 0x28:    /* l.addic */

        LOG_DIS("l.addic r%d, r%d, %d\n", rd, ra, I16);

        t0 = tcg_const_tl(I16);

        gen_addc(dc, cpu_R[rd], cpu_R[ra], t0);

        tcg_temp_free(t0);

        break;

    case 0x29:    /* l.andi */

        LOG_DIS("l.andi r%d, r%d, %d\n", rd, ra, K16);

        tcg_gen_andi_tl(cpu_R[rd], cpu_R[ra], K16);

        break;

    case 0x2a:    /* l.ori */

        LOG_DIS("l.ori r%d, r%d, %d\n", rd, ra, K16);

        tcg_gen_ori_tl(cpu_R[rd], cpu_R[ra], K16);

        break;

    case 0x2b:    /* l.xori */

        LOG_DIS("l.xori r%d, r%d, %d\n", rd, ra, I16);

        tcg_gen_xori_tl(cpu_R[rd], cpu_R[ra], I16);

        break;

    case 0x2c:    /* l.muli */

        LOG_DIS("l.muli r%d, r%d, %d\n", rd, ra, I16);

        t0 = tcg_const_tl(I16);

        gen_mul(dc, cpu_R[rd], cpu_R[ra], t0);

        tcg_temp_free(t0);

        break;

    case 0x2d:    /* l.mfspr */

        LOG_DIS("l.mfspr r%d, r%d, %d\n", rd, ra, K16);

        {

#if defined(CONFIG_USER_ONLY)

            return;

#else

            TCGv_i32 ti = tcg_const_i32(K16);

            if (dc->mem_idx == MMU_USER_IDX) {

                gen_illegal_exception(dc);

                return;

            }

            gen_helper_mfspr(cpu_R[rd], cpu_env, cpu_R[rd], cpu_R[ra], ti);

            tcg_temp_free_i32(ti);

#endif

        }

        break;

    case 0x30:    /* l.mtspr */

        LOG_DIS("l.mtspr r%d, r%d, %d\n", ra, rb, K5_11);

        {

#if defined(CONFIG_USER_ONLY)

            return;

#else

            TCGv_i32 im = tcg_const_i32(K5_11);

            if (dc->mem_idx == MMU_USER_IDX) {

                gen_illegal_exception(dc);

                return;

            }

            gen_helper_mtspr(cpu_env, cpu_R[ra], cpu_R[rb], im);

            tcg_temp_free_i32(im);

#endif

        }

        break;

    case 0x33: /* l.swa */

        LOG_DIS("l.swa r%d, r%d, %d\n", ra, rb, I5_11);

        gen_swa(dc, cpu_R[rb], cpu_R[ra], I5_11);

        break;

/* not used yet, open it when we need or64.  */

/*#ifdef TARGET_OPENRISC64

    case 0x34:     l.sd

        LOG_DIS("l.sd r%d, r%d, %d\n", ra, rb, I5_11);

        check_ob64s(dc);

        mop = MO_TEQ;

        goto do_store;

#endif*/

    case 0x35:    /* l.sw */

        LOG_DIS("l.sw r%d, r%d, %d\n", ra, rb, I5_11);

        mop = MO_TEUL;

        goto do_store;

    case 0x36:    /* l.sb */

        LOG_DIS("l.sb r%d, r%d, %d\n", ra, rb, I5_11);

        mop = MO_UB;

        goto do_store;

    case 0x37:    /* l.sh */

        LOG_DIS("l.sh r%d, r%d, %d\n", ra, rb, I5_11);

        mop = MO_TEUW;

        goto do_store;

    do_store:

        {

            TCGv t0 = tcg_temp_new();

            tcg_gen_addi_tl(t0, cpu_R[ra], I5_11);

            tcg_gen_qemu_st_tl(cpu_R[rb], t0, dc->mem_idx, mop);

            tcg_temp_free(t0);

        }

        break;

    default:

        gen_illegal_exception(dc);

        break;

    }

}


g_malloc0(size_t n_bytes)

{

    void *mem;

    __coverity_negative_sink__(n_bytes);

    mem = calloc(1, n_bytes == 0 ? 1 : n_bytes);

    if (!mem) __coverity_panic__();

    return mem;

}


static ssize_t unix_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,

                                  int64_t pos)

{

    QEMUFileSocket *s = opaque;

    ssize_t len, offset;

    ssize_t size = iov_size(iov, iovcnt);

    ssize_t total = 0;

    assert(iovcnt > 0);

    offset = 0;

    while (size > 0) {

        /* Find the next start position; skip all full-sized vector elements  */

        while (offset >= iov[0].iov_len) {

            offset -= iov[0].iov_len;

            iov++, iovcnt--;

        }

        /* skip `offset' bytes from the (now) first element, undo it on exit */

        assert(iovcnt > 0);

        iov[0].iov_base += offset;

        iov[0].iov_len -= offset;

        do {

            len = writev(s->fd, iov, iovcnt);

        } while (len == -1 && errno == EINTR);

        if (len == -1) {

            return -errno;

        }

        /* Undo the changes above */

        iov[0].iov_base -= offset;

        iov[0].iov_len += offset;

        /* Prepare for the next iteration */

        offset += len;

        total += len;

        size -= len;

    }

    return total;

}


void ff_rfps_calculate(AVFormatContext *ic)

{

    int i, j;

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

        AVStream *st = ic->streams[i];

        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)

            continue;

        // the check for tb_unreliable() is not completely correct, since this is not about handling

        // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.

        // ipmovie.c produces.

        if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)

            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);

        if (st->info->duration_count>1 && !st->r_frame_rate.num

            && tb_unreliable(st->codec)) {

            int num = 0;

            double best_error= 0.01;

            AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);

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

                int k;

                if (st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))

                    continue;

                if (!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))

                    continue;

                if (av_q2d(st->time_base) * st->info->rfps_duration_sum / st->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))

                    continue;

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

                    int n = st->info->duration_count;

                    double a= st->info->duration_error[k][0][j] / n;

                    double error= st->info->duration_error[k][1][j]/n - a*a;

                    if (error < best_error && best_error> 0.000000001) {

                        best_error= error;

                        num = get_std_framerate(j);

                    }

                    if (error < 0.02)

                        av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);

                }

            }

            // do not increase frame rate by more than 1 % in order to match a standard rate.

            if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))

                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);

        }

        if (   !st->avg_frame_rate.num

            && st->r_frame_rate.num && st->info->rfps_duration_sum

            && st->info->codec_info_duration <= 0

            && st->info->duration_count > 2

            && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - st->info->rfps_duration_sum / (double)st->info->duration_count) <= 1.0

            ) {

            av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");

            st->avg_frame_rate = st->r_frame_rate;

        }

        av_freep(&st->info->duration_error);

        st->info->last_dts = AV_NOPTS_VALUE;

        st->info->duration_count = 0;

        st->info->rfps_duration_sum = 0;

    }

}


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

                             int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    ThreadFrame tframe = { .f = data };

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    FLACContext *s = avctx->priv_data;

    int bytes_read = 0;

    int ret;

    *got_frame_ptr = 0;

    if (s->max_framesize == 0) {

        s->max_framesize =

            ff_flac_get_max_frame_size(s->max_blocksize ? s->max_blocksize : FLAC_MAX_BLOCKSIZE,

                                       FLAC_MAX_CHANNELS, 32);

    }

    if (buf_size > 5 && !memcmp(buf, "\177FLAC", 5)) {

        av_log(s->avctx, AV_LOG_DEBUG, "skiping flac header packet 1\n");

        return buf_size;

    }

    if (buf_size > 0 && (*buf & 0x7F) == FLAC_METADATA_TYPE_VORBIS_COMMENT) {

        av_log(s->avctx, AV_LOG_DEBUG, "skiping vorbis comment\n");

        return buf_size;

    }

    /* check that there is at least the smallest decodable amount of data.

       this amount corresponds to the smallest valid FLAC frame possible.

       FF F8 69 02 00 00 9A 00 00 34 46 */

    if (buf_size < FLAC_MIN_FRAME_SIZE)

        return buf_size;

    /* check for inline header */

    if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {

        if (!s->got_streaminfo && (ret = parse_streaminfo(s, buf, buf_size))) {

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

            return ret;

        }

        return get_metadata_size(buf, buf_size);

    }

    /* decode frame */

    if ((ret = init_get_bits8(&s->gb, buf, buf_size)) < 0)

        return ret;

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

        av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");

        return ret;

    }

    bytes_read = get_bits_count(&s->gb)/8;

    if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&

        av_crc(av_crc_get_table(AV_CRC_16_ANSI),

               0, buf, bytes_read)) {

        av_log(s->avctx, AV_LOG_ERROR, "CRC error at PTS %"PRId64"\n", avpkt->pts);

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

            return AVERROR_INVALIDDATA;

    }

    /* get output buffer */

    frame->nb_samples = s->blocksize;

    if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0)

        return ret;

    s->dsp.decorrelate[s->ch_mode](frame->data, s->decoded, s->channels,

                                   s->blocksize, s->sample_shift);

    if (bytes_read > buf_size) {

        av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);

        return AVERROR_INVALIDDATA;

    }

    if (bytes_read < buf_size) {

        av_log(s->avctx, AV_LOG_DEBUG, "underread: %d orig size: %d\n",

               buf_size - bytes_read, buf_size);

    }

    *got_frame_ptr = 1;

    return bytes_read;

}


static int nut_read_packet(AVFormatContext * avf, AVPacket * pkt) {

    NUTContext * priv = avf->priv_data;

    nut_packet_t pd;

    int ret;

    while ((ret = nut_read_next_packet(priv->nut, &pd)) < 0)

        av_log(avf, AV_LOG_ERROR, " NUT error: %s\n", nut_error(-ret));

    if (ret || av_new_packet(pkt, pd.len) < 0) return -1;

    if (pd.flags & NUT_FLAG_KEY) pkt->flags |= PKT_FLAG_KEY;

    pkt->pts = pd.pts;

    pkt->stream_index = pd.stream;

    pkt->pos = url_ftell(&avf->pb);

    ret = nut_read_frame(priv->nut, &pd.len, pkt->data);

    return ret;

}


void acpi_memory_unplug_request_cb(HotplugHandler *hotplug_dev,

                                   MemHotplugState *mem_st,

                                   DeviceState *dev, Error **errp)

{

    MemStatus *mdev;

    mdev = acpi_memory_slot_status(mem_st, dev, errp);

    if (!mdev) {

        return;

    }

    /* nvdimm device hot unplug is not supported yet. */

    assert(!object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM));

    mdev->is_removing = true;

    acpi_send_event(DEVICE(hotplug_dev), ACPI_MEMORY_HOTPLUG_STATUS);

}


static inline uint32_t ne2000_mem_readl(NE2000State *s, uint32_t addr)

{

    addr &= ~1; /* XXX: check exact behaviour if not even */

    if (addr < 32 ||

        (addr >= NE2000_PMEM_START && addr < NE2000_MEM_SIZE)) {

        return ldl_le_p(s->mem + addr);

    } else {

        return 0xffffffff;

    }

}


static void jazz_led_write(void *opaque, target_phys_addr_t addr,

                           uint64_t val, unsigned int size)

{

    LedState *s = opaque;

    uint8_t new_val = val & 0xff;

    trace_jazz_led_write(addr, new_val);

    s->segments = new_val;

    s->state |= REDRAW_SEGMENTS;

}


static void gd_grab_pointer(GtkDisplayState *s)

{

#if GTK_CHECK_VERSION(3, 0, 0)

    GdkDisplay *display = gtk_widget_get_display(s->drawing_area);

    GdkDeviceManager *mgr = gdk_display_get_device_manager(display);

    GList *devices = gdk_device_manager_list_devices(mgr,

                                                     GDK_DEVICE_TYPE_MASTER);

    GList *tmp = devices;

    while (tmp) {

        GdkDevice *dev = tmp->data;

        if (gdk_device_get_source(dev) == GDK_SOURCE_MOUSE) {

            gdk_device_grab(dev,

                            gtk_widget_get_window(s->drawing_area),

                            GDK_OWNERSHIP_NONE,

                            FALSE, /* All events to come to our

                                      window directly */

                            GDK_POINTER_MOTION_MASK |

                            GDK_BUTTON_PRESS_MASK |

                            GDK_BUTTON_RELEASE_MASK |

                            GDK_BUTTON_MOTION_MASK |

                            GDK_SCROLL_MASK,

                            s->null_cursor,

                            GDK_CURRENT_TIME);

        }

        tmp = tmp->next;

    }

    g_list_free(devices);

#else

    gdk_pointer_grab(gtk_widget_get_window(s->drawing_area),

                     FALSE, /* All events to come to our window directly */

                     GDK_POINTER_MOTION_MASK |

                     GDK_BUTTON_PRESS_MASK |

                     GDK_BUTTON_RELEASE_MASK |

                     GDK_BUTTON_MOTION_MASK |

                     GDK_SCROLL_MASK,

                     NULL, /* Allow cursor to move over entire desktop */

                     s->null_cursor,

                     GDK_CURRENT_TIME);

#endif

}


static uint64_t virtio_pci_config_read(void *opaque, hwaddr addr,

                                       unsigned size)

{

    VirtIOPCIProxy *proxy = opaque;

    uint32_t config = VIRTIO_PCI_CONFIG(&proxy->pci_dev);

    uint64_t val = 0;

    if (addr < config) {

        return virtio_ioport_read(proxy, addr);

    }

    addr -= config;

    switch (size) {

    case 1:

        val = virtio_config_readb(proxy->vdev, addr);

        break;

    case 2:

        val = virtio_config_readw(proxy->vdev, addr);

        if (virtio_is_big_endian()) {

            val = bswap16(val);

        }

        break;

    case 4:

        val = virtio_config_readl(proxy->vdev, addr);

        if (virtio_is_big_endian()) {

            val = bswap32(val);

        }

        break;

    }

    return val;

}


void spapr_cpu_parse_features(sPAPRMachineState *spapr)

{

    /*

     * Backwards compatibility hack:

     *

     *   CPUs had a "compat=" property which didn't make sense for

     *   anything except pseries.  It was replaced by "max-cpu-compat"

     *   machine option.  This supports old command lines like

     *       -cpu POWER8,compat=power7

     *   By stripping the compat option and applying it to the machine

     *   before passing it on to the cpu level parser.

     */

    gchar **inpieces;

    gchar *newprops;

    int i, j;

    gchar *compat_str = NULL;

    inpieces = g_strsplit(MACHINE(spapr)->cpu_model, ",", 0);

    /* inpieces[0] is the actual model string */

    i = 1;

    j = 1;

    while (inpieces[i]) {

        if (g_str_has_prefix(inpieces[i], "compat=")) {

            /* in case of multiple compat= options */

            g_free(compat_str);

            compat_str = inpieces[i];

        } else {

            j++;

        }

        i++;

        /* Excise compat options from list */

        inpieces[j] = inpieces[i];

    }

    if (compat_str) {

        char *val = compat_str + strlen("compat=");

        object_property_set_str(OBJECT(spapr), val, "max-cpu-compat",

                                &error_fatal);

    }

    newprops = g_strjoinv(",", inpieces);

    cpu_parse_cpu_model(TYPE_POWERPC_CPU, newprops);

    g_free(newprops);

    g_strfreev(inpieces);

}


static void gen_debug(DisasContext *s, target_ulong cur_eip)

{

    gen_update_cc_op(s);

    gen_jmp_im(cur_eip);

    gen_helper_debug(cpu_env);

    s->is_jmp = DISAS_TB_JUMP;

}


int ff_request_frame(AVFilterLink *link)

{

    int ret = -1;

    FF_TPRINTF_START(NULL, request_frame); ff_tlog_link(NULL, link, 1);

    if (link->closed)

        return AVERROR_EOF;

    av_assert0(!link->frame_requested);

    link->frame_requested = 1;

    while (link->frame_requested) {

        if (link->srcpad->request_frame)

            ret = link->srcpad->request_frame(link);

        else if (link->src->inputs[0])

            ret = ff_request_frame(link->src->inputs[0]);

        if (ret == AVERROR_EOF && link->partial_buf) {

            AVFrame *pbuf = link->partial_buf;

            link->partial_buf = NULL;

            ret = ff_filter_frame_framed(link, pbuf);

        }

        if (ret < 0) {

            link->frame_requested = 0;

            if (ret == AVERROR_EOF)

                link->closed = 1;

        } else {

            av_assert0(!link->frame_requested ||

                       link->flags & FF_LINK_FLAG_REQUEST_LOOP);

        }

    }

    return ret;

}


static int pci_unin_agp_init_device(SysBusDevice *dev)

{

    UNINState *s;

    int pci_mem_config, pci_mem_data;

    /* Uninorth AGP bus */

    s = FROM_SYSBUS(UNINState, dev);

    pci_mem_config = cpu_register_io_memory(pci_unin_config_read,

                                            pci_unin_config_write, s);

    pci_mem_data = cpu_register_io_memory(pci_unin_main_read,

                                          pci_unin_main_write, &s->host_state);

    sysbus_init_mmio(dev, 0x1000, pci_mem_config);

    sysbus_init_mmio(dev, 0x1000, pci_mem_data);

    return 0;

}


nand_write(void *opaque, target_phys_addr_t addr, uint64_t value,

           unsigned size)

{

    struct nand_state_t *s = opaque;

    int rdy;

    DNAND(printf("%s addr=%x v=%x\n", __func__, addr, (unsigned)value));

    nand_setpins(s->nand, s->cle, s->ale, s->ce, 1, 0);

    nand_setio(s->nand, value);

    nand_getpins(s->nand, &rdy);

    s->rdy = rdy;

}


static void omap_mpui_init(MemoryRegion *memory, target_phys_addr_t base,

                struct omap_mpu_state_s *mpu)

{

    memory_region_init_io(&mpu->mpui_iomem, &omap_mpui_ops, mpu,

                          "omap-mpui", 0x100);

    memory_region_add_subregion(memory, base, &mpu->mpui_iomem);

    omap_mpui_reset(mpu);

}


static BusState *qbus_find(const char *path)

{

    DeviceState *dev;

    BusState *bus;

    char elem[128], msg[256];

    int pos, len;

    /* find start element */

    if (path[0] == '/') {

        bus = main_system_bus;

        pos = 0;

    } else {

        if (sscanf(path, "%127[^/]%n", elem, &len) != 1) {

            qemu_error("path parse error (\"%s\")\n", path);

            return NULL;

        }

        bus = qbus_find_recursive(main_system_bus, elem, NULL);

        if (!bus) {

            qemu_error("bus \"%s\" not found\n", elem);

            return NULL;

        }

        pos = len;

    }

    for (;;) {

        if (path[pos] == '\0') {

            /* we are done */

            return bus;

        }

        /* find device */

        if (sscanf(path+pos, "/%127[^/]%n", elem, &len) != 1) {

            qemu_error("path parse error (\"%s\" pos %d)\n", path, pos);

            return NULL;

        }

        pos += len;

        dev = qbus_find_dev(bus, elem);

        if (!dev) {

            qbus_list_dev(bus, msg, sizeof(msg));

            qemu_error("device \"%s\" not found\n%s\n", elem, msg);

            return NULL;

        }

        if (path[pos] == '\0') {

            /* last specified element is a device.  If it has exactly

             * one child bus accept it nevertheless */

            switch (dev->num_child_bus) {

            case 0:

                qemu_error("device has no child bus (%s)\n", path);

                return NULL;

            case 1:

                return LIST_FIRST(&dev->child_bus);

            default:

                qbus_list_bus(dev, msg, sizeof(msg));

                qemu_error("device has multiple child busses (%s)\n%s\n",

                           path, msg);

                return NULL;

            }

        }

        /* find bus */

        if (sscanf(path+pos, "/%127[^/]%n", elem, &len) != 1) {

            qemu_error("path parse error (\"%s\" pos %d)\n", path, pos);

            return NULL;

        }

        pos += len;

        bus = qbus_find_bus(dev, elem);

        if (!bus) {

            qbus_list_bus(dev, msg, sizeof(msg));

            qemu_error("child bus \"%s\" not found\n%s\n", elem, msg);

            return NULL;

        }

    }

}


iscsi_aio_read16_cb(struct iscsi_context *iscsi, int status,

                    void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    trace_iscsi_aio_read16_cb(iscsi, status, acb, acb->canceled);

    if (acb->canceled != 0) {

        return;

    }

    acb->status = 0;

    if (status != 0) {

        if (status == SCSI_STATUS_CHECK_CONDITION

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

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

            if (acb->task != NULL) {

                scsi_free_scsi_task(acb->task);

                acb->task = NULL;

            }

            if (iscsi_aio_readv_acb(acb) == 0) {

                iscsi_set_events(acb->iscsilun);

                return;

            }

        }

        error_report("Failed to read16 data from iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(acb);

}


void apic_sipi(CPUState *env)

{

    APICState *s = env->apic_state;

    cpu_reset_interrupt(env, CPU_INTERRUPT_SIPI);

    if (!s->wait_for_sipi)

        return;

    env->eip = 0;

    cpu_x86_load_seg_cache(env, R_CS, s->sipi_vector << 8, s->sipi_vector << 12,

                           0xffff, 0);

    env->halted = 0;

    s->wait_for_sipi = 0;

}


static int print_drive(DeviceState *dev, Property *prop, char *dest, size_t len)

{

    DriveInfo **ptr = qdev_get_prop_ptr(dev, prop);

    return snprintf(dest, len, "%s", (*ptr) ? (*ptr)->id : "<null>");

}


static void pxa2xx_pic_mem_write(void *opaque, hwaddr offset,

                                 uint64_t value, unsigned size)

{

    PXA2xxPICState *s = (PXA2xxPICState *) opaque;

    switch (offset) {

    case ICMR:	/* Mask register */

        s->int_enabled[0] = value;

        break;

    case ICMR2:	/* Mask register 2 */

        s->int_enabled[1] = value;

        break;

    case ICLR:	/* Level register */

        s->is_fiq[0] = value;

        break;

    case ICLR2:	/* Level register 2 */

        s->is_fiq[1] = value;

        break;

    case ICCR:	/* Idle mask */

        s->int_idle = (value & 1) ? 0 : ~0;

        break;

    case IPR0  ... IPR31:

        s->priority[0  + ((offset - IPR0 ) >> 2)] = value & 0x8000003f;

        break;

    case IPR32 ... IPR39:

        s->priority[32 + ((offset - IPR32) >> 2)] = value & 0x8000003f;

        break;

    default:

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

        return;

    }

    pxa2xx_pic_update(opaque);

}


static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    char *buf;

    size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());

    /* For SCSI generic devices the alignment is not really used.

       With buffered I/O, we don't have any restrictions. */

    if (bdrv_is_sg(bs) || !s->needs_alignment) {

        bs->request_alignment = 1;

        s->buf_align = 1;

        return;

    }

    bs->request_alignment = 0;

    s->buf_align = 0;

    /* Let's try to use the logical blocksize for the alignment. */

    if (probe_logical_blocksize(fd, &bs->request_alignment) < 0) {

        bs->request_alignment = 0;

    }

#ifdef CONFIG_XFS

    if (s->is_xfs) {

        struct dioattr da;

        if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {

            bs->request_alignment = da.d_miniosz;

            /* The kernel returns wrong information for d_mem */

            /* s->buf_align = da.d_mem; */

        }

    }

#endif

    /* If we could not get the sizes so far, we can only guess them */

    if (!s->buf_align) {

        size_t align;

        buf = qemu_memalign(max_align, 2 * max_align);

        for (align = 512; align <= max_align; align <<= 1) {

            if (raw_is_io_aligned(fd, buf + align, max_align)) {

                s->buf_align = align;

                break;

            }

        }

        qemu_vfree(buf);

    }

    if (!bs->request_alignment) {

        size_t align;

        buf = qemu_memalign(s->buf_align, max_align);

        for (align = 512; align <= max_align; align <<= 1) {

            if (raw_is_io_aligned(fd, buf, align)) {

                bs->request_alignment = align;

                break;

            }

        }

        qemu_vfree(buf);

    }

    if (!s->buf_align || !bs->request_alignment) {

        error_setg(errp, "Could not find working O_DIRECT alignment. "

                         "Try cache.direct=off.");

    }

}


static void filter_frame(H264Context *h) {

    int mb_x = 0;

    int mb_y = 0;

    for( mb_y = 0; mb_y < h->s.mb_height; mb_y++ ) {

        for( mb_x = 0; mb_x < h->s.mb_width; mb_x++ ) {

            filter_mb( h, mb_x, mb_y );

        }

    }

}


static int xen_pt_msgaddr64_reg_write(XenPCIPassthroughState *s,

                                      XenPTReg *cfg_entry, uint32_t *val,

                                      uint32_t dev_value, uint32_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint32_t writable_mask = 0;

    uint32_t old_addr = cfg_entry->data;

    /* check whether the type is 64 bit or not */

    if (!(s->msi->flags & PCI_MSI_FLAGS_64BIT)) {

        XEN_PT_ERR(&s->dev,

                   "Can't write to the upper address without 64 bit support\n");

        return -1;

    }

    /* modify emulate register */

    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    /* update the msi_info too */

    s->msi->addr_hi = cfg_entry->data;

    /* create value for writing to I/O device register */

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);

    /* update MSI */

    if (cfg_entry->data != old_addr) {

        if (s->msi->mapped) {

            xen_pt_msi_update(s);

        }

    }

    return 0;

}


static int v9fs_synth_close(FsContext *ctx, V9fsFidOpenState *fs)

{

    V9fsSynthOpenState *synth_open = fs->private;

    V9fsSynthNode *node = synth_open->node;

    node->open_count--;

    g_free(synth_open);

    fs->private = NULL;

    return 0;

}


static void monitor_handle_command(Monitor *mon, const char *cmdline)

{

    const char *p, *pstart, *typestr;

    char *q;

    int c, nb_args, len, i, has_arg;

    const mon_cmd_t *cmd;

    char cmdname[256];

    char buf[1024];

    void *str_allocated[MAX_ARGS];

    void *args[MAX_ARGS];

    void (*handler_0)(Monitor *mon);

    void (*handler_1)(Monitor *mon, void *arg0);

    void (*handler_2)(Monitor *mon, void *arg0, void *arg1);

    void (*handler_3)(Monitor *mon, void *arg0, void *arg1, void *arg2);

    void (*handler_4)(Monitor *mon, void *arg0, void *arg1, void *arg2,

                      void *arg3);

    void (*handler_5)(Monitor *mon, void *arg0, void *arg1, void *arg2,

                      void *arg3, void *arg4);

    void (*handler_6)(Monitor *mon, void *arg0, void *arg1, void *arg2,

                      void *arg3, void *arg4, void *arg5);

    void (*handler_7)(Monitor *mon, void *arg0, void *arg1, void *arg2,

                      void *arg3, void *arg4, void *arg5, void *arg6);

#ifdef DEBUG

    monitor_printf(mon, "command='%s'\n", cmdline);

#endif

    /* extract the command name */

    p = cmdline;

    q = cmdname;

    while (qemu_isspace(*p))

        p++;

    if (*p == '\0')

        return;

    pstart = p;

    while (*p != '\0' && *p != '/' && !qemu_isspace(*p))

        p++;

    len = p - pstart;

    if (len > sizeof(cmdname) - 1)

        len = sizeof(cmdname) - 1;

    memcpy(cmdname, pstart, len);

    cmdname[len] = '\0';

    /* find the command */

    for(cmd = mon_cmds; cmd->name != NULL; cmd++) {

        if (compare_cmd(cmdname, cmd->name))

            goto found;

    }

    monitor_printf(mon, "unknown command: '%s'\n", cmdname);

    return;

 found:

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

        str_allocated[i] = NULL;

    /* parse the parameters */

    typestr = cmd->args_type;

    nb_args = 0;

    for(;;) {

        c = *typestr;

        if (c == '\0')

            break;

        typestr++;

        switch(c) {

        case 'F':

        case 'B':

        case 's':

            {

                int ret;

                char *str;

                while (qemu_isspace(*p))

                    p++;

                if (*typestr == '?') {

                    typestr++;

                    if (*p == '\0') {

                        /* no optional string: NULL argument */

                        str = NULL;

                        goto add_str;

                    }

                }

                ret = get_str(buf, sizeof(buf), &p);

                if (ret < 0) {

                    switch(c) {

                    case 'F':

                        monitor_printf(mon, "%s: filename expected\n",

                                       cmdname);

                        break;

                    case 'B':

                        monitor_printf(mon, "%s: block device name expected\n",

                                       cmdname);

                        break;

                    default:

                        monitor_printf(mon, "%s: string expected\n", cmdname);

                        break;

                    }

                    goto fail;

                }

                str = qemu_malloc(strlen(buf) + 1);

                pstrcpy(str, sizeof(buf), buf);

                str_allocated[nb_args] = str;

            add_str:

                if (nb_args >= MAX_ARGS) {

                error_args:

                    monitor_printf(mon, "%s: too many arguments\n", cmdname);

                    goto fail;

                }

                args[nb_args++] = str;

            }

            break;

        case '/':

            {

                int count, format, size;

                while (qemu_isspace(*p))

                    p++;

                if (*p == '/') {

                    /* format found */

                    p++;

                    count = 1;

                    if (qemu_isdigit(*p)) {

                        count = 0;

                        while (qemu_isdigit(*p)) {

                            count = count * 10 + (*p - '0');

                            p++;

                        }

                    }

                    size = -1;

                    format = -1;

                    for(;;) {

                        switch(*p) {

                        case 'o':

                        case 'd':

                        case 'u':

                        case 'x':

                        case 'i':

                        case 'c':

                            format = *p++;

                            break;

                        case 'b':

                            size = 1;

                            p++;

                            break;

                        case 'h':

                            size = 2;

                            p++;

                            break;

                        case 'w':

                            size = 4;

                            p++;

                            break;

                        case 'g':

                        case 'L':

                            size = 8;

                            p++;

                            break;

                        default:

                            goto next;

                        }

                    }

                next:

                    if (*p != '\0' && !qemu_isspace(*p)) {

                        monitor_printf(mon, "invalid char in format: '%c'\n",

                                       *p);

                        goto fail;

                    }

                    if (format < 0)

                        format = default_fmt_format;

                    if (format != 'i') {

                        /* for 'i', not specifying a size gives -1 as size */

                        if (size < 0)

                            size = default_fmt_size;

                        default_fmt_size = size;

                    }

                    default_fmt_format = format;

                } else {

                    count = 1;

                    format = default_fmt_format;

                    if (format != 'i') {

                        size = default_fmt_size;

                    } else {

                        size = -1;

                    }

                }

                if (nb_args + 3 > MAX_ARGS)

                    goto error_args;

                args[nb_args++] = (void*)(long)count;

                args[nb_args++] = (void*)(long)format;

                args[nb_args++] = (void*)(long)size;

            }

            break;

        case 'i':

        case 'l':

            {

                int64_t val;

                while (qemu_isspace(*p))

                    p++;

                if (*typestr == '?' || *typestr == '.') {

                    if (*typestr == '?') {

                        if (*p == '\0')

                            has_arg = 0;

                        else

                            has_arg = 1;

                    } else {

                        if (*p == '.') {

                            p++;

                            while (qemu_isspace(*p))

                                p++;

                            has_arg = 1;

                        } else {

                            has_arg = 0;

                        }

                    }

                    typestr++;

                    if (nb_args >= MAX_ARGS)

                        goto error_args;

                    args[nb_args++] = (void *)(long)has_arg;

                    if (!has_arg) {

                        if (nb_args >= MAX_ARGS)

                            goto error_args;

                        val = -1;

                        goto add_num;

                    }

                }

                if (get_expr(mon, &val, &p))

                    goto fail;

            add_num:

                if (c == 'i') {

                    if (nb_args >= MAX_ARGS)

                        goto error_args;

                    args[nb_args++] = (void *)(long)val;

                } else {

                    if ((nb_args + 1) >= MAX_ARGS)

                        goto error_args;

#if TARGET_PHYS_ADDR_BITS > 32

                    args[nb_args++] = (void *)(long)((val >> 32) & 0xffffffff);

#else

                    args[nb_args++] = (void *)0;

#endif

                    args[nb_args++] = (void *)(long)(val & 0xffffffff);

                }

            }

            break;

        case '-':

            {

                int has_option;

                /* option */

                c = *typestr++;

                if (c == '\0')

                    goto bad_type;

                while (qemu_isspace(*p))

                    p++;

                has_option = 0;

                if (*p == '-') {

                    p++;

                    if (*p != c) {

                        monitor_printf(mon, "%s: unsupported option -%c\n",

                                       cmdname, *p);

                        goto fail;

                    }

                    p++;

                    has_option = 1;

                }

                if (nb_args >= MAX_ARGS)

                    goto error_args;

                args[nb_args++] = (void *)(long)has_option;

            }

            break;

        default:

        bad_type:

            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);

            goto fail;

        }

    }

    /* check that all arguments were parsed */

    while (qemu_isspace(*p))

        p++;

    if (*p != '\0') {

        monitor_printf(mon, "%s: extraneous characters at the end of line\n",

                       cmdname);

        goto fail;

    }

    switch(nb_args) {

    case 0:

        handler_0 = cmd->handler;

        handler_0(mon);

        break;

    case 1:

        handler_1 = cmd->handler;

        handler_1(mon, args[0]);

        break;

    case 2:

        handler_2 = cmd->handler;

        handler_2(mon, args[0], args[1]);

        break;

    case 3:

        handler_3 = cmd->handler;

        handler_3(mon, args[0], args[1], args[2]);

        break;

    case 4:

        handler_4 = cmd->handler;

        handler_4(mon, args[0], args[1], args[2], args[3]);

        break;

    case 5:

        handler_5 = cmd->handler;

        handler_5(mon, args[0], args[1], args[2], args[3], args[4]);

        break;

    case 6:

        handler_6 = cmd->handler;

        handler_6(mon, args[0], args[1], args[2], args[3], args[4], args[5]);

        break;

    case 7:

        handler_7 = cmd->handler;

        handler_7(mon, args[0], args[1], args[2], args[3], args[4], args[5],

                  args[6]);

        break;

    default:

        monitor_printf(mon, "unsupported number of arguments: %d\n", nb_args);

        goto fail;

    }

 fail:

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

        qemu_free(str_allocated[i]);

    return;

}


static void nvic_systick_trigger(void *opaque, int n, int level)

{

    NVICState *s = opaque;

    if (level) {

        /* SysTick just asked us to pend its exception.

         * (This is different from an external interrupt line's

         * behaviour.)

         */

        armv7m_nvic_set_pending(s, ARMV7M_EXCP_SYSTICK);

    }

}


int32_t helper_fqtoi(CPUSPARCState *env)

{

    int32_t ret;

    clear_float_exceptions(env);

    ret = float128_to_int32_round_to_zero(QT1, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


void qemu_opts_print(QemuOpts *opts, const char *separator)

{

    QemuOpt *opt;

    QemuOptDesc *desc = opts->list->desc;

    const char *sep = "";

    if (opts->id) {

        printf("id=%s", opts->id); /* passed id_wellformed -> no commas */

        sep = separator;

    }

    if (desc[0].name == NULL) {

        QTAILQ_FOREACH(opt, &opts->head, next) {

            printf("%s%s=", sep, opt->name);

            escaped_print(opt->str);

            sep = separator;

        }

        return;

    }

    for (; desc && desc->name; desc++) {

        const char *value;

        QemuOpt *opt = qemu_opt_find(opts, desc->name);

        value = opt ? opt->str : desc->def_value_str;

        if (!value) {

            continue;

        }

        if (desc->type == QEMU_OPT_STRING) {

            printf("%s%s=", sep, desc->name);

            escaped_print(value);

        } else if ((desc->type == QEMU_OPT_SIZE ||

                    desc->type == QEMU_OPT_NUMBER) && opt) {

            printf("%s%s=%" PRId64, sep, desc->name, opt->value.uint);

        } else {

            printf("%s%s=%s", sep, desc->name, value);

        }

        sep = separator;

    }

}


static void adb_keyboard_event(DeviceState *dev, QemuConsole *src,

                               InputEvent *evt)

{

    KBDState *s = (KBDState *)dev;

    int qcode, keycode;

    qcode = qemu_input_key_value_to_qcode(evt->u.key.data->key);

    if (qcode >= ARRAY_SIZE(qcode_to_adb_keycode)) {

        return;

    }

    keycode = qcode_to_adb_keycode[qcode];

    if (evt->u.key.data->down == false) { /* if key release event */

        keycode = keycode | 0x80;   /* create keyboard break code */

    }

    adb_kbd_put_keycode(s, keycode);

}


static void nvram_writew (void *opaque, target_phys_addr_t addr, uint32_t value)

{

    M48t59State *NVRAM = opaque;

    m48t59_write(NVRAM, addr, (value >> 8) & 0xff);

    m48t59_write(NVRAM, addr + 1, value & 0xff);

}


void dsputilenc_init_mmx(DSPContext* c, AVCodecContext *avctx)

{

    if (mm_flags & FF_MM_MMX) {

        const int dct_algo = avctx->dct_algo;

        if(dct_algo==FF_DCT_AUTO || dct_algo==FF_DCT_MMX){

            if(mm_flags & FF_MM_SSE2){

                c->fdct = ff_fdct_sse2;

            }else if(mm_flags & FF_MM_MMX2){

                c->fdct = ff_fdct_mmx2;

            }else{

                c->fdct = ff_fdct_mmx;

            }

        }

        c->get_pixels = get_pixels_mmx;

        c->diff_pixels = diff_pixels_mmx;

        c->pix_sum = pix_sum16_mmx;

        c->diff_bytes= diff_bytes_mmx;

        c->sum_abs_dctelem= sum_abs_dctelem_mmx;

        c->hadamard8_diff[0]= hadamard8_diff16_mmx;

        c->hadamard8_diff[1]= hadamard8_diff_mmx;

        c->pix_norm1 = pix_norm1_mmx;

        c->sse[0] = (mm_flags & FF_MM_SSE2) ? sse16_sse2 : sse16_mmx;

          c->sse[1] = sse8_mmx;

        c->vsad[4]= vsad_intra16_mmx;

        c->nsse[0] = nsse16_mmx;

        c->nsse[1] = nsse8_mmx;

        if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

            c->vsad[0] = vsad16_mmx;

        }

        if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

            c->try_8x8basis= try_8x8basis_mmx;

        }

        c->add_8x8basis= add_8x8basis_mmx;

        c->ssd_int8_vs_int16 = ssd_int8_vs_int16_mmx;

        if (mm_flags & FF_MM_MMX2) {

            c->sum_abs_dctelem= sum_abs_dctelem_mmx2;

            c->hadamard8_diff[0]= hadamard8_diff16_mmx2;

            c->hadamard8_diff[1]= hadamard8_diff_mmx2;

            c->vsad[4]= vsad_intra16_mmx2;

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->vsad[0] = vsad16_mmx2;

            }

            c->sub_hfyu_median_prediction= sub_hfyu_median_prediction_mmx2;

        }

        if(mm_flags & FF_MM_SSE2){

            c->get_pixels = get_pixels_sse2;

            c->sum_abs_dctelem= sum_abs_dctelem_sse2;

            c->hadamard8_diff[0]= hadamard8_diff16_sse2;

            c->hadamard8_diff[1]= hadamard8_diff_sse2;

#if CONFIG_LPC

            c->lpc_compute_autocorr = ff_lpc_compute_autocorr_sse2;

#endif

        }

#if HAVE_SSSE3

        if(mm_flags & FF_MM_SSSE3){

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->try_8x8basis= try_8x8basis_ssse3;

            }

            c->add_8x8basis= add_8x8basis_ssse3;

            c->sum_abs_dctelem= sum_abs_dctelem_ssse3;

            c->hadamard8_diff[0]= hadamard8_diff16_ssse3;

            c->hadamard8_diff[1]= hadamard8_diff_ssse3;

        }

#endif

        if(mm_flags & FF_MM_3DNOW){

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->try_8x8basis= try_8x8basis_3dnow;

            }

            c->add_8x8basis= add_8x8basis_3dnow;

        }

    }

    dsputil_init_pix_mmx(c, avctx);

}


PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)

{

    PCIBus *bus;

    do {

         bus = dev->bus;

         pin = bus->map_irq(dev, pin);

         dev = bus->parent_dev;

    } while (dev);

    assert(bus->route_intx_to_irq);

    return bus->route_intx_to_irq(bus->irq_opaque, pin);

}


static void uhci_frame_timer(void *opaque)

{

    UHCIState *s = opaque;

    int64_t expire_time;

    uint32_t frame_addr, link, old_td_ctrl, val, int_mask;

    int cnt, ret;

    UHCI_TD td;

    UHCI_QH qh;

    uint32_t old_async_qh;

    if (!(s->cmd & UHCI_CMD_RS)) {

        qemu_del_timer(s->frame_timer);

        /* set hchalted bit in status - UHCI11D 2.1.2 */

        s->status |= UHCI_STS_HCHALTED;

        return;

    }

    /* Complete the previous frame.  */

    s->frnum = (s->frnum + 1) & 0x7ff;

    if (s->pending_int_mask) {

        s->status2 |= s->pending_int_mask;

        s->status |= UHCI_STS_USBINT;

        uhci_update_irq(s);

    }

    old_async_qh = s->async_qh;

    frame_addr = s->fl_base_addr + ((s->frnum & 0x3ff) << 2);

    cpu_physical_memory_read(frame_addr, (uint8_t *)&link, 4);

    le32_to_cpus(&link);

    int_mask = 0;

    cnt = FRAME_MAX_LOOPS;

    while ((link & 1) == 0) {

        if (--cnt == 0)

            break;

        /* valid frame */

        if (link & 2) {

            /* QH */

            if (link == s->async_qh) {

                /* We've found a previously issues packet.

                   Nothing else to do.  */

                old_async_qh = 0;

                break;

            }

            cpu_physical_memory_read(link & ~0xf, (uint8_t *)&qh, sizeof(qh));

            le32_to_cpus(&qh.link);

            le32_to_cpus(&qh.el_link);

        depth_first:

            if (qh.el_link & 1) {

                /* no element : go to next entry */

                link = qh.link;

            } else if (qh.el_link & 2) {

                /* QH */

                link = qh.el_link;

            } else if (s->async_qh) {

                /* We can only cope with one pending packet.  Keep looking

                   for the previously issued packet.  */

                link = qh.link;

            } else {

                /* TD */

                if (--cnt == 0)

                    break;

                cpu_physical_memory_read(qh.el_link & ~0xf,

                                         (uint8_t *)&td, sizeof(td));

                le32_to_cpus(&td.link);

                le32_to_cpus(&td.ctrl);

                le32_to_cpus(&td.token);

                le32_to_cpus(&td.buffer);

                old_td_ctrl = td.ctrl;

                ret = uhci_handle_td(s, &td, &int_mask, 0);

                /* update the status bits of the TD */

                if (old_td_ctrl != td.ctrl) {

                    val = cpu_to_le32(td.ctrl);

                    cpu_physical_memory_write((qh.el_link & ~0xf) + 4,

                                              (const uint8_t *)&val,

                                              sizeof(val));

                }

                if (ret < 0)

                    break; /* interrupted frame */

                if (ret == 2) {

                    s->async_qh = link;

                } else if (ret == 0) {

                    /* update qh element link */

                    qh.el_link = td.link;

                    val = cpu_to_le32(qh.el_link);

                    cpu_physical_memory_write((link & ~0xf) + 4,

                                              (const uint8_t *)&val,

                                              sizeof(val));

                    if (qh.el_link & 4) {

                        /* depth first */

                        goto depth_first;

                    }

                }

                /* go to next entry */

                link = qh.link;

            }

        } else {

            /* TD */

            cpu_physical_memory_read(link & ~0xf, (uint8_t *)&td, sizeof(td));

            le32_to_cpus(&td.link);

            le32_to_cpus(&td.ctrl);

            le32_to_cpus(&td.token);

            le32_to_cpus(&td.buffer);

            /* Handle isochonous transfer.  */

            /* FIXME: might be more than one isoc in frame */

            old_td_ctrl = td.ctrl;

            ret = uhci_handle_td(s, &td, &int_mask, 0);

            /* update the status bits of the TD */

            if (old_td_ctrl != td.ctrl) {

                val = cpu_to_le32(td.ctrl);

                cpu_physical_memory_write((link & ~0xf) + 4,

                                          (const uint8_t *)&val,

                                          sizeof(val));

            }

            if (ret < 0)

                break; /* interrupted frame */

            if (ret == 2) {

                s->async_frame_addr = frame_addr;

            }

            link = td.link;

        }

    }

    s->pending_int_mask = int_mask;

    if (old_async_qh) {

        /* A previously started transfer has disappeared from the transfer

           list.  There's nothing useful we can do with it now, so just

           discard the packet and hope it wasn't too important.  */

#ifdef DEBUG

        printf("Discarding USB packet\n");

#endif

        usb_cancel_packet(&s->usb_packet);

        s->async_qh = 0;

    }

    /* prepare the timer for the next frame */

    expire_time = qemu_get_clock(vm_clock) +

        (ticks_per_sec / FRAME_TIMER_FREQ);

    qemu_mod_timer(s->frame_timer, expire_time);

}


static int block_save_iterate(QEMUFile *f, void *opaque)

{

    int ret;

    DPRINTF("Enter save live iterate submitted %d transferred %d\n",

            block_mig_state.submitted, block_mig_state.transferred);

    ret = flush_blks(f);

    if (ret) {

        blk_mig_cleanup();

        return ret;

    }

    blk_mig_reset_dirty_cursor();

    /* control the rate of transfer */

    while ((block_mig_state.submitted +

            block_mig_state.read_done) * BLOCK_SIZE <

           qemu_file_get_rate_limit(f)) {

        if (block_mig_state.bulk_completed == 0) {

            /* first finish the bulk phase */

            if (blk_mig_save_bulked_block(f) == 0) {

                /* finished saving bulk on all devices */

                block_mig_state.bulk_completed = 1;

            }

        } else {

            ret = blk_mig_save_dirty_block(f, 1);

            if (ret != 0) {

                /* no more dirty blocks */

                break;

            }

        }

    }

    if (ret < 0) {

        blk_mig_cleanup();

        return ret;

    }

    ret = flush_blks(f);

    if (ret) {

        blk_mig_cleanup();

        return ret;

    }

    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

    return 0;

}


sdhci_readfn(void *opaque, hwaddr offset, unsigned size)

{

    SDHCIState *s = (SDHCIState *)opaque;

    return SDHCI_GET_CLASS(s)->mem_read(s, offset, size);

}


void migrate_fd_error(MigrationState *s)

{

    DPRINTF("setting error state\n");

    s->state = MIG_STATE_ERROR;

    notifier_list_notify(&migration_state_notifiers, s);

    migrate_fd_cleanup(s);

}


static int virtio_scsi_load(QEMUFile *f, void *opaque, int version_id)

{

    VirtIOSCSI *s = opaque;

    virtio_load(&s->vdev, f);

    return 0;

}


static int ebml_read_ascii(AVIOContext *pb, int size, char **str)

{

    av_free(*str);

    /* EBML strings are usually not 0-terminated, so we allocate one

     * byte more, read the string and NULL-terminate it ourselves. */

    if (!(*str = av_malloc(size + 1)))

        return AVERROR(ENOMEM);

    if (avio_read(pb, (uint8_t *) *str, size) != size) {

        av_freep(str);

        return AVERROR(EIO);

    }

    (*str)[size] = '\0';

    return 0;

}


ARITH3(addlv)

ARITH3(sublv)

ARITH3(addqv)

ARITH3(subqv)

ARITH3(umulh)

ARITH3(mullv)

ARITH3(mulqv)

ARITH3(minub8)

ARITH3(minsb8)

ARITH3(minuw4)

ARITH3(minsw4)

ARITH3(maxub8)

ARITH3(maxsb8)

ARITH3(maxuw4)

ARITH3(maxsw4)

ARITH3(perr)

#define MVIOP2(name)                                    \

static inline void glue(gen_, name)(int rb, int rc)     \

{                                                       \

    if (unlikely(rc == 31))                             \

        return;                                         \

    if (unlikely(rb == 31))                             \

        tcg_gen_movi_i64(cpu_ir[rc], 0);                \

    else                                                \

        gen_helper_ ## name (cpu_ir[rc], cpu_ir[rb]);   \

}

MVIOP2(pklb)

MVIOP2(pkwb)

MVIOP2(unpkbl)

MVIOP2(unpkbw)

static void gen_cmp(TCGCond cond, int ra, int rb, int rc,

                    int islit, uint8_t lit)

{

    TCGv va, vb;

    if (unlikely(rc == 31)) {

        return;

    }

    if (ra == 31) {

        va = tcg_const_i64(0);

    } else {

        va = cpu_ir[ra];

    }

    if (islit) {

        vb = tcg_const_i64(lit);

    } else {

        vb = cpu_ir[rb];

    }

    tcg_gen_setcond_i64(cond, cpu_ir[rc], va, vb);

    if (ra == 31) {

        tcg_temp_free(va);

    }

    if (islit) {

        tcg_temp_free(vb);

    }

}


void ppc_store_sdr1(CPUPPCState *env, target_ulong value)

{

    LOG_MMU("%s: " TARGET_FMT_lx "\n", __func__, value);

    if (env->spr[SPR_SDR1] != value) {

        env->spr[SPR_SDR1] = value;

#if defined(TARGET_PPC64)

        if (env->mmu_model & POWERPC_MMU_64) {

            target_ulong htabsize = value & SDR_64_HTABSIZE;

            if (htabsize > 28) {

                fprintf(stderr, "Invalid HTABSIZE 0x" TARGET_FMT_lx

                        " stored in SDR1\n", htabsize);

                htabsize = 28;

            }

            env->htab_mask = (1ULL << (htabsize + 18)) - 1;

            env->htab_base = value & SDR_64_HTABORG;

        } else

#endif /* defined(TARGET_PPC64) */

        {

            /* FIXME: Should check for valid HTABMASK values */

            env->htab_mask = ((value & SDR_32_HTABMASK) << 16) | 0xFFFF;

            env->htab_base = value & SDR_32_HTABORG;

        }

        tlb_flush(env, 1);

    }

}


void stream_start(BlockDriverState *bs, BlockDriverState *base,

                  const char *backing_file_str, int64_t speed,

                  BlockdevOnError on_error,

                  BlockCompletionFunc *cb,

                  void *opaque, Error **errp)

{

    StreamBlockJob *s;

    s = block_job_create(&stream_job_driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->base = base;

    s->backing_file_str = g_strdup(backing_file_str);

    s->on_error = on_error;

    s->common.co = qemu_coroutine_create(stream_run);

    trace_stream_start(bs, base, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


static void clear_sel(IPMIBmcSim *ibs,

                      uint8_t *cmd, unsigned int cmd_len,

                      uint8_t *rsp, unsigned int *rsp_len,

                      unsigned int max_rsp_len)

{

    IPMI_CHECK_CMD_LEN(8);

    IPMI_CHECK_RESERVATION(2, ibs->sel.reservation);

    if (cmd[4] != 'C' || cmd[5] != 'L' || cmd[6] != 'R') {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    if (cmd[7] == 0xaa) {

        ibs->sel.next_free = 0;

        ibs->sel.overflow = 0;

        set_timestamp(ibs, ibs->sdr.last_clear);

        IPMI_ADD_RSP_DATA(1); /* Erasure complete */

        sel_inc_reservation(&ibs->sel);

    } else if (cmd[7] == 0) {

        IPMI_ADD_RSP_DATA(1); /* Erasure complete */

    } else {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

}


int ff_spatial_idwt_init2(DWTContext *d, IDWTELEM *buffer, int width, int height,

                          int stride, enum dwt_type type, int decomposition_count,

                          IDWTELEM *temp)

{

    int level;

    d->buffer = buffer;

    d->width = width;

    d->height = height;

    d->stride = stride;

    d->decomposition_count = decomposition_count;

    d->temp = temp + 8;

    for(level=decomposition_count-1; level>=0; level--){

        int hl = height >> level;

        int stride_l = stride << level;

        switch(type){

        case DWT_DIRAC_DD9_7:

            spatial_compose_dd97i_init(d->cs+level, buffer, hl, stride_l);

            break;

        case DWT_DIRAC_LEGALL5_3:

            spatial_compose53i_init2(d->cs+level, buffer, hl, stride_l);

            break;

        case DWT_DIRAC_DD13_7:

            spatial_compose_dd137i_init(d->cs+level, buffer, hl, stride_l);

            break;

        case DWT_DIRAC_HAAR0:

        case DWT_DIRAC_HAAR1:

            d->cs[level].y = 1;

            break;

        case DWT_DIRAC_DAUB9_7:

            spatial_compose97i_init2(d->cs+level, buffer, hl, stride_l);

            break;

        default:

            d->cs[level].y = 0;

            break;

        }

    }

    switch (type) {

    case DWT_DIRAC_DD9_7:

        d->spatial_compose = spatial_compose_dd97i_dy;

        d->vertical_compose_l0 = (void*)vertical_compose53iL0;

        d->vertical_compose_h0 = (void*)vertical_compose_dd97iH0;

        d->horizontal_compose = horizontal_compose_dd97i;

        d->support = 7;

        break;

    case DWT_DIRAC_LEGALL5_3:

        d->spatial_compose = spatial_compose_dirac53i_dy;

        d->vertical_compose_l0 = (void*)vertical_compose53iL0;

        d->vertical_compose_h0 = (void*)vertical_compose_dirac53iH0;

        d->horizontal_compose = horizontal_compose_dirac53i;

        d->support = 3;

        break;

    case DWT_DIRAC_DD13_7:

        d->spatial_compose = spatial_compose_dd137i_dy;

        d->vertical_compose_l0 = (void*)vertical_compose_dd137iL0;

        d->vertical_compose_h0 = (void*)vertical_compose_dd97iH0;

        d->horizontal_compose = horizontal_compose_dd137i;

        d->support = 7;

        break;

    case DWT_DIRAC_HAAR0:

    case DWT_DIRAC_HAAR1:

        d->spatial_compose = spatial_compose_haari_dy;

        d->vertical_compose = (void*)vertical_compose_haar;

        if (type == DWT_DIRAC_HAAR0)

            d->horizontal_compose = horizontal_compose_haar0i;

        else

            d->horizontal_compose = horizontal_compose_haar1i;

        d->support = 1;

        break;

    case DWT_DIRAC_FIDELITY:

        d->spatial_compose = spatial_compose_fidelity;

        d->vertical_compose_l0 = (void*)vertical_compose_fidelityiL0;

        d->vertical_compose_h0 = (void*)vertical_compose_fidelityiH0;

        d->horizontal_compose = horizontal_compose_fidelityi;

        break;

    case DWT_DIRAC_DAUB9_7:

        d->spatial_compose = spatial_compose_daub97i_dy;

        d->vertical_compose_l0 = (void*)vertical_compose_daub97iL0;

        d->vertical_compose_h0 = (void*)vertical_compose_daub97iH0;

        d->vertical_compose_l1 = (void*)vertical_compose_daub97iL1;

        d->vertical_compose_h1 = (void*)vertical_compose_daub97iH1;

        d->horizontal_compose = horizontal_compose_daub97i;

        d->support = 5;

        break;

    default:

        av_log(NULL, AV_LOG_ERROR, "Unknown wavelet type %d\n", type);

        return -1;

    }

    if (HAVE_MMX) ff_spatial_idwt_init_mmx(d, type);

    return 0;

}


static void m68k_cpu_realizefn(DeviceState *dev, Error **errp)

{

    M68kCPU *cpu = M68K_CPU(dev);

    M68kCPUClass *mcc = M68K_CPU_GET_CLASS(dev);

    m68k_cpu_init_gdb(cpu);

    cpu_reset(CPU(cpu));

    mcc->parent_realize(dev, errp);

}


void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)

{

    int len, count, i;

    NetClientState *ncs[MAX_QUEUE_NUM];

    if (nb_args != 2) {

        return;

    }

    len = strlen(str);

    readline_set_completion_index(rs, len);

    count = qemu_find_net_clients_except(NULL, ncs, NET_CLIENT_OPTIONS_KIND_NIC,

                                         MAX_QUEUE_NUM);

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

        QemuOpts *opts;

        const char *name = ncs[i]->name;

        if (strncmp(str, name, len)) {

            continue;

        }

        opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), name);

        if (opts) {

            readline_add_completion(rs, name);

        }

    }

}


static void caps_to_network(RDMACapabilities *cap)

{

    cap->version = htonl(cap->version);

    cap->flags = htonl(cap->flags);

}


static void piix4_acpi_system_hot_add_init(PCIBus *bus, PIIX4PMState *s)

{

    register_ioport_write(GPE_BASE, GPE_LEN, 1, gpe_writeb, s);

    register_ioport_read(GPE_BASE, GPE_LEN, 1,  gpe_readb, s);

    acpi_gpe_blk(&s->ar, GPE_BASE);

    register_ioport_read(PCI_UP_BASE, 4, 4, pci_up_read, s);

    register_ioport_read(PCI_DOWN_BASE, 4, 4, pci_down_read, s);

    register_ioport_write(PCI_EJ_BASE, 4, 4, pciej_write, bus);

    register_ioport_read(PCI_EJ_BASE, 4, 4,  pciej_read, bus);

    register_ioport_write(PCI_RMV_BASE, 4, 4, pcirmv_write, s);

    register_ioport_read(PCI_RMV_BASE, 4, 4,  pcirmv_read, s);

    pci_bus_hotplug(bus, piix4_device_hotplug, &s->dev.qdev);

}


void qmp_drive_backup(const char *device, const char *target,

                      bool has_format, const char *format,

                      enum MirrorSyncMode sync,

                      bool has_mode, enum NewImageMode mode,

                      bool has_speed, int64_t speed,

                      bool has_on_source_error, BlockdevOnError on_source_error,

                      bool has_on_target_error, BlockdevOnError on_target_error,

                      Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    BlockDriverState *source = NULL;

    AioContext *aio_context;

    BlockDriver *drv = NULL;

    Error *local_err = NULL;

    int flags;

    int64_t size;

    int ret;

    if (!has_speed) {

        speed = 0;

    }

    if (!has_on_source_error) {

        on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_on_target_error) {

        on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_mode) {

        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    /* Although backup_run has this check too, we need to use bs->drv below, so

     * do an early check redundantly. */

    if (!bdrv_is_inserted(bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        goto out;

    }

    if (!has_format) {

        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;

    }

    if (format) {

        drv = bdrv_find_format(format);

        if (!drv) {

            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

            goto out;

        }

    }

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {

        goto out;

    }

    flags = bs->open_flags | BDRV_O_RDWR;

    /* See if we have a backing HD we can use to create our new image

     * on top of. */

    if (sync == MIRROR_SYNC_MODE_TOP) {

        source = bs->backing_hd;

        if (!source) {

            sync = MIRROR_SYNC_MODE_FULL;

        }

    }

    if (sync == MIRROR_SYNC_MODE_NONE) {

        source = bs;

    }

    size = bdrv_getlength(bs);

    if (size < 0) {

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

        goto out;

    }

    if (mode != NEW_IMAGE_MODE_EXISTING) {

        assert(format && drv);

        if (source) {

            bdrv_img_create(target, format, source->filename,

                            source->drv->format_name, NULL,

                            size, flags, &local_err, false);

        } else {

            bdrv_img_create(target, format, NULL, NULL, NULL,

                            size, flags, &local_err, false);

        }

    }

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    target_bs = NULL;

    ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto out;

    }

    bdrv_set_aio_context(target_bs, aio_context);

    backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,

                 block_job_cb, bs, &local_err);

    if (local_err != NULL) {

        bdrv_unref(target_bs);

        error_propagate(errp, local_err);

        goto out;

    }

out:

    aio_context_release(aio_context);

}


static uint32_t parse_enumeration(char *str,
    EnumTable *table, uint32_t not_found_value)
{
    uint32_t ret = not_found_value;
    while (table->name != NULL) {
        if (strcmp(table->name, str) == 0) {
            ret = table->value;
            break;
        }
        table++;
    }
    return ret;
}


static int mov_probe(AVProbeData *p)

{

    unsigned int offset;

    uint32_t tag;

    int score = 0;

    /* check file header */

    offset = 0;

    for (;;) {

        /* ignore invalid offset */

        if ((offset + 8) > (unsigned int)p->buf_size)

            return score;

        tag = AV_RL32(p->buf + offset + 4);

        switch(tag) {

        /* check for obvious tags */

        case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */

        case MKTAG('m','o','o','v'):

        case MKTAG('m','d','a','t'):

        case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */

        case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */

        case MKTAG('f','t','y','p'):

            return AVPROBE_SCORE_MAX;

        /* those are more common words, so rate then a bit less */

        case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */

        case MKTAG('w','i','d','e'):

        case MKTAG('f','r','e','e'):

        case MKTAG('j','u','n','k'):

        case MKTAG('p','i','c','t'):

            return AVPROBE_SCORE_MAX - 5;

        case MKTAG(0x82,0x82,0x7f,0x7d):

        case MKTAG('s','k','i','p'):

        case MKTAG('u','u','i','d'):

        case MKTAG('p','r','f','l'):

            offset = AV_RB32(p->buf+offset) + offset;

            /* if we only find those cause probedata is too small at least rate them */

            score = AVPROBE_SCORE_MAX - 50;

            break;

        default:

            /* unrecognized tag */

            return score;

        }

    }

}


static void virtser_port_device_realize(DeviceState *dev, Error **errp)

{

    VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);

    VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);

    VirtIOSerialBus *bus = VIRTIO_SERIAL_BUS(qdev_get_parent_bus(dev));

    VirtIODevice *vdev = VIRTIO_DEVICE(bus->vser);

    int max_nr_ports;

    bool plugging_port0;

    Error *err = NULL;

    port->vser = bus->vser;

    port->bh = qemu_bh_new(flush_queued_data_bh, port);

    assert(vsc->have_data);

    /*

     * Is the first console port we're seeing? If so, put it up at

     * location 0. This is done for backward compatibility (old

     * kernel, new qemu).

     */

    plugging_port0 = vsc->is_console && !find_port_by_id(port->vser, 0);

    if (find_port_by_id(port->vser, port->id)) {

        error_setg(errp, "virtio-serial-bus: A port already exists at id %u",

                   port->id);

        return;

    }

    if (find_port_by_name(port->name)) {

        error_setg(errp, "virtio-serial-bus: A port already exists by name %s",

                   port->name);

        return;

    }

    if (port->id == VIRTIO_CONSOLE_BAD_ID) {

        if (plugging_port0) {

            port->id = 0;

        } else {

            port->id = find_free_port_id(port->vser);

            if (port->id == VIRTIO_CONSOLE_BAD_ID) {

                error_setg(errp, "virtio-serial-bus: Maximum port limit for "

                                 "this device reached");

                return;

            }

        }

    }

    max_nr_ports = virtio_tswap32(vdev, port->vser->config.max_nr_ports);

    if (port->id >= max_nr_ports) {

        error_setg(errp, "virtio-serial-bus: Out-of-range port id specified, "

                         "max. allowed: %u", max_nr_ports - 1);

        return;

    }

    vsc->realize(dev, &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

    port->elem.out_num = 0;

}


YUV2RGB(rgb8, uint8_t)

YUV2RGB(rgb16, uint16_t)

/* process exactly one decompressed row */

static void png_handle_row(PNGDecContext *s)

{

    uint8_t *ptr, *last_row;

    int got_line;

    if (!s->interlace_type) {

        ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;

        if (s->y == 0)

            last_row = s->last_row;

        else

            last_row = ptr - s->image_linesize;

        png_filter_row(&s->dsp, ptr, s->crow_buf[0], s->crow_buf + 1,

                       last_row, s->row_size, s->bpp);

        /* loco lags by 1 row so that it doesn't interfere with top prediction */

        if (s->filter_type == PNG_FILTER_TYPE_LOCO && s->y > 0) {

            if (s->bit_depth == 16) {

                deloco_rgb16((uint16_t *)(ptr - s->image_linesize), s->row_size / 2,

                             s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);

            } else {

                deloco_rgb8(ptr - s->image_linesize, s->row_size,

                            s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);

            }

        }

        s->y++;

        if (s->y == s->cur_h) {

            s->state |= PNG_ALLIMAGE;

            if (s->filter_type == PNG_FILTER_TYPE_LOCO) {

                if (s->bit_depth == 16) {

                    deloco_rgb16((uint16_t *)ptr, s->row_size / 2,

                                 s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);

                } else {

                    deloco_rgb8(ptr, s->row_size,

                                s->color_type == PNG_COLOR_TYPE_RGB_ALPHA);

                }

            }

        }

    } else {

        got_line = 0;

        for (;;) {

            ptr = s->image_buf + s->image_linesize * (s->y + s->y_offset) + s->x_offset * s->bpp;

            if ((ff_png_pass_ymask[s->pass] << (s->y & 7)) & 0x80) {

                /* if we already read one row, it is time to stop to

                 * wait for the next one */

                if (got_line)

                    break;

                png_filter_row(&s->dsp, s->tmp_row, s->crow_buf[0], s->crow_buf + 1,

                               s->last_row, s->pass_row_size, s->bpp);

                FFSWAP(uint8_t *, s->last_row, s->tmp_row);

                FFSWAP(unsigned int, s->last_row_size, s->tmp_row_size);

                got_line = 1;

            }

            if ((png_pass_dsp_ymask[s->pass] << (s->y & 7)) & 0x80) {

                png_put_interlaced_row(ptr, s->cur_w, s->bits_per_pixel, s->pass,

                                       s->color_type, s->last_row);

            }

            s->y++;

            if (s->y == s->cur_h) {

                memset(s->last_row, 0, s->row_size);

                for (;;) {

                    if (s->pass == NB_PASSES - 1) {

                        s->state |= PNG_ALLIMAGE;

                        goto the_end;

                    } else {

                        s->pass++;

                        s->y = 0;

                        s->pass_row_size = ff_png_pass_row_size(s->pass,

                                                                s->bits_per_pixel,

                                                                s->cur_w);

                        s->crow_size = s->pass_row_size + 1;

                        if (s->pass_row_size != 0)

                            break;

                        /* skip pass if empty row */

                    }

                }

            }

        }

the_end:;

    }

}


static void gen_iccci(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    /* interpreted as no-op */

#endif

}


void qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_only)

{

    QJSON *vmdesc;

    int vmdesc_len;

    SaveStateEntry *se;

    int ret;

    bool in_postcopy = migration_in_postcopy();

    trace_savevm_state_complete_precopy();

    cpu_synchronize_all_states();

    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {

        if (!se->ops ||

            (in_postcopy && se->ops->save_live_complete_postcopy) ||

            (in_postcopy && !iterable_only) ||

            !se->ops->save_live_complete_precopy) {

            continue;

        }

        if (se->ops && se->ops->is_active) {

            if (!se->ops->is_active(se->opaque)) {

                continue;

            }

        }

        trace_savevm_section_start(se->idstr, se->section_id);

        save_section_header(f, se, QEMU_VM_SECTION_END);

        ret = se->ops->save_live_complete_precopy(f, se->opaque);

        trace_savevm_section_end(se->idstr, se->section_id, ret);

        save_section_footer(f, se);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

            return;

        }

    }

    if (iterable_only) {

        return;

    }

    vmdesc = qjson_new();

    json_prop_int(vmdesc, "page_size", qemu_target_page_size());

    json_start_array(vmdesc, "devices");

    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {

        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {

            continue;

        }

        if (se->vmsd && !vmstate_save_needed(se->vmsd, se->opaque)) {

            trace_savevm_section_skip(se->idstr, se->section_id);

            continue;

        }

        trace_savevm_section_start(se->idstr, se->section_id);

        json_start_object(vmdesc, NULL);

        json_prop_str(vmdesc, "name", se->idstr);

        json_prop_int(vmdesc, "instance_id", se->instance_id);

        save_section_header(f, se, QEMU_VM_SECTION_FULL);

        vmstate_save(f, se, vmdesc);

        trace_savevm_section_end(se->idstr, se->section_id, 0);

        save_section_footer(f, se);

        json_end_object(vmdesc);

    }

    if (!in_postcopy) {

        /* Postcopy stream will still be going */

        qemu_put_byte(f, QEMU_VM_EOF);

    }

    json_end_array(vmdesc);

    qjson_finish(vmdesc);

    vmdesc_len = strlen(qjson_get_str(vmdesc));

    if (should_send_vmdesc()) {

        qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);

        qemu_put_be32(f, vmdesc_len);

        qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);

    }

    qjson_destroy(vmdesc);

    qemu_fflush(f);

}


static void openrisc_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    OpenRISCCPU *cpu = OPENRISC_CPU(obj);

    static int inited;

    cs->env_ptr = &cpu->env;

    cpu_exec_init(cs, &error_abort);

#ifndef CONFIG_USER_ONLY

    cpu_openrisc_mmu_init(cpu);

#endif

    if (tcg_enabled() && !inited) {

        inited = 1;

        openrisc_translate_init();

    }

}


int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id,

                      int apply_defdispwin, AVBufferRef **vps_list, AVCodecContext *avctx)

{

    HEVCWindow *ow;

    int ret = 0;

    int log2_diff_max_min_transform_block_size;

    int bit_depth_chroma, start, vui_present, sublayer_ordering_info;

    int i;

    // Coded parameters

    sps->vps_id = get_bits(gb, 4);

    if (sps->vps_id >= HEVC_MAX_VPS_COUNT) {

        av_log(avctx, AV_LOG_ERROR, "VPS id out of range: %d\n", sps->vps_id);

    if (vps_list && !vps_list[sps->vps_id]) {

        av_log(avctx, AV_LOG_ERROR, "VPS %d does not exist\n",

               sps->vps_id);

    sps->max_sub_layers = get_bits(gb, 3) + 1;

    if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) {

        av_log(avctx, AV_LOG_ERROR, "sps_max_sub_layers out of range: %d\n",

               sps->max_sub_layers);

    skip_bits1(gb); // temporal_id_nesting_flag

    parse_ptl(gb, avctx, &sps->ptl, sps->max_sub_layers);

    *sps_id = get_ue_golomb_long(gb);

    if (*sps_id >= HEVC_MAX_SPS_COUNT) {

        av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", *sps_id);

    sps->chroma_format_idc = get_ue_golomb_long(gb);

    if (sps->chroma_format_idc != 1) {

        avpriv_report_missing_feature(avctx, "chroma_format_idc %d",

                                      sps->chroma_format_idc);

        ret = AVERROR_PATCHWELCOME;

    if (sps->chroma_format_idc == 3)

        sps->separate_colour_plane_flag = get_bits1(gb);

    sps->width  = get_ue_golomb_long(gb);

    sps->height = get_ue_golomb_long(gb);

    if ((ret = av_image_check_size(sps->width,

                                   sps->height, 0, avctx)) < 0)

    if (get_bits1(gb)) { // pic_conformance_flag

        //TODO: * 2 is only valid for 420

        sps->pic_conf_win.left_offset   = get_ue_golomb_long(gb) * 2;

        sps->pic_conf_win.right_offset  = get_ue_golomb_long(gb) * 2;

        sps->pic_conf_win.top_offset    = get_ue_golomb_long(gb) * 2;

        sps->pic_conf_win.bottom_offset = get_ue_golomb_long(gb) * 2;

        if (avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {

            av_log(avctx, AV_LOG_DEBUG,

                   "discarding sps conformance window, "

                   "original values are l:%u r:%u t:%u b:%u\n",

                   sps->pic_conf_win.left_offset,

                   sps->pic_conf_win.right_offset,

                   sps->pic_conf_win.top_offset,

                   sps->pic_conf_win.bottom_offset);

            sps->pic_conf_win.left_offset   =

            sps->pic_conf_win.right_offset  =

            sps->pic_conf_win.top_offset    =

            sps->pic_conf_win.bottom_offset = 0;

        sps->output_window = sps->pic_conf_win;

    sps->bit_depth   = get_ue_golomb_long(gb) + 8;

    bit_depth_chroma = get_ue_golomb_long(gb) + 8;

    if (bit_depth_chroma != sps->bit_depth) {

        av_log(avctx, AV_LOG_ERROR,

               "Luma bit depth (%d) is different from chroma bit depth (%d), "

               "this is unsupported.\n",

               sps->bit_depth, bit_depth_chroma);

    ret = map_pixel_format(avctx, sps);

    if (ret < 0)

    sps->log2_max_poc_lsb = get_ue_golomb_long(gb) + 4;

    if (sps->log2_max_poc_lsb > 16) {

        av_log(avctx, AV_LOG_ERROR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n",

               sps->log2_max_poc_lsb - 4);

    sublayer_ordering_info = get_bits1(gb);

    start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1;

    for (i = start; i < sps->max_sub_layers; i++) {

        sps->temporal_layer[i].max_dec_pic_buffering = get_ue_golomb_long(gb) + 1;

        sps->temporal_layer[i].num_reorder_pics      = get_ue_golomb_long(gb);

        sps->temporal_layer[i].max_latency_increase  = get_ue_golomb_long(gb) - 1;

        if (sps->temporal_layer[i].max_dec_pic_buffering > HEVC_MAX_DPB_SIZE) {

            av_log(avctx, AV_LOG_ERROR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n",

                   sps->temporal_layer[i].max_dec_pic_buffering - 1);

        if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) {

            av_log(avctx, AV_LOG_WARNING, "sps_max_num_reorder_pics out of range: %d\n",

                   sps->temporal_layer[i].num_reorder_pics);

            if (avctx->err_recognition & AV_EF_EXPLODE ||

                sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) {

            sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1;

    if (!sublayer_ordering_info) {

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

            sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering;

            sps->temporal_layer[i].num_reorder_pics      = sps->temporal_layer[start].num_reorder_pics;

            sps->temporal_layer[i].max_latency_increase  = sps->temporal_layer[start].max_latency_increase;

    sps->log2_min_cb_size                    = get_ue_golomb_long(gb) + 3;

    sps->log2_diff_max_min_coding_block_size = get_ue_golomb_long(gb);

    sps->log2_min_tb_size                    = get_ue_golomb_long(gb) + 2;

    log2_diff_max_min_transform_block_size   = get_ue_golomb_long(gb);

    sps->log2_max_trafo_size                 = log2_diff_max_min_transform_block_size +

                                               sps->log2_min_tb_size;

    if (sps->log2_min_tb_size >= sps->log2_min_cb_size) {

        av_log(avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");

    sps->max_transform_hierarchy_depth_inter = get_ue_golomb_long(gb);

    sps->max_transform_hierarchy_depth_intra = get_ue_golomb_long(gb);

    sps->scaling_list_enable_flag = get_bits1(gb);

    if (sps->scaling_list_enable_flag) {

        set_default_scaling_list_data(&sps->scaling_list);

        if (get_bits1(gb)) {

            ret = scaling_list_data(gb, avctx, &sps->scaling_list);

            if (ret < 0)

    sps->amp_enabled_flag = get_bits1(gb);

    sps->sao_enabled      = get_bits1(gb);

    sps->pcm_enabled_flag = get_bits1(gb);

    if (sps->pcm_enabled_flag) {

        sps->pcm.bit_depth   = get_bits(gb, 4) + 1;

        sps->pcm.bit_depth_chroma = get_bits(gb, 4) + 1;

        sps->pcm.log2_min_pcm_cb_size = get_ue_golomb_long(gb) + 3;

        sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size +

                                        get_ue_golomb_long(gb);

        if (sps->pcm.bit_depth > sps->bit_depth) {

            av_log(avctx, AV_LOG_ERROR,

                   "PCM bit depth (%d) is greater than normal bit depth (%d)\n",

                   sps->pcm.bit_depth, sps->bit_depth);

        sps->pcm.loop_filter_disable_flag = get_bits1(gb);

    sps->nb_st_rps = get_ue_golomb_long(gb);

    if (sps->nb_st_rps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) {

        av_log(avctx, AV_LOG_ERROR, "Too many short term RPS: %d.\n",

               sps->nb_st_rps);

    for (i = 0; i < sps->nb_st_rps; i++) {

        if ((ret = ff_hevc_decode_short_term_rps(gb, avctx, &sps->st_rps[i],

                                                 sps, 0)) < 0)

    sps->long_term_ref_pics_present_flag = get_bits1(gb);

    if (sps->long_term_ref_pics_present_flag) {

        sps->num_long_term_ref_pics_sps = get_ue_golomb_long(gb);

        for (i = 0; i < sps->num_long_term_ref_pics_sps; i++) {

            sps->lt_ref_pic_poc_lsb_sps[i]       = get_bits(gb, sps->log2_max_poc_lsb);

            sps->used_by_curr_pic_lt_sps_flag[i] = get_bits1(gb);

    sps->sps_temporal_mvp_enabled_flag          = get_bits1(gb);

    sps->sps_strong_intra_smoothing_enable_flag = get_bits1(gb);

    sps->vui.sar = (AVRational){0, 1};

    vui_present = get_bits1(gb);

    if (vui_present)

        decode_vui(gb, avctx, apply_defdispwin, sps);

    skip_bits1(gb); // sps_extension_flag

    if (apply_defdispwin) {

        sps->output_window.left_offset   += sps->vui.def_disp_win.left_offset;

        sps->output_window.right_offset  += sps->vui.def_disp_win.right_offset;

        sps->output_window.top_offset    += sps->vui.def_disp_win.top_offset;

        sps->output_window.bottom_offset += sps->vui.def_disp_win.bottom_offset;

    ow = &sps->output_window;

    if (ow->left_offset >= INT_MAX - ow->right_offset     ||

        ow->top_offset  >= INT_MAX - ow->bottom_offset    ||

        ow->left_offset + ow->right_offset  >= sps->width ||

        ow->top_offset  + ow->bottom_offset >= sps->height) {

        av_log(avctx, AV_LOG_WARNING, "Invalid cropping offsets: %u/%u/%u/%u\n",

               ow->left_offset, ow->right_offset, ow->top_offset, ow->bottom_offset);

        if (avctx->err_recognition & AV_EF_EXPLODE) {

        av_log(avctx, AV_LOG_WARNING,

               "Displaying the whole video surface.\n");

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

    // Inferred parameters

    sps->log2_ctb_size = sps->log2_min_cb_size +

                         sps->log2_diff_max_min_coding_block_size;

    sps->log2_min_pu_size = sps->log2_min_cb_size - 1;

    sps->ctb_width  = (sps->width  + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;

    sps->ctb_height = (sps->height + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;

    sps->ctb_size   = sps->ctb_width * sps->ctb_height;

    sps->min_cb_width  = sps->width  >> sps->log2_min_cb_size;

    sps->min_cb_height = sps->height >> sps->log2_min_cb_size;

    sps->min_tb_width  = sps->width  >> sps->log2_min_tb_size;

    sps->min_tb_height = sps->height >> sps->log2_min_tb_size;

    sps->min_pu_width  = sps->width  >> sps->log2_min_pu_size;

    sps->min_pu_height = sps->height >> sps->log2_min_pu_size;

    sps->qp_bd_offset = 6 * (sps->bit_depth - 8);

    if (sps->width  & ((1 << sps->log2_min_cb_size) - 1) ||

        sps->height & ((1 << sps->log2_min_cb_size) - 1)) {

        av_log(avctx, AV_LOG_ERROR, "Invalid coded frame dimensions.\n");

    if (sps->log2_ctb_size > HEVC_MAX_LOG2_CTB_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size);

    if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) {

        av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_inter out of range: %d\n",

               sps->max_transform_hierarchy_depth_inter);

    if (sps->max_transform_hierarchy_depth_intra > sps->log2_ctb_size - sps->log2_min_tb_size) {

        av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_intra out of range: %d\n",

               sps->max_transform_hierarchy_depth_intra);

    if (sps->log2_max_trafo_size > FFMIN(sps->log2_ctb_size, 5)) {

        av_log(avctx, AV_LOG_ERROR,

               "max transform block size out of range: %d\n",

               sps->log2_max_trafo_size);

    return 0;

err:

    return ret < 0 ? ret : AVERROR_INVALIDDATA;


static int eject_device(Monitor *mon, BlockDriverState *bs, int force)

{

    if (bdrv_is_inserted(bs)) {

        if (!force) {

            if (!bdrv_is_removable(bs)) {

                qerror_report(QERR_DEVICE_NOT_REMOVABLE,

                               bdrv_get_device_name(bs));

                return -1;

            }

            if (bdrv_is_locked(bs)) {

                qerror_report(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));

                return -1;

            }

        }

        bdrv_close(bs);

    }

    return 0;

}


int vnc_display_open(DisplayState *ds, const char *display)

{

    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;

    const char *options;

    int password = 0;

    int reverse = 0;

    int to_port = 0;

#ifdef CONFIG_VNC_TLS

    int tls = 0, x509 = 0;

#endif

    if (!vnc_display)

        return -1;

    vnc_display_close(ds);

    if (strcmp(display, "none") == 0)

	return 0;

    if (!(vs->display = strdup(display)))

	return -1;

    options = display;

    while ((options = strchr(options, ','))) {

	options++;

	if (strncmp(options, "password", 8) == 0) {

	    password = 1; /* Require password auth */

	} else if (strncmp(options, "reverse", 7) == 0) {

	    reverse = 1;

	} else if (strncmp(options, "to=", 3) == 0) {

            to_port = atoi(options+3) + 5900;

#ifdef CONFIG_VNC_TLS

	} else if (strncmp(options, "tls", 3) == 0) {

	    tls = 1; /* Require TLS */

	} else if (strncmp(options, "x509", 4) == 0) {

	    char *start, *end;

	    x509 = 1; /* Require x509 certificates */

	    if (strncmp(options, "x509verify", 10) == 0)

	        vs->tls.x509verify = 1; /* ...and verify client certs */

	    /* Now check for 'x509=/some/path' postfix

	     * and use that to setup x509 certificate/key paths */

	    start = strchr(options, '=');

	    end = strchr(options, ',');

	    if (start && (!end || (start < end))) {

		int len = end ? end-(start+1) : strlen(start+1);

		char *path = qemu_strndup(start + 1, len);

		VNC_DEBUG("Trying certificate path '%s'\n", path);

		if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {

		    fprintf(stderr, "Failed to find x509 certificates/keys in %s\n", path);

		    qemu_free(path);

		    qemu_free(vs->display);

		    vs->display = NULL;

		    return -1;

		}

		qemu_free(path);

	    } else {

		fprintf(stderr, "No certificate path provided\n");

		qemu_free(vs->display);

		vs->display = NULL;

		return -1;

	    }

#endif

	}

    }

    if (password) {

#ifdef CONFIG_VNC_TLS

	if (tls) {

	    vs->auth = VNC_AUTH_VENCRYPT;

	    if (x509) {

		VNC_DEBUG("Initializing VNC server with x509 password auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;

	    } else {

		VNC_DEBUG("Initializing VNC server with TLS password auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;

	    }

	} else {

#endif

	    VNC_DEBUG("Initializing VNC server with password auth\n");

	    vs->auth = VNC_AUTH_VNC;

#ifdef CONFIG_VNC_TLS

	    vs->subauth = VNC_AUTH_INVALID;

	}

#endif

    } else {

#ifdef CONFIG_VNC_TLS

	if (tls) {

	    vs->auth = VNC_AUTH_VENCRYPT;

	    if (x509) {

		VNC_DEBUG("Initializing VNC server with x509 no auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;

	    } else {

		VNC_DEBUG("Initializing VNC server with TLS no auth\n");

		vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;

	    }

	} else {

#endif

	    VNC_DEBUG("Initializing VNC server with no auth\n");

	    vs->auth = VNC_AUTH_NONE;

#ifdef CONFIG_VNC_TLS

	    vs->subauth = VNC_AUTH_INVALID;

	}

#endif

    }

    if (reverse) {

        /* connect to viewer */

        if (strncmp(display, "unix:", 5) == 0)

            vs->lsock = unix_connect(display+5);

        else

            vs->lsock = inet_connect(display, SOCK_STREAM);

        if (-1 == vs->lsock) {

            free(vs->display);

            vs->display = NULL;

            return -1;

        } else {

            int csock = vs->lsock;

            vs->lsock = -1;

            vnc_connect(vs, csock);

        }

        return 0;

    } else {

        /* listen for connects */

        char *dpy;

        dpy = qemu_malloc(256);

        if (strncmp(display, "unix:", 5) == 0) {

            pstrcpy(dpy, 256, "unix:");

            vs->lsock = unix_listen(display+5, dpy+5, 256-5);

        } else {

            vs->lsock = inet_listen(display, dpy, 256, SOCK_STREAM, 5900);

        }

        if (-1 == vs->lsock) {

            free(dpy);

            return -1;

        } else {

            free(vs->display);

            vs->display = dpy;

        }

    }

    return qemu_set_fd_handler2(vs->lsock, NULL, vnc_listen_read, NULL, vs);

}


static int need_output(void)

{

    int i;

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

        OutputStream *ost    = output_streams[i];

        OutputFile *of       = output_files[ost->file_index];

        AVFormatContext *os  = output_files[ost->file_index]->ctx;

        if (ost->is_past_recording_time ||

            (os->pb && avio_tell(os->pb) >= of->limit_filesize))

            continue;

        if (ost->frame_number >= ost->max_frames) {

            int j;

            for (j = 0; j < of->ctx->nb_streams; j++)

                output_streams[of->ost_index + j]->is_past_recording_time = 1;

            continue;

        }

        return 1;

    }

    return 0;

}


void qmp_migrate_set_speed(int64_t value, Error **errp)

{

    MigrationState *s;

    if (value < 0) {

        value = 0;

    }

    if (value > SIZE_MAX) {

        value = SIZE_MAX;

    }

    s = migrate_get_current();

    s->bandwidth_limit = value;

    if (s->file) {

        qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);

    }

}


void aio_set_event_notifier(AioContext *ctx,

                            EventNotifier *e,

                            bool is_external,

                            EventNotifierHandler *io_notify)

{

    AioHandler *node;

    QLIST_FOREACH(node, &ctx->aio_handlers, node) {

        if (node->e == e && !node->deleted) {

            break;

        }

    }

    /* Are we deleting the fd handler? */

    if (!io_notify) {

        if (node) {

            g_source_remove_poll(&ctx->source, &node->pfd);

            /* If the lock is held, just mark the node as deleted */

            if (ctx->walking_handlers) {

                node->deleted = 1;

                node->pfd.revents = 0;

            } else {

                /* Otherwise, delete it for real.  We can't just mark it as

                 * deleted because deleted nodes are only cleaned up after

                 * releasing the walking_handlers lock.

                 */

                QLIST_REMOVE(node, node);

                g_free(node);

            }

        }

    } else {

        if (node == NULL) {

            /* Alloc and insert if it's not already there */

            node = g_new0(AioHandler, 1);

            node->e = e;

            node->pfd.fd = (uintptr_t)event_notifier_get_handle(e);

            node->pfd.events = G_IO_IN;

            node->is_external = is_external;

            QLIST_INSERT_HEAD(&ctx->aio_handlers, node, node);

            g_source_add_poll(&ctx->source, &node->pfd);

        }

        /* Update handler with latest information */

        node->io_notify = io_notify;

    }

    aio_notify(ctx);

}


static av_cold int ulti_decode_init(AVCodecContext *avctx)

{

    UltimotionDecodeContext *s = avctx->priv_data;

    s->avctx = avctx;

    s->width = avctx->width;

    s->height = avctx->height;

    s->blocks = (s->width / 8) * (s->height / 8);

    avctx->pix_fmt = AV_PIX_FMT_YUV410P;

    s->ulti_codebook = ulti_codebook;

    s->frame = av_frame_alloc();

    if (!s->frame)

        return AVERROR(ENOMEM);

    return 0;

}


static void setup_vm_cmd(IVState *s, const char *cmd, bool msix)

{

    uint64_t barsize;

    s->qtest = qtest_start(cmd);

    s->pcibus = qpci_init_pc(NULL);

    s->dev = get_device(s->pcibus);

    s->reg_base = qpci_iomap(s->dev, 0, &barsize);

    g_assert_nonnull(s->reg_base);

    g_assert_cmpuint(barsize, ==, 256);

    if (msix) {

        qpci_msix_enable(s->dev);

    }

    s->mem_base = qpci_iomap(s->dev, 2, &barsize);

    g_assert_nonnull(s->mem_base);

    g_assert_cmpuint(barsize, ==, TMPSHMSIZE);

    qpci_device_enable(s->dev);

}