static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,

                   abi_ulong parent_tidptr, target_ulong newtls,

                   abi_ulong child_tidptr)

{

    CPUState *cpu = ENV_GET_CPU(env);

    int ret;

    TaskState *ts;

    CPUState *new_cpu;

    CPUArchState *new_env;

    unsigned int nptl_flags;

    sigset_t sigmask;

    /* Emulate vfork() with fork() */

    if (flags & CLONE_VFORK)

        flags &= ~(CLONE_VFORK | CLONE_VM);

    if (flags & CLONE_VM) {

        TaskState *parent_ts = (TaskState *)cpu->opaque;

        new_thread_info info;

        pthread_attr_t attr;

        ts = g_new0(TaskState, 1);

        init_task_state(ts);

        /* we create a new CPU instance. */

        new_env = cpu_copy(env);

        /* Init regs that differ from the parent.  */

        cpu_clone_regs(new_env, newsp);

        new_cpu = ENV_GET_CPU(new_env);

        new_cpu->opaque = ts;

        ts->bprm = parent_ts->bprm;

        ts->info = parent_ts->info;

        ts->signal_mask = parent_ts->signal_mask;

        nptl_flags = flags;

        flags &= ~CLONE_NPTL_FLAGS2;

        if (nptl_flags & CLONE_CHILD_CLEARTID) {

            ts->child_tidptr = child_tidptr;

        }

        if (nptl_flags & CLONE_SETTLS)

            cpu_set_tls (new_env, newtls);

        /* Grab a mutex so that thread setup appears atomic.  */

        pthread_mutex_lock(&clone_lock);

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

        pthread_mutex_init(&info.mutex, NULL);

        pthread_mutex_lock(&info.mutex);

        pthread_cond_init(&info.cond, NULL);

        info.env = new_env;

        if (nptl_flags & CLONE_CHILD_SETTID)

            info.child_tidptr = child_tidptr;

        if (nptl_flags & CLONE_PARENT_SETTID)

            info.parent_tidptr = parent_tidptr;

        ret = pthread_attr_init(&attr);

        ret = pthread_attr_setstacksize(&attr, NEW_STACK_SIZE);

        ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

        /* It is not safe to deliver signals until the child has finished

           initializing, so temporarily block all signals.  */

        sigfillset(&sigmask);

        sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);

        ret = pthread_create(&info.thread, &attr, clone_func, &info);

        /* TODO: Free new CPU state if thread creation failed.  */

        sigprocmask(SIG_SETMASK, &info.sigmask, NULL);

        pthread_attr_destroy(&attr);

        if (ret == 0) {

            /* Wait for the child to initialize.  */

            pthread_cond_wait(&info.cond, &info.mutex);

            ret = info.tid;

            if (flags & CLONE_PARENT_SETTID)

                put_user_u32(ret, parent_tidptr);

        } else {

            ret = -1;

        }

        pthread_mutex_unlock(&info.mutex);

        pthread_cond_destroy(&info.cond);

        pthread_mutex_destroy(&info.mutex);

        pthread_mutex_unlock(&clone_lock);

    } else {

        /* if no CLONE_VM, we consider it is a fork */

        if ((flags & ~(CSIGNAL | CLONE_NPTL_FLAGS2)) != 0) {

            return -TARGET_EINVAL;

        }

        if (block_signals()) {

            return -TARGET_ERESTARTSYS;

        }

        fork_start();

        ret = fork();

        if (ret == 0) {

            /* Child Process.  */

            rcu_after_fork();

            cpu_clone_regs(env, newsp);

            fork_end(1);

            /* There is a race condition here.  The parent process could

               theoretically read the TID in the child process before the child

               tid is set.  This would require using either ptrace

               (not implemented) or having *_tidptr to point at a shared memory

               mapping.  We can't repeat the spinlock hack used above because

               the child process gets its own copy of the lock.  */

            if (flags & CLONE_CHILD_SETTID)

                put_user_u32(gettid(), child_tidptr);

            if (flags & CLONE_PARENT_SETTID)

                put_user_u32(gettid(), parent_tidptr);

            ts = (TaskState *)cpu->opaque;

            if (flags & CLONE_SETTLS)

                cpu_set_tls (env, newtls);

            if (flags & CLONE_CHILD_CLEARTID)

                ts->child_tidptr = child_tidptr;

        } else {

            fork_end(0);

        }

    }

    return ret;

}


static void test_hash_digest(void)

{

    size_t i;

    g_assert(qcrypto_init(NULL) == 0);

    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {

        int ret;

        char *digest;

        size_t digestsize;

        digestsize = qcrypto_hash_digest_len(i);

        g_assert_cmpint(digestsize * 2, ==, strlen(expected_outputs[i]));

        ret = qcrypto_hash_digest(i,

                                  INPUT_TEXT,

                                  strlen(INPUT_TEXT),

                                  &digest,

                                  NULL);

        g_assert(ret == 0);

        g_assert(g_str_equal(digest, expected_outputs[i]));

        g_free(digest);

    }

}


static uint32_t pci_apb_ioreadw (void *opaque, target_phys_addr_t addr)

{

    uint32_t val;

    val = bswap16(cpu_inw(addr & IOPORTS_MASK));

    return val;

}


static void destroy_l2_mapping(PhysPageEntry *lp, unsigned level)

{

    unsigned i;

    PhysPageEntry *p = lp->u.node;

    if (!p) {

        return;

    }

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

        if (level > 0) {

            destroy_l2_mapping(&p[i], level - 1);

        } else {

            destroy_page_desc(p[i].u.leaf);

        }

    }

    g_free(p);

    lp->u.node = NULL;

}


static void prstat_to_stat(struct stat *stbuf, ProxyStat *prstat)

{

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

   stbuf->st_dev = prstat->st_dev;

   stbuf->st_ino = prstat->st_ino;

   stbuf->st_nlink = prstat->st_nlink;

   stbuf->st_mode = prstat->st_mode;

   stbuf->st_uid = prstat->st_uid;

   stbuf->st_gid = prstat->st_gid;

   stbuf->st_rdev = prstat->st_rdev;

   stbuf->st_size = prstat->st_size;

   stbuf->st_blksize = prstat->st_blksize;

   stbuf->st_blocks = prstat->st_blocks;

   stbuf->st_atim.tv_sec = prstat->st_atim_sec;

   stbuf->st_atim.tv_nsec = prstat->st_atim_nsec;

   stbuf->st_mtime = prstat->st_mtim_sec;

   stbuf->st_mtim.tv_nsec = prstat->st_mtim_nsec;

   stbuf->st_ctime = prstat->st_ctim_sec;

   stbuf->st_ctim.tv_nsec = prstat->st_ctim_nsec;

}


S390CPU *cpu_s390x_init(const char *cpu_model)

{

    S390CPU *cpu;

    cpu = S390_CPU(object_new(TYPE_S390_CPU));

    object_property_set_bool(OBJECT(cpu), true, "realized", NULL);

    return cpu;

}


void pci_unregister_vga(PCIDevice *pci_dev)

{

    if (!pci_dev->has_vga) {

        return;

    }

    memory_region_del_subregion(pci_dev->bus->address_space_mem,

                                pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);

    memory_region_del_subregion(pci_dev->bus->address_space_io,

                                pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);

    memory_region_del_subregion(pci_dev->bus->address_space_io,

                                pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);

    pci_dev->has_vga = false;

}


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

                        int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    C93DecoderContext * const c93 = avctx->priv_data;

    AVFrame * const newpic = &c93->pictures[c93->currentpic];

    AVFrame * const oldpic = &c93->pictures[c93->currentpic^1];

    GetByteContext gb;

    uint8_t *out;

    int stride, ret, i, x, y, b, bt = 0;

    c93->currentpic ^= 1;

    if ((ret = ff_reget_buffer(avctx, newpic)) < 0)

        return ret;

    stride = newpic->linesize[0];

    bytestream2_init(&gb, buf, buf_size);

    b = bytestream2_get_byte(&gb);

    if (b & C93_FIRST_FRAME) {

        newpic->pict_type = AV_PICTURE_TYPE_I;

        newpic->key_frame = 1;

    } else {

        newpic->pict_type = AV_PICTURE_TYPE_P;

        newpic->key_frame = 0;

    }

    for (y = 0; y < HEIGHT; y += 8) {

        out = newpic->data[0] + y * stride;

        for (x = 0; x < WIDTH; x += 8) {

            uint8_t *copy_from = oldpic->data[0];

            unsigned int offset, j;

            uint8_t cols[4], grps[4];

            C93BlockType block_type;

            if (!bt)

                bt = bytestream2_get_byte(&gb);

            block_type= bt & 0x0F;

            switch (block_type) {

            case C93_8X8_FROM_PREV:

                offset = bytestream2_get_le16(&gb);

                if ((ret = copy_block(avctx, out, copy_from, offset, 8, stride)) < 0)

                    return ret;

                break;

            case C93_4X4_FROM_CURR:

                copy_from = newpic->data[0];

            case C93_4X4_FROM_PREV:

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

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

                        offset = bytestream2_get_le16(&gb);

                        if ((ret = copy_block(avctx, &out[j*stride+i],

                                              copy_from, offset, 4, stride)) < 0)

                            return ret;

                    }

                }

                break;

            case C93_8X8_2COLOR:

                bytestream2_get_buffer(&gb, cols, 2);

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

                    draw_n_color(out + i*stride, stride, 8, 1, 1, cols,

                                     NULL, bytestream2_get_byte(&gb));

                }

                break;

            case C93_4X4_2COLOR:

            case C93_4X4_4COLOR:

            case C93_4X4_4COLOR_GRP:

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

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

                        if (block_type == C93_4X4_2COLOR) {

                            bytestream2_get_buffer(&gb, cols, 2);

                            draw_n_color(out + i + j*stride, stride, 4, 4,

                                    1, cols, NULL, bytestream2_get_le16(&gb));

                        } else if (block_type == C93_4X4_4COLOR) {

                            bytestream2_get_buffer(&gb, cols, 4);

                            draw_n_color(out + i + j*stride, stride, 4, 4,

                                    2, cols, NULL, bytestream2_get_le32(&gb));

                        } else {

                            bytestream2_get_buffer(&gb, grps, 4);

                            draw_n_color(out + i + j*stride, stride, 4, 4,

                                    1, cols, grps, bytestream2_get_le16(&gb));

                        }

                    }

                }

                break;

            case C93_NOOP:

                break;

            case C93_8X8_INTRA:

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

                    bytestream2_get_buffer(&gb, out + j*stride, 8);

                break;

            default:

                av_log(avctx, AV_LOG_ERROR, "unexpected type %x at %dx%d\n",

                       block_type, x, y);

                return AVERROR_INVALIDDATA;

            }

            bt >>= 4;

            out += 8;

        }

    }

    if (b & C93_HAS_PALETTE) {

        uint32_t *palette = (uint32_t *) newpic->data[1];

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

            palette[i] = 0xFFU << 24 | bytestream2_get_be24(&gb);

        }

        newpic->palette_has_changed = 1;

    } else {

        if (oldpic->data[1])

            memcpy(newpic->data[1], oldpic->data[1], 256 * 4);

    }

    if ((ret = av_frame_ref(data, newpic)) < 0)

        return ret;

    *got_frame = 1;

    return buf_size;

}


VncInfo2List *qmp_query_vnc_servers(Error **errp)

{

    VncInfo2List *item, *prev = NULL;

    VncInfo2 *info;

    VncDisplay *vd;

    DeviceState *dev;

    QTAILQ_FOREACH(vd, &vnc_displays, next) {

        info = g_new0(VncInfo2, 1);

        info->id = g_strdup(vd->id);

        info->clients = qmp_query_client_list(vd);

        qmp_query_auth(vd, info);

        if (vd->dcl.con) {

            dev = DEVICE(object_property_get_link(OBJECT(vd->dcl.con),

                                                  "device", NULL));

            info->has_display = true;

            info->display = g_strdup(dev->id);

        }

        if (vd->lsock != NULL) {

            info->server = qmp_query_server_entry(

                vd->lsock, false, info->server);

        }

        if (vd->lwebsock != NULL) {

            info->server = qmp_query_server_entry(

                vd->lwebsock, true, info->server);

        }

        item = g_new0(VncInfo2List, 1);

        item->value = info;

        item->next = prev;

        prev = item;

    }

    return prev;

}


pic_read(void *opaque, target_phys_addr_t addr, unsigned int size)

{

    struct etrax_pic *fs = opaque;

    uint32_t rval;

    rval = fs->regs[addr >> 2];

    D(printf("%s %x=%x\n", __func__, addr, rval));

    return rval;

}


static int coroutine_fn nfs_co_writev(BlockDriverState *bs,

                                        int64_t sector_num, int nb_sectors,

                                        QEMUIOVector *iov)

{

    NFSClient *client = bs->opaque;

    NFSRPC task;

    char *buf = NULL;

    nfs_co_init_task(client, &task);

    buf = g_try_malloc(nb_sectors * BDRV_SECTOR_SIZE);

    if (nb_sectors && buf == NULL) {

        return -ENOMEM;

    }

    qemu_iovec_to_buf(iov, 0, buf, nb_sectors * BDRV_SECTOR_SIZE);

    if (nfs_pwrite_async(client->context, client->fh,

                         sector_num * BDRV_SECTOR_SIZE,

                         nb_sectors * BDRV_SECTOR_SIZE,

                         buf, nfs_co_generic_cb, &task) != 0) {

        g_free(buf);

        return -ENOMEM;

    }

    while (!task.complete) {

        nfs_set_events(client);

        qemu_coroutine_yield();

    }

    g_free(buf);

    if (task.ret != nb_sectors * BDRV_SECTOR_SIZE) {

        return task.ret < 0 ? task.ret : -EIO;

    }

    return 0;

}


static gboolean cadence_uart_xmit(GIOChannel *chan, GIOCondition cond,

                                  void *opaque)

{

    CadenceUARTState *s = opaque;

    int ret;

    /* instant drain the fifo when there's no back-end */

    if (!s->chr) {

        s->tx_count = 0;

        return FALSE;

    }

    if (!s->tx_count) {

        return FALSE;

    }

    ret = qemu_chr_fe_write(s->chr, s->tx_fifo, s->tx_count);

    s->tx_count -= ret;

    memmove(s->tx_fifo, s->tx_fifo + ret, s->tx_count);

    if (s->tx_count) {

        int r = qemu_chr_fe_add_watch(s->chr, G_IO_OUT|G_IO_HUP,

                                      cadence_uart_xmit, s);

        assert(r);

    }

    uart_update_status(s);

    return FALSE;

}


void error_set_field(Error *err, const char *field, const char *value)

{

    QDict *dict = qdict_get_qdict(err->obj, "data");

    return qdict_put(dict, field, qstring_from_str(value));

}


static void replay_add_event(ReplayAsyncEventKind event_kind,

                             void *opaque,

                             void *opaque2, uint64_t id)

{

    assert(event_kind < REPLAY_ASYNC_COUNT);

    if (!replay_file || replay_mode == REPLAY_MODE_NONE

        || !events_enabled) {

        Event e;

        e.event_kind = event_kind;

        e.opaque = opaque;

        e.opaque2 = opaque2;

        e.id = id;

        replay_run_event(&e);

        return;

    }

    Event *event = g_malloc0(sizeof(Event));

    event->event_kind = event_kind;

    event->opaque = opaque;

    event->opaque2 = opaque2;

    event->id = id;

    replay_mutex_lock();

    QTAILQ_INSERT_TAIL(&events_list, event, events);

    replay_mutex_unlock();

}


static void unsafe_flush_warning(BDRVSSHState *s, const char *what)

{

    if (!s->unsafe_flush_warning) {

        error_report("warning: ssh server %s does not support fsync",

                     s->inet->host);

        if (what) {

            error_report("to support fsync, you need %s", what);

        }

        s->unsafe_flush_warning = true;

    }

}


static int hls_slice_header(HEVCContext *s)

{

    GetBitContext *gb = &s->HEVClc->gb;

    SliceHeader *sh   = &s->sh;

    int i, j, ret;

    // Coded parameters

    sh->first_slice_in_pic_flag = get_bits1(gb);

    if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) {

        s->seq_decode = (s->seq_decode + 1) & 0xff;

        s->max_ra     = INT_MAX;

        if (IS_IDR(s))

            ff_hevc_clear_refs(s);

    }

    sh->no_output_of_prior_pics_flag = 0;

    if (IS_IRAP(s))

        sh->no_output_of_prior_pics_flag = get_bits1(gb);

    sh->pps_id = get_ue_golomb_long(gb);

    if (sh->pps_id >= MAX_PPS_COUNT || !s->pps_list[sh->pps_id]) {

        av_log(s->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (!sh->first_slice_in_pic_flag &&

        s->pps != (HEVCPPS*)s->pps_list[sh->pps_id]->data) {

        av_log(s->avctx, AV_LOG_ERROR, "PPS changed between slices.\n");

        return AVERROR_INVALIDDATA;

    }

    s->pps = (HEVCPPS*)s->pps_list[sh->pps_id]->data;

    if (s->nal_unit_type == NAL_CRA_NUT && s->last_eos == 1)

        sh->no_output_of_prior_pics_flag = 1;

    if (s->sps != (HEVCSPS*)s->sps_list[s->pps->sps_id]->data) {

        const HEVCSPS* last_sps = s->sps;

        s->sps = (HEVCSPS*)s->sps_list[s->pps->sps_id]->data;

        if (last_sps && IS_IRAP(s) && s->nal_unit_type != NAL_CRA_NUT) {

            if (s->sps->width !=  last_sps->width || s->sps->height != last_sps->height ||

                s->sps->temporal_layer[s->sps->max_sub_layers - 1].max_dec_pic_buffering !=

                last_sps->temporal_layer[last_sps->max_sub_layers - 1].max_dec_pic_buffering)

                sh->no_output_of_prior_pics_flag = 0;

        }

        ff_hevc_clear_refs(s);

        ret = set_sps(s, s->sps, AV_PIX_FMT_NONE);

        if (ret < 0)

            return ret;

        s->seq_decode = (s->seq_decode + 1) & 0xff;

        s->max_ra     = INT_MAX;

    }

    sh->dependent_slice_segment_flag = 0;

    if (!sh->first_slice_in_pic_flag) {

        int slice_address_length;

        if (s->pps->dependent_slice_segments_enabled_flag)

            sh->dependent_slice_segment_flag = get_bits1(gb);

        slice_address_length = av_ceil_log2(s->sps->ctb_width *

                                            s->sps->ctb_height);

        sh->slice_segment_addr = get_bits(gb, slice_address_length);

        if (sh->slice_segment_addr >= s->sps->ctb_width * s->sps->ctb_height) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Invalid slice segment address: %u.\n",

                   sh->slice_segment_addr);

            return AVERROR_INVALIDDATA;

        }

        if (!sh->dependent_slice_segment_flag) {

            sh->slice_addr = sh->slice_segment_addr;

            s->slice_idx++;

        }

    } else {

        sh->slice_segment_addr = sh->slice_addr = 0;

        s->slice_idx           = 0;

        s->slice_initialized   = 0;

    }

    if (!sh->dependent_slice_segment_flag) {

        s->slice_initialized = 0;

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

            skip_bits(gb, 1);  // slice_reserved_undetermined_flag[]

        sh->slice_type = get_ue_golomb_long(gb);

        if (!(sh->slice_type == I_SLICE ||

              sh->slice_type == P_SLICE ||

              sh->slice_type == B_SLICE)) {

            av_log(s->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",

                   sh->slice_type);

            return AVERROR_INVALIDDATA;

        }

        if (IS_IRAP(s) && sh->slice_type != I_SLICE) {

            av_log(s->avctx, AV_LOG_ERROR, "Inter slices in an IRAP frame.\n");

            return AVERROR_INVALIDDATA;

        }

        // when flag is not present, picture is inferred to be output

        sh->pic_output_flag = 1;

        if (s->pps->output_flag_present_flag)

            sh->pic_output_flag = get_bits1(gb);

        if (s->sps->separate_colour_plane_flag)

            sh->colour_plane_id = get_bits(gb, 2);

        if (!IS_IDR(s)) {

            int poc;

            sh->pic_order_cnt_lsb = get_bits(gb, s->sps->log2_max_poc_lsb);

            poc = ff_hevc_compute_poc(s, sh->pic_order_cnt_lsb);

            if (!sh->first_slice_in_pic_flag && poc != s->poc) {

                av_log(s->avctx, AV_LOG_WARNING,

                       "Ignoring POC change between slices: %d -> %d\n", s->poc, poc);

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

                    return AVERROR_INVALIDDATA;

                poc = s->poc;

            }

            s->poc = poc;

            sh->short_term_ref_pic_set_sps_flag = get_bits1(gb);

            if (!sh->short_term_ref_pic_set_sps_flag) {

                int pos = get_bits_left(gb);

                ret = ff_hevc_decode_short_term_rps(s, &sh->slice_rps, s->sps, 1);

                if (ret < 0)

                    return ret;

                sh->short_term_ref_pic_set_size = pos - get_bits_left(gb);

                sh->short_term_rps = &sh->slice_rps;

            } else {

                int numbits, rps_idx;

                if (!s->sps->nb_st_rps) {

                    av_log(s->avctx, AV_LOG_ERROR, "No ref lists in the SPS.\n");

                    return AVERROR_INVALIDDATA;

                }

                numbits = av_ceil_log2(s->sps->nb_st_rps);

                rps_idx = numbits > 0 ? get_bits(gb, numbits) : 0;

                sh->short_term_rps = &s->sps->st_rps[rps_idx];

            }

            ret = decode_lt_rps(s, &sh->long_term_rps, gb);

            if (ret < 0) {

                av_log(s->avctx, AV_LOG_WARNING, "Invalid long term RPS.\n");

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

                    return AVERROR_INVALIDDATA;

            }

            if (s->sps->sps_temporal_mvp_enabled_flag)

                sh->slice_temporal_mvp_enabled_flag = get_bits1(gb);

            else

                sh->slice_temporal_mvp_enabled_flag = 0;

        } else {

            s->sh.short_term_rps = NULL;

            s->poc               = 0;

        }

        /* 8.3.1 */

        if (s->temporal_id == 0 &&

            s->nal_unit_type != NAL_TRAIL_N &&

            s->nal_unit_type != NAL_TSA_N   &&

            s->nal_unit_type != NAL_STSA_N  &&

            s->nal_unit_type != NAL_RADL_N  &&

            s->nal_unit_type != NAL_RADL_R  &&

            s->nal_unit_type != NAL_RASL_N  &&

            s->nal_unit_type != NAL_RASL_R)

            s->pocTid0 = s->poc;

        if (s->sps->sao_enabled) {

            sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb);

            if (s->sps->chroma_format_idc) {

                sh->slice_sample_adaptive_offset_flag[1] =

                sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb);

            }

        } else {

            sh->slice_sample_adaptive_offset_flag[0] = 0;

            sh->slice_sample_adaptive_offset_flag[1] = 0;

            sh->slice_sample_adaptive_offset_flag[2] = 0;

        }

        sh->nb_refs[L0] = sh->nb_refs[L1] = 0;

        if (sh->slice_type == P_SLICE || sh->slice_type == B_SLICE) {

            int nb_refs;

            sh->nb_refs[L0] = s->pps->num_ref_idx_l0_default_active;

            if (sh->slice_type == B_SLICE)

                sh->nb_refs[L1] = s->pps->num_ref_idx_l1_default_active;

            if (get_bits1(gb)) { // num_ref_idx_active_override_flag

                sh->nb_refs[L0] = get_ue_golomb_long(gb) + 1;

                if (sh->slice_type == B_SLICE)

                    sh->nb_refs[L1] = get_ue_golomb_long(gb) + 1;

            }

            if (sh->nb_refs[L0] > MAX_REFS || sh->nb_refs[L1] > MAX_REFS) {

                av_log(s->avctx, AV_LOG_ERROR, "Too many refs: %d/%d.\n",

                       sh->nb_refs[L0], sh->nb_refs[L1]);

                return AVERROR_INVALIDDATA;

            }

            sh->rpl_modification_flag[0] = 0;

            sh->rpl_modification_flag[1] = 0;

            nb_refs = ff_hevc_frame_nb_refs(s);

            if (!nb_refs) {

                av_log(s->avctx, AV_LOG_ERROR, "Zero refs for a frame with P or B slices.\n");

                return AVERROR_INVALIDDATA;

            }

            if (s->pps->lists_modification_present_flag && nb_refs > 1) {

                sh->rpl_modification_flag[0] = get_bits1(gb);

                if (sh->rpl_modification_flag[0]) {

                    for (i = 0; i < sh->nb_refs[L0]; i++)

                        sh->list_entry_lx[0][i] = get_bits(gb, av_ceil_log2(nb_refs));

                }

                if (sh->slice_type == B_SLICE) {

                    sh->rpl_modification_flag[1] = get_bits1(gb);

                    if (sh->rpl_modification_flag[1] == 1)

                        for (i = 0; i < sh->nb_refs[L1]; i++)

                            sh->list_entry_lx[1][i] = get_bits(gb, av_ceil_log2(nb_refs));

                }

            }

            if (sh->slice_type == B_SLICE)

                sh->mvd_l1_zero_flag = get_bits1(gb);

            if (s->pps->cabac_init_present_flag)

                sh->cabac_init_flag = get_bits1(gb);

            else

                sh->cabac_init_flag = 0;

            sh->collocated_ref_idx = 0;

            if (sh->slice_temporal_mvp_enabled_flag) {

                sh->collocated_list = L0;

                if (sh->slice_type == B_SLICE)

                    sh->collocated_list = !get_bits1(gb);

                if (sh->nb_refs[sh->collocated_list] > 1) {

                    sh->collocated_ref_idx = get_ue_golomb_long(gb);

                    if (sh->collocated_ref_idx >= sh->nb_refs[sh->collocated_list]) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "Invalid collocated_ref_idx: %d.\n",

                               sh->collocated_ref_idx);

                        return AVERROR_INVALIDDATA;

                    }

                }

            }

            if ((s->pps->weighted_pred_flag   && sh->slice_type == P_SLICE) ||

                (s->pps->weighted_bipred_flag && sh->slice_type == B_SLICE)) {

                pred_weight_table(s, gb);

            }

            sh->max_num_merge_cand = 5 - get_ue_golomb_long(gb);

            if (sh->max_num_merge_cand < 1 || sh->max_num_merge_cand > 5) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "Invalid number of merging MVP candidates: %d.\n",

                       sh->max_num_merge_cand);

                return AVERROR_INVALIDDATA;

            }

        }

        sh->slice_qp_delta = get_se_golomb(gb);

        if (s->pps->pic_slice_level_chroma_qp_offsets_present_flag) {

            sh->slice_cb_qp_offset = get_se_golomb(gb);

            sh->slice_cr_qp_offset = get_se_golomb(gb);

        } else {

            sh->slice_cb_qp_offset = 0;

            sh->slice_cr_qp_offset = 0;

        }

        if (s->pps->chroma_qp_offset_list_enabled_flag)

            sh->cu_chroma_qp_offset_enabled_flag = get_bits1(gb);

        else

            sh->cu_chroma_qp_offset_enabled_flag = 0;

        if (s->pps->deblocking_filter_control_present_flag) {

            int deblocking_filter_override_flag = 0;

            if (s->pps->deblocking_filter_override_enabled_flag)

                deblocking_filter_override_flag = get_bits1(gb);

            if (deblocking_filter_override_flag) {

                sh->disable_deblocking_filter_flag = get_bits1(gb);

                if (!sh->disable_deblocking_filter_flag) {

                    sh->beta_offset = get_se_golomb(gb) * 2;

                    sh->tc_offset   = get_se_golomb(gb) * 2;

                }

            } else {

                sh->disable_deblocking_filter_flag = s->pps->disable_dbf;

                sh->beta_offset                    = s->pps->beta_offset;

                sh->tc_offset                      = s->pps->tc_offset;

            }

        } else {

            sh->disable_deblocking_filter_flag = 0;

            sh->beta_offset                    = 0;

            sh->tc_offset                      = 0;

        }

        if (s->pps->seq_loop_filter_across_slices_enabled_flag &&

            (sh->slice_sample_adaptive_offset_flag[0] ||

             sh->slice_sample_adaptive_offset_flag[1] ||

             !sh->disable_deblocking_filter_flag)) {

            sh->slice_loop_filter_across_slices_enabled_flag = get_bits1(gb);

        } else {

            sh->slice_loop_filter_across_slices_enabled_flag = s->pps->seq_loop_filter_across_slices_enabled_flag;

        }

    } else if (!s->slice_initialized) {

        av_log(s->avctx, AV_LOG_ERROR, "Independent slice segment missing.\n");

        return AVERROR_INVALIDDATA;

    }

    sh->num_entry_point_offsets = 0;

    if (s->pps->tiles_enabled_flag || s->pps->entropy_coding_sync_enabled_flag) {

        unsigned num_entry_point_offsets = get_ue_golomb_long(gb);

        // It would be possible to bound this tighter but this here is simpler

        if (sh->num_entry_point_offsets > get_bits_left(gb)) {

            av_log(s->avctx, AV_LOG_ERROR, "num_entry_point_offsets %d is invalid\n", num_entry_point_offsets);

            return AVERROR_INVALIDDATA;

        }

        sh->num_entry_point_offsets = num_entry_point_offsets;

        if (sh->num_entry_point_offsets > 0) {

            int offset_len = get_ue_golomb_long(gb) + 1;

            if (offset_len < 1 || offset_len > 32) {

                sh->num_entry_point_offsets = 0;

                av_log(s->avctx, AV_LOG_ERROR, "offset_len %d is invalid\n", offset_len);

                return AVERROR_INVALIDDATA;

            }

            av_freep(&sh->entry_point_offset);

            av_freep(&sh->offset);

            av_freep(&sh->size);

            sh->entry_point_offset = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));

            sh->offset = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));

            sh->size = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));

            if (!sh->entry_point_offset || !sh->offset || !sh->size) {

                sh->num_entry_point_offsets = 0;

                av_log(s->avctx, AV_LOG_ERROR, "Failed to allocate memory\n");

                return AVERROR(ENOMEM);

            }

            for (i = 0; i < sh->num_entry_point_offsets; i++) {

                unsigned val = get_bits_long(gb, offset_len);

                sh->entry_point_offset[i] = val + 1; // +1; // +1 to get the size

            }

            if (s->threads_number > 1 && (s->pps->num_tile_rows > 1 || s->pps->num_tile_columns > 1)) {

                s->enable_parallel_tiles = 0; // TODO: you can enable tiles in parallel here

                s->threads_number = 1;

            } else

                s->enable_parallel_tiles = 0;

        } else

            s->enable_parallel_tiles = 0;

    }

    if (s->pps->slice_header_extension_present_flag) {

        unsigned int length = get_ue_golomb_long(gb);

        if (length*8LL > get_bits_left(gb)) {

            av_log(s->avctx, AV_LOG_ERROR, "too many slice_header_extension_data_bytes\n");

            return AVERROR_INVALIDDATA;

        }

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

            skip_bits(gb, 8);  // slice_header_extension_data_byte

    }

    // Inferred parameters

    sh->slice_qp = 26U + s->pps->pic_init_qp_minus26 + sh->slice_qp_delta;

    if (sh->slice_qp > 51 ||

        sh->slice_qp < -s->sps->qp_bd_offset) {

        av_log(s->avctx, AV_LOG_ERROR,

               "The slice_qp %d is outside the valid range "

               "[%d, 51].\n",

               sh->slice_qp,

               -s->sps->qp_bd_offset);

        return AVERROR_INVALIDDATA;

    }

    sh->slice_ctb_addr_rs = sh->slice_segment_addr;

    if (!s->sh.slice_ctb_addr_rs && s->sh.dependent_slice_segment_flag) {

        av_log(s->avctx, AV_LOG_ERROR, "Impossible slice segment.\n");

        return AVERROR_INVALIDDATA;

    }

    if (get_bits_left(gb) < 0) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Overread slice header by %d bits\n", -get_bits_left(gb));

        return AVERROR_INVALIDDATA;

    }

    s->HEVClc->first_qp_group = !s->sh.dependent_slice_segment_flag;

    if (!s->pps->cu_qp_delta_enabled_flag)

        s->HEVClc->qp_y = s->sh.slice_qp;

    s->slice_initialized = 1;

    s->HEVClc->tu.cu_qp_offset_cb = 0;

    s->HEVClc->tu.cu_qp_offset_cr = 0;

    return 0;

}


static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey,

                      int w, int h, int stride, int color)

{

    int x, y, fr, f;

    sx = av_clip(sx, 0, w - 1);

    sy = av_clip(sy, 0, h - 1);

    ex = av_clip(ex, 0, w - 1);

    ey = av_clip(ey, 0, h - 1);

    buf[sy * stride + sx] += color;

    if (FFABS(ex - sx) > FFABS(ey - sy)) {

        if (sx > ex) {

            FFSWAP(int, sx, ex);

            FFSWAP(int, sy, ey);

        }

        buf += sx + sy * stride;

        ex  -= sx;

        f    = ((ey - sy) << 16) / ex;

        for (x = 0; x = ex; x++) {

            y  = (x * f) >> 16;

            fr = (x * f) & 0xFFFF;

            buf[y * stride + x]       += (color * (0x10000 - fr)) >> 16;

            buf[(y + 1) * stride + x] += (color *            fr ) >> 16;

        }

    } else {

        if (sy > ey) {

            FFSWAP(int, sx, ex);

            FFSWAP(int, sy, ey);

        }

        buf += sx + sy * stride;

        ey  -= sy;

        if (ey)

            f  = ((ex - sx) << 16) / ey;

        else

            f = 0;

        for (y = 0; y = ey; y++) {

            x  = (y * f) >> 16;

            fr = (y * f) & 0xFFFF;

            buf[y * stride + x]     += (color * (0x10000 - fr)) >> 16;

            buf[y * stride + x + 1] += (color *            fr ) >> 16;

        }

    }

}


static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,

                        QEMUIOVector *qiov, bool is_write,

                        BdrvRequestFlags flags)

{

    Coroutine *co;

    RwCo rwco = {

        .bs = bs,

        .offset = offset,

        .qiov = qiov,

        .is_write = is_write,

        .ret = NOT_DONE,

        .flags = flags,

    };

    /**

     * In sync call context, when the vcpu is blocked, this throttling timer

     * will not fire; so the I/O throttling function has to be disabled here

     * if it has been enabled.

     */

    if (bs->io_limits_enabled) {

        fprintf(stderr, "Disabling I/O throttling on '%s' due "

                        "to synchronous I/O.\n", bdrv_get_device_name(bs));

        bdrv_io_limits_disable(bs);

    }

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_rw_co_entry(&rwco);

    } else {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        co = qemu_coroutine_create(bdrv_rw_co_entry);

        qemu_coroutine_enter(co, &rwco);

        while (rwco.ret == NOT_DONE) {

            aio_poll(aio_context, true);

        }

    }

    return rwco.ret;

}


static uint64_t omap_mcbsp_read(void *opaque, hwaddr addr,

                                unsigned size)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    uint16_t ret;

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (offset) {

    case 0x00:	/* DRR2 */

        if (((s->rcr[0] >> 5) & 7) < 3)			/* RWDLEN1 */

            return 0x0000;

        /* Fall through.  */

    case 0x02:	/* DRR1 */

        if (s->rx_req < 2) {

            printf("%s: Rx FIFO underrun\n", __FUNCTION__);

            omap_mcbsp_rx_done(s);

        } else {

            s->tx_req -= 2;

            if (s->codec && s->codec->in.len >= 2) {

                ret = s->codec->in.fifo[s->codec->in.start ++] << 8;

                ret |= s->codec->in.fifo[s->codec->in.start ++];

                s->codec->in.len -= 2;

            } else

                ret = 0x0000;

            if (!s->tx_req)

                omap_mcbsp_rx_done(s);

            return ret;

        }

        return 0x0000;

    case 0x04:	/* DXR2 */

    case 0x06:	/* DXR1 */

        return 0x0000;

    case 0x08:	/* SPCR2 */

        return s->spcr[1];

    case 0x0a:	/* SPCR1 */

        return s->spcr[0];

    case 0x0c:	/* RCR2 */

        return s->rcr[1];

    case 0x0e:	/* RCR1 */

        return s->rcr[0];

    case 0x10:	/* XCR2 */

        return s->xcr[1];

    case 0x12:	/* XCR1 */

        return s->xcr[0];

    case 0x14:	/* SRGR2 */

        return s->srgr[1];

    case 0x16:	/* SRGR1 */

        return s->srgr[0];

    case 0x18:	/* MCR2 */

        return s->mcr[1];

    case 0x1a:	/* MCR1 */

        return s->mcr[0];

    case 0x1c:	/* RCERA */

        return s->rcer[0];

    case 0x1e:	/* RCERB */

        return s->rcer[1];

    case 0x20:	/* XCERA */

        return s->xcer[0];

    case 0x22:	/* XCERB */

        return s->xcer[1];

    case 0x24:	/* PCR0 */

        return s->pcr;

    case 0x26:	/* RCERC */

        return s->rcer[2];

    case 0x28:	/* RCERD */

        return s->rcer[3];

    case 0x2a:	/* XCERC */

        return s->xcer[2];

    case 0x2c:	/* XCERD */

        return s->xcer[3];

    case 0x2e:	/* RCERE */

        return s->rcer[4];

    case 0x30:	/* RCERF */

        return s->rcer[5];

    case 0x32:	/* XCERE */

        return s->xcer[4];

    case 0x34:	/* XCERF */

        return s->xcer[5];

    case 0x36:	/* RCERG */

        return s->rcer[6];

    case 0x38:	/* RCERH */

        return s->rcer[7];

    case 0x3a:	/* XCERG */

        return s->xcer[6];

    case 0x3c:	/* XCERH */

        return s->xcer[7];

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static void check_suspend_mode(GuestSuspendMode mode, Error **errp)

{

    SYSTEM_POWER_CAPABILITIES sys_pwr_caps;

    Error *local_err = NULL;

    ZeroMemory(&sys_pwr_caps, sizeof(sys_pwr_caps));

    if (!GetPwrCapabilities(&sys_pwr_caps)) {

        error_setg(&local_err, QERR_QGA_COMMAND_FAILED,

                   "failed to determine guest suspend capabilities");

        goto out;

    }

    switch (mode) {

    case GUEST_SUSPEND_MODE_DISK:

        if (!sys_pwr_caps.SystemS4) {

            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,

                       "suspend-to-disk not supported by OS");

        }

        break;

    case GUEST_SUSPEND_MODE_RAM:

        if (!sys_pwr_caps.SystemS3) {

            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,

                       "suspend-to-ram not supported by OS");

        }

        break;

    default:

        error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "mode",

                   "GuestSuspendMode");

    }

out:

    if (local_err) {

        error_propagate(errp, local_err);

    }

}


av_cold static int lavfi_read_header(AVFormatContext *avctx)

{

    LavfiContext *lavfi = avctx->priv_data;

    AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;

    AVFilter *buffersink, *abuffersink;

    int *pix_fmts = create_all_formats(AV_PIX_FMT_NB);

    enum AVMediaType type;

    int ret = 0, i, n;

#define FAIL(ERR) { ret = ERR; goto end; }

    if (!pix_fmts)

        FAIL(AVERROR(ENOMEM));

    avfilter_register_all();

    buffersink = avfilter_get_by_name("buffersink");

    abuffersink = avfilter_get_by_name("abuffersink");

    if (lavfi->graph_filename && lavfi->graph_str) {

        av_log(avctx, AV_LOG_ERROR,

               "Only one of the graph or graph_file options must be specified\n");

        FAIL(AVERROR(EINVAL));

    }

    if (lavfi->graph_filename) {

        uint8_t *file_buf, *graph_buf;

        size_t file_bufsize;

        ret = av_file_map(lavfi->graph_filename,

                          &file_buf, &file_bufsize, 0, avctx);

        if (ret < 0)

            goto end;

        /* create a 0-terminated string based on the read file */

        graph_buf = av_malloc(file_bufsize + 1);

        if (!graph_buf) {

            av_file_unmap(file_buf, file_bufsize);

            FAIL(AVERROR(ENOMEM));

        }

        memcpy(graph_buf, file_buf, file_bufsize);

        graph_buf[file_bufsize] = 0;

        av_file_unmap(file_buf, file_bufsize);

        lavfi->graph_str = graph_buf;

    }

    if (!lavfi->graph_str)

        lavfi->graph_str = av_strdup(avctx->filename);

    /* parse the graph, create a stream for each open output */

    if (!(lavfi->graph = avfilter_graph_alloc()))

        FAIL(AVERROR(ENOMEM));

    if ((ret = avfilter_graph_parse(lavfi->graph, lavfi->graph_str,

                                    &input_links, &output_links, avctx)) < 0)

        FAIL(ret);

    if (input_links) {

        av_log(avctx, AV_LOG_ERROR,

               "Open inputs in the filtergraph are not acceptable\n");

        FAIL(AVERROR(EINVAL));

    }

    /* count the outputs */

    for (n = 0, inout = output_links; inout; n++, inout = inout->next);

    if (!(lavfi->sink_stream_map = av_malloc(sizeof(int) * n)))

        FAIL(AVERROR(ENOMEM));

    if (!(lavfi->sink_eof = av_mallocz(sizeof(int) * n)))

        FAIL(AVERROR(ENOMEM));

    if (!(lavfi->stream_sink_map = av_malloc(sizeof(int) * n)))

        FAIL(AVERROR(ENOMEM));

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

        lavfi->stream_sink_map[i] = -1;

    /* parse the output link names - they need to be of the form out0, out1, ...

     * create a mapping between them and the streams */

    for (i = 0, inout = output_links; inout; i++, inout = inout->next) {

        int stream_idx;

        if (!strcmp(inout->name, "out"))

            stream_idx = 0;

        else if (sscanf(inout->name, "out%d\n", &stream_idx) != 1) {

            av_log(avctx,  AV_LOG_ERROR,

                   "Invalid outpad name '%s'\n", inout->name);

            FAIL(AVERROR(EINVAL));

        }

        if ((unsigned)stream_idx >= n) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid index was specified in output '%s', "

                   "must be a non-negative value < %d\n",

                   inout->name, n);

            FAIL(AVERROR(EINVAL));

        }

        /* is an audio or video output? */

        type = inout->filter_ctx->output_pads[inout->pad_idx].type;

        if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {

            av_log(avctx,  AV_LOG_ERROR,

                   "Output '%s' is not a video or audio output, not yet supported\n", inout->name);

            FAIL(AVERROR(EINVAL));

        }

        if (lavfi->stream_sink_map[stream_idx] != -1) {

            av_log(avctx,  AV_LOG_ERROR,

                   "An output with stream index %d was already specified\n",

                   stream_idx);

            FAIL(AVERROR(EINVAL));

        }

        lavfi->sink_stream_map[i] = stream_idx;

        lavfi->stream_sink_map[stream_idx] = i;

    }

    /* for each open output create a corresponding stream */

    for (i = 0, inout = output_links; inout; i++, inout = inout->next) {

        AVStream *st;

        if (!(st = avformat_new_stream(avctx, NULL)))

            FAIL(AVERROR(ENOMEM));

        st->id = i;

    }

    /* create a sink for each output and connect them to the graph */

    lavfi->sinks = av_malloc(sizeof(AVFilterContext *) * avctx->nb_streams);

    if (!lavfi->sinks)

        FAIL(AVERROR(ENOMEM));

    for (i = 0, inout = output_links; inout; i++, inout = inout->next) {

        AVFilterContext *sink;

        type = inout->filter_ctx->output_pads[inout->pad_idx].type;

        if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||

            type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {

                av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");

                FAIL(AVERROR_FILTER_NOT_FOUND);

        }

        if (type == AVMEDIA_TYPE_VIDEO) {

            ret = avfilter_graph_create_filter(&sink, buffersink,

                                               inout->name, NULL,

                                               NULL, lavfi->graph);

            av_opt_set_int_list(sink, "pix_fmts", pix_fmts,  AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);

            if (ret < 0)

                goto end;

        } else if (type == AVMEDIA_TYPE_AUDIO) {

            enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_U8,

                                                  AV_SAMPLE_FMT_S16,

                                                  AV_SAMPLE_FMT_S32,

                                                  AV_SAMPLE_FMT_FLT,

                                                  AV_SAMPLE_FMT_DBL, -1 };

            ret = avfilter_graph_create_filter(&sink, abuffersink,

                                               inout->name, NULL,

                                               NULL, lavfi->graph);

            av_opt_set_int_list(sink, "sample_fmts", sample_fmts,  AV_SAMPLE_FMT_NONE, AV_OPT_SEARCH_CHILDREN);

            if (ret < 0)

                goto end;

        }

        lavfi->sinks[i] = sink;

        if ((ret = avfilter_link(inout->filter_ctx, inout->pad_idx, sink, 0)) < 0)

            FAIL(ret);

    }

    /* configure the graph */

    if ((ret = avfilter_graph_config(lavfi->graph, avctx)) < 0)

        FAIL(ret);

    if (lavfi->dump_graph) {

        char *dump = avfilter_graph_dump(lavfi->graph, lavfi->dump_graph);

        fputs(dump, stderr);

        fflush(stderr);

        av_free(dump);

    }

    /* fill each stream with the information in the corresponding sink */

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

        AVFilterLink *link = lavfi->sinks[lavfi->stream_sink_map[i]]->inputs[0];

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

        st->codec->codec_type = link->type;

        avpriv_set_pts_info(st, 64, link->time_base.num, link->time_base.den);

        if (link->type == AVMEDIA_TYPE_VIDEO) {

            st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;

            st->codec->pix_fmt    = link->format;

            st->codec->time_base  = link->time_base;

            st->codec->width      = link->w;

            st->codec->height     = link->h;

            st       ->sample_aspect_ratio =

            st->codec->sample_aspect_ratio = link->sample_aspect_ratio;

            avctx->probesize = FFMAX(avctx->probesize,

                                     link->w * link->h *

                                     av_get_padded_bits_per_pixel(av_pix_fmt_desc_get(link->format)) *

                                     30);

        } else if (link->type == AVMEDIA_TYPE_AUDIO) {

            st->codec->codec_id    = av_get_pcm_codec(link->format, -1);

            st->codec->channels    = av_get_channel_layout_nb_channels(link->channel_layout);

            st->codec->sample_fmt  = link->format;

            st->codec->sample_rate = link->sample_rate;

            st->codec->time_base   = link->time_base;

            st->codec->channel_layout = link->channel_layout;

            if (st->codec->codec_id == AV_CODEC_ID_NONE)

                av_log(avctx, AV_LOG_ERROR,

                       "Could not find PCM codec for sample format %s.\n",

                       av_get_sample_fmt_name(link->format));

        }

    }

    if (!(lavfi->decoded_frame = av_frame_alloc()))

        FAIL(AVERROR(ENOMEM));

end:

    av_free(pix_fmts);

    avfilter_inout_free(&input_links);

    avfilter_inout_free(&output_links);

    if (ret < 0)

        lavfi_read_close(avctx);

    return ret;

}


int do_balloon(Monitor *mon, const QDict *params,

	       MonitorCompletion cb, void *opaque)

{

    int ret;

    if (kvm_enabled() && !kvm_has_sync_mmu()) {

        qerror_report(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");

        return -1;

    }

    ret = qemu_balloon(qdict_get_int(params, "value"));

    if (ret == 0) {

        qerror_report(QERR_DEVICE_NOT_ACTIVE, "balloon");

        return -1;

    }

    cb(opaque, NULL);

    return 0;

}


static av_cold int movie_init(AVFilterContext *ctx, const char *args)

{

    MovieContext *movie = ctx->priv;

    AVInputFormat *iformat = NULL;

    int64_t timestamp;

    int nb_streams, ret, i;

    char default_streams[16], *stream_specs, *spec, *cursor;

    char name[16];

    AVStream *st;

    movie->class = &movie_class;

    av_opt_set_defaults(movie);

    if (args)

        movie->file_name = av_get_token(&args, ":");

    if (!movie->file_name || !*movie->file_name) {

        av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");

        return AVERROR(EINVAL);

    }

    if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0)

        return ret;

    movie->seek_point = movie->seek_point_d * 1000000 + 0.5;

    stream_specs = movie->stream_specs;

    if (!stream_specs) {

        snprintf(default_streams, sizeof(default_streams), "d%c%d",

                 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',

                 movie->stream_index);

        stream_specs = default_streams;

    }

    for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)

        if (*cursor == '+')

            nb_streams++;

    if (movie->loop_count != 1 && nb_streams != 1) {

        av_log(ctx, AV_LOG_ERROR,

               "Loop with several streams is currently unsupported\n");

        return AVERROR_PATCHWELCOME;

    }

    av_register_all();

    // Try to find the movie format (container)

    iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;

    movie->format_ctx = NULL;

    if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {

        av_log(ctx, AV_LOG_ERROR,

               "Failed to avformat_open_input '%s'\n", movie->file_name);

        return ret;

    }

    if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)

        av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");

    // if seeking requested, we execute it

    if (movie->seek_point > 0) {

        timestamp = movie->seek_point;

        // add the stream start time, should it exist

        if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {

            if (timestamp > INT64_MAX - movie->format_ctx->start_time) {

                av_log(ctx, AV_LOG_ERROR,

                       "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",

                       movie->file_name, movie->format_ctx->start_time, movie->seek_point);

                return AVERROR(EINVAL);

            }

            timestamp += movie->format_ctx->start_time;

        }

        if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {

            av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",

                   movie->file_name, timestamp);

            return ret;

        }

    }

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

        movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;

    movie->st = av_calloc(nb_streams, sizeof(*movie->st));

    if (!movie->st)

        return AVERROR(ENOMEM);

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

        spec = av_strtok(stream_specs, "+", &cursor);

        if (!spec)

            return AVERROR_BUG;

        stream_specs = NULL; /* for next strtok */

        st = find_stream(ctx, movie->format_ctx, spec);

        if (!st)

            return AVERROR(EINVAL);

        st->discard = AVDISCARD_DEFAULT;

        movie->st[i].st = st;

        movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);

    }

    if (av_strtok(NULL, "+", &cursor))

        return AVERROR_BUG;

    movie->out_index = av_calloc(movie->max_stream_index + 1,

                                 sizeof(*movie->out_index));

    if (!movie->out_index)

        return AVERROR(ENOMEM);

    for (i = 0; i <= movie->max_stream_index; i++)

        movie->out_index[i] = -1;

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

        movie->out_index[movie->st[i].st->index] = i;

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

        AVFilterPad pad = { 0 };

        snprintf(name, sizeof(name), "out%d", i);

        pad.type          = movie->st[i].st->codec->codec_type;

        pad.name          = av_strdup(name);

        pad.config_props  = movie_config_output_props;

        pad.request_frame = movie_request_frame;

        ff_insert_outpad(ctx, i, &pad);

        ret = open_stream(ctx, &movie->st[i]);

        if (ret < 0)

            return ret;

        if ( movie->st[i].st->codec->codec->type == AVMEDIA_TYPE_AUDIO &&

            !movie->st[i].st->codec->channel_layout) {

            ret = guess_channel_layout(&movie->st[i], i, ctx);

            if (ret < 0)

                return ret;

        }

    }

    if (!(movie->frame = avcodec_alloc_frame()) ) {

        av_log(log, AV_LOG_ERROR, "Failed to alloc frame\n");

        return AVERROR(ENOMEM);

    }

    av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",

           movie->seek_point, movie->format_name, movie->file_name,

           movie->stream_index);

    return 0;

}


void cpu_outl(pio_addr_t addr, uint32_t val)

{

    LOG_IOPORT("outl: %04"FMT_pioaddr" %08"PRIx32"\n", addr, val);

    trace_cpu_out(addr, val);

    ioport_write(2, addr, val);

}


static void do_loadvm(int argc, const char **argv)

{

    if (argc != 2) {

        help_cmd(argv[0]);

        return;

    }

    if (qemu_loadvm(argv[1]) < 0)

        term_printf("I/O error when loading VM from '%s'\n", argv[1]);

}


static void vmdk_refresh_limits(BlockDriverState *bs, Error **errp)

{

    BDRVVmdkState *s = bs->opaque;

    int i;

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

        if (!s->extents[i].flat) {

            bs->bl.write_zeroes_alignment =

                MAX(bs->bl.write_zeroes_alignment,

                    s->extents[i].cluster_sectors);

        }

    }

}


static int handle_cmd(AHCIState *s, int port, int slot)

{

    IDEState *ide_state;

    uint32_t opts;

    uint64_t tbl_addr;

    AHCICmdHdr *cmd;

    uint8_t *cmd_fis;

    dma_addr_t cmd_len;

    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {

        /* Engine currently busy, try again later */

        DPRINTF(port, "engine busy\n");

        return -1;

    }

    cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot];

    if (!s->dev[port].lst) {

        DPRINTF(port, "error: lst not given but cmd handled");

        return -1;

    }

    /* remember current slot handle for later */

    s->dev[port].cur_cmd = cmd;

    opts = le32_to_cpu(cmd->opts);

    tbl_addr = le64_to_cpu(cmd->tbl_addr);

    cmd_len = 0x80;

    cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,

                             DMA_DIRECTION_FROM_DEVICE);

    if (!cmd_fis) {

        DPRINTF(port, "error: guest passed us an invalid cmd fis\n");

        return -1;

    }

    /* The device we are working for */

    ide_state = &s->dev[port].port.ifs[0];

    if (!ide_state->bs) {

        DPRINTF(port, "error: guest accessed unused port");

        goto out;

    }

    debug_print_fis(cmd_fis, 0x90);

    //debug_print_fis(cmd_fis, (opts & AHCI_CMD_HDR_CMD_FIS_LEN) * 4);

    switch (cmd_fis[0]) {

        case SATA_FIS_TYPE_REGISTER_H2D:

            break;

        default:

            DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "

                          "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],

                          cmd_fis[2]);

            goto out;

            break;

    }

    switch (cmd_fis[1]) {

        case SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER:

            break;

        case 0:

            break;

        default:

            DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "

                          "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],

                          cmd_fis[2]);

            goto out;

            break;

    }

    switch (s->dev[port].port_state) {

        case STATE_RUN:

            if (cmd_fis[15] & ATA_SRST) {

                s->dev[port].port_state = STATE_RESET;

            }

            break;

        case STATE_RESET:

            if (!(cmd_fis[15] & ATA_SRST)) {

                ahci_reset_port(s, port);

            }

            break;

    }

    if (cmd_fis[1] == SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER) {

        /* Check for NCQ command */

        if ((cmd_fis[2] == READ_FPDMA_QUEUED) ||

            (cmd_fis[2] == WRITE_FPDMA_QUEUED)) {

            process_ncq_command(s, port, cmd_fis, slot);

            goto out;

        }

        /* Decompose the FIS  */

        ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);

        ide_state->feature = cmd_fis[3];

        if (!ide_state->nsector) {

            ide_state->nsector = 256;

        }

        if (ide_state->drive_kind != IDE_CD) {

            /*

             * We set the sector depending on the sector defined in the FIS.

             * Unfortunately, the spec isn't exactly obvious on this one.

             *

             * Apparently LBA48 commands set fis bytes 10,9,8,6,5,4 to the

             * 48 bit sector number. ATA_CMD_READ_DMA_EXT is an example for

             * such a command.

             *

             * Non-LBA48 commands however use 7[lower 4 bits],6,5,4 to define a

             * 28-bit sector number. ATA_CMD_READ_DMA is an example for such

             * a command.

             *

             * Since the spec doesn't explicitly state what each field should

             * do, I simply assume non-used fields as reserved and OR everything

             * together, independent of the command.

             */

            ide_set_sector(ide_state, ((uint64_t)cmd_fis[10] << 40)

                                    | ((uint64_t)cmd_fis[9] << 32)

                                    /* This is used for LBA48 commands */

                                    | ((uint64_t)cmd_fis[8] << 24)

                                    /* This is used for non-LBA48 commands */

                                    | ((uint64_t)(cmd_fis[7] & 0xf) << 24)

                                    | ((uint64_t)cmd_fis[6] << 16)

                                    | ((uint64_t)cmd_fis[5] << 8)

                                    | cmd_fis[4]);

        }

        /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command

         * table to ide_state->io_buffer

         */

        if (opts & AHCI_CMD_ATAPI) {

            memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);

            ide_state->lcyl = 0x14;

            ide_state->hcyl = 0xeb;

            debug_print_fis(ide_state->io_buffer, 0x10);

            ide_state->feature = IDE_FEATURE_DMA;

            s->dev[port].done_atapi_packet = false;

            /* XXX send PIO setup FIS */

        }

        ide_state->error = 0;

        /* Reset transferred byte counter */

        cmd->status = 0;

        /* We're ready to process the command in FIS byte 2. */

        ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);

    }

out:

    dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,

                     cmd_len);

    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {

        /* async command, complete later */

        s->dev[port].busy_slot = slot;

        return -1;

    }

    /* done handling the command */

    return 0;

}


static void virtio_rng_process(VirtIORNG *vrng)

{

    size_t size;

    if (!is_guest_ready(vrng)) {

        return;

    }

    size = get_request_size(vrng->vq);

    size = MIN(vrng->quota_remaining, size);

    if (size) {

        rng_backend_request_entropy(vrng->rng, size, chr_read, vrng);

    }

}


static int vhost_verify_ring_part_mapping(void *part,

                                          uint64_t part_addr,

                                          uint64_t part_size,

                                          uint64_t start_addr,

                                          uint64_t size)

{

    hwaddr l;

    void *p;

    int r = 0;

    if (!ranges_overlap(start_addr, size, part_addr, part_size)) {

        return 0;

    }

    l = part_size;

    p = cpu_physical_memory_map(part_addr, &l, 1);

    if (!p || l != part_size) {

        r = -ENOMEM;

    }

    if (p != part) {

        r = -EBUSY;

    }

    cpu_physical_memory_unmap(p, l, 0, 0);

    return r;

}


bool block_job_is_paused(BlockJob *job)

{

    return job->paused;

}


int qemu_register_machine(QEMUMachine *m)

{

    char *name = g_strconcat(m->name, TYPE_MACHINE_SUFFIX, NULL);

    TypeInfo ti = {

        .name       = name,

        .parent     = TYPE_MACHINE,

        .class_init = machine_class_init,

        .class_data = (void *)m,

    };

    type_register(&ti);

    g_free(name);

    return 0;

}


static int tosa_dac_event(I2CSlave *i2c, enum i2c_event event)

{

    TosaDACState *s = TOSA_DAC(i2c);

    s->len = 0;

    switch (event) {

    case I2C_START_SEND:

        break;

    case I2C_START_RECV:

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

        break;

    case I2C_FINISH:

#ifdef VERBOSE

        if (s->len < 2)

            printf("%s: message too short (%i bytes)\n", __FUNCTION__, s->len);

        if (s->len > 2)

            printf("%s: message too long\n", __FUNCTION__);

#endif

        break;

    default:

        break;

    }

    return 0;

}


av_cold void ff_vp8dsp_init_neon(VP8DSPContext *dsp)

{

    dsp->vp8_luma_dc_wht    = ff_vp8_luma_dc_wht_neon;

    dsp->vp8_idct_add       = ff_vp8_idct_add_neon;

    dsp->vp8_idct_dc_add    = ff_vp8_idct_dc_add_neon;

    dsp->vp8_idct_dc_add4y  = ff_vp8_idct_dc_add4y_neon;

    dsp->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_neon;

    dsp->vp8_v_loop_filter16y = ff_vp8_v_loop_filter16_neon;

    dsp->vp8_h_loop_filter16y = ff_vp8_h_loop_filter16_neon;

    dsp->vp8_v_loop_filter8uv = ff_vp8_v_loop_filter8uv_neon;

    dsp->vp8_h_loop_filter8uv = ff_vp8_h_loop_filter8uv_neon;

    dsp->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16_inner_neon;

    dsp->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16_inner_neon;

    dsp->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_neon;

    dsp->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_neon;

    dsp->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter16_simple_neon;

    dsp->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter16_simple_neon;

    dsp->put_vp8_epel_pixels_tab[0][0][0] = ff_put_vp8_pixels16_neon;

    dsp->put_vp8_epel_pixels_tab[0][0][2] = ff_put_vp8_epel16_h6_neon;

    dsp->put_vp8_epel_pixels_tab[0][2][0] = ff_put_vp8_epel16_v6_neon;

    dsp->put_vp8_epel_pixels_tab[0][2][2] = ff_put_vp8_epel16_h6v6_neon;

    dsp->put_vp8_epel_pixels_tab[1][0][0] = ff_put_vp8_pixels8_neon;

    dsp->put_vp8_epel_pixels_tab[1][0][1] = ff_put_vp8_epel8_h4_neon;

    dsp->put_vp8_epel_pixels_tab[1][0][2] = ff_put_vp8_epel8_h6_neon;

    dsp->put_vp8_epel_pixels_tab[1][1][0] = ff_put_vp8_epel8_v4_neon;

    dsp->put_vp8_epel_pixels_tab[1][1][1] = ff_put_vp8_epel8_h4v4_neon;

    dsp->put_vp8_epel_pixels_tab[1][1][2] = ff_put_vp8_epel8_h6v4_neon;

    dsp->put_vp8_epel_pixels_tab[1][2][0] = ff_put_vp8_epel8_v6_neon;

    dsp->put_vp8_epel_pixels_tab[1][2][1] = ff_put_vp8_epel8_h4v6_neon;

    dsp->put_vp8_epel_pixels_tab[1][2][2] = ff_put_vp8_epel8_h6v6_neon;

    dsp->put_vp8_epel_pixels_tab[2][0][1] = ff_put_vp8_epel4_h4_neon;

    dsp->put_vp8_epel_pixels_tab[2][0][2] = ff_put_vp8_epel4_h6_neon;

    dsp->put_vp8_epel_pixels_tab[2][1][0] = ff_put_vp8_epel4_v4_neon;

    dsp->put_vp8_epel_pixels_tab[2][1][1] = ff_put_vp8_epel4_h4v4_neon;

    dsp->put_vp8_epel_pixels_tab[2][1][2] = ff_put_vp8_epel4_h6v4_neon;

    dsp->put_vp8_epel_pixels_tab[2][2][0] = ff_put_vp8_epel4_v6_neon;

    dsp->put_vp8_epel_pixels_tab[2][2][1] = ff_put_vp8_epel4_h4v6_neon;

    dsp->put_vp8_epel_pixels_tab[2][2][2] = ff_put_vp8_epel4_h6v6_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][0][1] = ff_put_vp8_bilin16_h_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][0][2] = ff_put_vp8_bilin16_h_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][1][0] = ff_put_vp8_bilin16_v_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][1][1] = ff_put_vp8_bilin16_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][1][2] = ff_put_vp8_bilin16_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][2][0] = ff_put_vp8_bilin16_v_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][2][1] = ff_put_vp8_bilin16_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[0][2][2] = ff_put_vp8_bilin16_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][0][1] = ff_put_vp8_bilin8_h_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][0][2] = ff_put_vp8_bilin8_h_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][1][0] = ff_put_vp8_bilin8_v_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][1][1] = ff_put_vp8_bilin8_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][1][2] = ff_put_vp8_bilin8_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][2][0] = ff_put_vp8_bilin8_v_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][2][1] = ff_put_vp8_bilin8_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[1][2][2] = ff_put_vp8_bilin8_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][0][1] = ff_put_vp8_bilin4_h_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][0][2] = ff_put_vp8_bilin4_h_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][1][0] = ff_put_vp8_bilin4_v_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][1][1] = ff_put_vp8_bilin4_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][1][2] = ff_put_vp8_bilin4_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][2][0] = ff_put_vp8_bilin4_v_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][2][1] = ff_put_vp8_bilin4_hv_neon;

    dsp->put_vp8_bilinear_pixels_tab[2][2][2] = ff_put_vp8_bilin4_hv_neon;

}


static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested,

                                    uint32_t *byte_len)

{

    int num_cq_events = 0, ret = 0;

    struct ibv_cq *cq;

    void *cq_ctx;

    uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;

    if (ibv_req_notify_cq(rdma->cq, 0)) {

        return -1;

    }

    /* poll cq first */

    while (wr_id != wrid_requested) {

        ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);

        if (ret < 0) {

            return ret;

        }

        wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

        if (wr_id == RDMA_WRID_NONE) {

            break;

        }

        if (wr_id != wrid_requested) {

            trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested),

                       wrid_requested, print_wrid(wr_id), wr_id);

        }

    }

    if (wr_id == wrid_requested) {

        return 0;

    }

    while (1) {

        /*

         * Coroutine doesn't start until migration_fd_process_incoming()

         * so don't yield unless we know we're running inside of a coroutine.

         */

        if (rdma->migration_started_on_destination) {

            yield_until_fd_readable(rdma->comp_channel->fd);

        }

        ret = ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx);

        if (ret) {

            perror("ibv_get_cq_event");

            goto err_block_for_wrid;

        }

        num_cq_events++;

        ret = -ibv_req_notify_cq(cq, 0);

        if (ret) {

            goto err_block_for_wrid;

        }

        while (wr_id != wrid_requested) {

            ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);

            if (ret < 0) {

                goto err_block_for_wrid;

            }

            wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

            if (wr_id == RDMA_WRID_NONE) {

                break;

            }

            if (wr_id != wrid_requested) {

                trace_qemu_rdma_block_for_wrid_miss(print_wrid(wrid_requested),

                                   wrid_requested, print_wrid(wr_id), wr_id);

            }

        }

        if (wr_id == wrid_requested) {

            goto success_block_for_wrid;

        }

    }

success_block_for_wrid:

    if (num_cq_events) {

        ibv_ack_cq_events(cq, num_cq_events);

    }

    return 0;

err_block_for_wrid:

    if (num_cq_events) {

        ibv_ack_cq_events(cq, num_cq_events);

    }

    rdma->error_state = ret;

    return ret;

}


static void mmio_ide_cmd_write(void *opaque, target_phys_addr_t addr,

                               uint64_t val, unsigned size)

{

    MMIOState *s = opaque;

    ide_cmd_write(&s->bus, 0, val);

}


static void xenfb_copy_mfns(int mode, int count, unsigned long *dst, void *src)

{

    uint32_t *src32 = src;

    uint64_t *src64 = src;

    int i;

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

	dst[i] = (mode == 32) ? src32[i] : src64[i];

}


void memory_region_unregister_iommu_notifier(MemoryRegion *mr, Notifier *n)

{

    notifier_remove(n);

    if (mr->iommu_ops->notify_stopped &&

        QLIST_EMPTY(&mr->iommu_notify.notifiers)) {

        mr->iommu_ops->notify_stopped(mr);

    }

}


int inet_connect(const char *str, bool block, Error **errp)

{

    QemuOpts *opts;

    int sock = -1;

    opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);

    if (inet_parse(opts, str) == 0) {

        if (block) {

            qemu_opt_set(opts, "block", "on");

        }

        sock = inet_connect_opts(opts, errp);

    } else {

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

    }

    qemu_opts_del(opts);

    return sock;

}


static void eth_send(mv88w8618_eth_state *s, int queue_index)

{

    uint32_t desc_addr = s->tx_queue[queue_index];

    mv88w8618_tx_desc desc;

    uint8_t buf[2048];

    int len;

    do {

        eth_tx_desc_get(desc_addr, &desc);

        if (desc.cmdstat & MP_ETH_TX_OWN) {

            len = desc.bytes;

            if (len < 2048) {

                cpu_physical_memory_read(desc.buffer, buf, len);

                qemu_send_packet(s->vc, buf, len);

            }

            desc.cmdstat &= ~MP_ETH_TX_OWN;

            s->icr |= 1 << (MP_ETH_IRQ_TXLO_BIT - queue_index);

            eth_tx_desc_put(desc_addr, &desc);

        }

        desc_addr = desc.next;

    } while (desc_addr != s->tx_queue[queue_index]);

}


static void test_submit_aio(void)

{

    WorkerTestData data = { .n = 0, .ret = -EINPROGRESS };

    data.aiocb = thread_pool_submit_aio(worker_cb, &data, done_cb, &data);

    /* The callbacks are not called until after the first wait.  */

    active = 1;

    g_assert_cmpint(data.ret, ==, -EINPROGRESS);

    qemu_aio_flush();

    g_assert_cmpint(active, ==, 0);

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.ret, ==, 0);

}


static int hls_start(AVFormatContext *s)

{

    HLSContext *c = s->priv_data;

    AVFormatContext *oc = c->avf;

    int err = 0;

    if (c->wrap)

        c->number %= c->wrap;

    if (av_get_frame_filename(oc->filename, sizeof(oc->filename),

                              c->basename, c->number++) < 0)

        return AVERROR(EINVAL);

    if ((err = avio_open2(&oc->pb, oc->filename, AVIO_FLAG_WRITE,

                          &s->interrupt_callback, NULL)) < 0)

        return err;

    if (oc->oformat->priv_class && oc->priv_data)

        av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);

    return 0;

}


void migrate_decompress_threads_create(void)

{

    int i, thread_count;

    thread_count = migrate_decompress_threads();

    decompress_threads = g_new0(QemuThread, thread_count);

    decomp_param = g_new0(DecompressParam, thread_count);

    quit_decomp_thread = false;

    qemu_mutex_init(&decomp_done_lock);

    qemu_cond_init(&decomp_done_cond);

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

        qemu_mutex_init(&decomp_param[i].mutex);

        qemu_cond_init(&decomp_param[i].cond);

        decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));

        decomp_param[i].done = true;

        qemu_thread_create(decompress_threads + i, "decompress",

                           do_data_decompress, decomp_param + i,

                           QEMU_THREAD_JOINABLE);

    }

}


void qdev_prop_set_drive(DeviceState *dev, const char *name, DriveInfo *value)

{

    qdev_prop_set(dev, name, &value, PROP_TYPE_DRIVE);

}


static void ppc_spapr_reset(void)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    PowerPCCPU *first_ppc_cpu;

    uint32_t rtas_limit;

    /* Check for unknown sysbus devices */

    foreach_dynamic_sysbus_device(find_unknown_sysbus_device, NULL);

    /* Reset the hash table & recalc the RMA */

    spapr_reset_htab(spapr);

    qemu_devices_reset();

    /*

     * We place the device tree and RTAS just below either the top of the RMA,

     * or just below 2GB, whichever is lowere, so that it can be

     * processed with 32-bit real mode code if necessary

     */

    rtas_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR);

    spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE;

    spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE;

    /* Load the fdt */

    spapr_finalize_fdt(spapr, spapr->fdt_addr, spapr->rtas_addr,

                       spapr->rtas_size);

    /* Copy RTAS over */

    cpu_physical_memory_write(spapr->rtas_addr, spapr->rtas_blob,

                              spapr->rtas_size);

    /* Set up the entry state */

    first_ppc_cpu = POWERPC_CPU(first_cpu);

    first_ppc_cpu->env.gpr[3] = spapr->fdt_addr;

    first_ppc_cpu->env.gpr[5] = 0;

    first_cpu->halted = 0;

    first_ppc_cpu->env.nip = spapr->entry_point;

}


static void create_one_flash(const char *name, hwaddr flashbase,

                             hwaddr flashsize)

{

    /* Create and map a single flash device. We use the same

     * parameters as the flash devices on the Versatile Express board.

     */

    DriveInfo *dinfo = drive_get_next(IF_PFLASH);

    DeviceState *dev = qdev_create(NULL, "cfi.pflash01");

    const uint64_t sectorlength = 256 * 1024;

    if (dinfo && qdev_prop_set_drive(dev, "drive",

                                     blk_bs(blk_by_legacy_dinfo(dinfo)))) {

        abort();

    }

    qdev_prop_set_uint32(dev, "num-blocks", flashsize / sectorlength);

    qdev_prop_set_uint64(dev, "sector-length", sectorlength);

    qdev_prop_set_uint8(dev, "width", 4);

    qdev_prop_set_uint8(dev, "device-width", 2);

    qdev_prop_set_uint8(dev, "big-endian", 0);

    qdev_prop_set_uint16(dev, "id0", 0x89);

    qdev_prop_set_uint16(dev, "id1", 0x18);

    qdev_prop_set_uint16(dev, "id2", 0x00);

    qdev_prop_set_uint16(dev, "id3", 0x00);

    qdev_prop_set_string(dev, "name", name);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, flashbase);

}


gdb_handlesig (CPUState *env, int sig)

{

  GDBState *s;

  char buf[256];

  int n;

  s = &gdbserver_state;

  if (gdbserver_fd < 0 || s->fd < 0)

    return sig;

  /* disable single step if it was enabled */

  cpu_single_step(env, 0);

  tb_flush(env);

  if (sig != 0)

    {

      snprintf(buf, sizeof(buf), "S%02x", sig);

      put_packet(s, buf);

    }

  /* put_packet() might have detected that the peer terminated the

     connection.  */

  if (s->fd < 0)

      return sig;

  sig = 0;

  s->state = RS_IDLE;

  s->running_state = 0;

  while (s->running_state == 0) {

      n = read (s->fd, buf, 256);

      if (n > 0)

        {

          int i;

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

            gdb_read_byte (s, buf[i]);

        }

      else if (n == 0 || errno != EAGAIN)

        {

          /* XXX: Connection closed.  Should probably wait for annother

             connection before continuing.  */

          return sig;

        }

  }

  sig = s->signal;

  s->signal = 0;

  return sig;

}


uint32_t HELPER(csst)(CPUS390XState *env, uint32_t r3, uint64_t a1, uint64_t a2)

{

#if !defined(CONFIG_USER_ONLY) || defined(CONFIG_ATOMIC128)

    uint32_t mem_idx = cpu_mmu_index(env, false);

#endif

    uintptr_t ra = GETPC();

    uint32_t fc = extract32(env->regs[0], 0, 8);

    uint32_t sc = extract32(env->regs[0], 8, 8);

    uint64_t pl = get_address(env, 1) & -16;

    uint64_t svh, svl;

    uint32_t cc;

    /* Sanity check the function code and storage characteristic.  */

    if (fc > 1 || sc > 3) {

        if (!s390_has_feat(S390_FEAT_COMPARE_AND_SWAP_AND_STORE_2)) {

            goto spec_exception;

        }

        if (fc > 2 || sc > 4 || (fc == 2 && (r3 & 1))) {

            goto spec_exception;

        }

    }

    /* Sanity check the alignments.  */

    if (extract32(a1, 0, 4 << fc) || extract32(a2, 0, 1 << sc)) {

        goto spec_exception;

    }

    /* Sanity check writability of the store address.  */

#ifndef CONFIG_USER_ONLY

    probe_write(env, a2, mem_idx, ra);

#endif

    /* Note that the compare-and-swap is atomic, and the store is atomic, but

       the complete operation is not.  Therefore we do not need to assert serial

       context in order to implement this.  That said, restart early if we can't

       support either operation that is supposed to be atomic.  */

    if (parallel_cpus) {

        int mask = 0;

#if !defined(CONFIG_ATOMIC64)

        mask = -8;

#elif !defined(CONFIG_ATOMIC128)

        mask = -16;

#endif

        if (((4 << fc) | (1 << sc)) & mask) {

            cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);

        }

    }

    /* All loads happen before all stores.  For simplicity, load the entire

       store value area from the parameter list.  */

    svh = cpu_ldq_data_ra(env, pl + 16, ra);

    svl = cpu_ldq_data_ra(env, pl + 24, ra);

    switch (fc) {

    case 0:

        {

            uint32_t nv = cpu_ldl_data_ra(env, pl, ra);

            uint32_t cv = env->regs[r3];

            uint32_t ov;

            if (parallel_cpus) {

#ifdef CONFIG_USER_ONLY

                uint32_t *haddr = g2h(a1);

                ov = atomic_cmpxchg__nocheck(haddr, cv, nv);

#else

                TCGMemOpIdx oi = make_memop_idx(MO_TEUL | MO_ALIGN, mem_idx);

                ov = helper_atomic_cmpxchgl_be_mmu(env, a1, cv, nv, oi, ra);

#endif

            } else {

                ov = cpu_ldl_data_ra(env, a1, ra);

                cpu_stl_data_ra(env, a1, (ov == cv ? nv : ov), ra);

            }

            cc = (ov != cv);

            env->regs[r3] = deposit64(env->regs[r3], 32, 32, ov);

        }

        break;

    case 1:

        {

            uint64_t nv = cpu_ldq_data_ra(env, pl, ra);

            uint64_t cv = env->regs[r3];

            uint64_t ov;

            if (parallel_cpus) {

#ifdef CONFIG_ATOMIC64

# ifdef CONFIG_USER_ONLY

                uint64_t *haddr = g2h(a1);

                ov = atomic_cmpxchg__nocheck(haddr, cv, nv);

# else

                TCGMemOpIdx oi = make_memop_idx(MO_TEQ | MO_ALIGN, mem_idx);

                ov = helper_atomic_cmpxchgq_be_mmu(env, a1, cv, nv, oi, ra);

# endif

#else

                /* Note that we asserted !parallel_cpus above.  */

                g_assert_not_reached();

#endif

            } else {

                ov = cpu_ldq_data_ra(env, a1, ra);

                cpu_stq_data_ra(env, a1, (ov == cv ? nv : ov), ra);

            }

            cc = (ov != cv);

            env->regs[r3] = ov;

        }

        break;

    case 2:

        {

            uint64_t nvh = cpu_ldq_data_ra(env, pl, ra);

            uint64_t nvl = cpu_ldq_data_ra(env, pl + 8, ra);

            Int128 nv = int128_make128(nvl, nvh);

            Int128 cv = int128_make128(env->regs[r3 + 1], env->regs[r3]);

            Int128 ov;

            if (parallel_cpus) {

#ifdef CONFIG_ATOMIC128

                TCGMemOpIdx oi = make_memop_idx(MO_TEQ | MO_ALIGN_16, mem_idx);

                ov = helper_atomic_cmpxchgo_be_mmu(env, a1, cv, nv, oi, ra);

                cc = !int128_eq(ov, cv);

#else

                /* Note that we asserted !parallel_cpus above.  */

                g_assert_not_reached();

#endif

            } else {

                uint64_t oh = cpu_ldq_data_ra(env, a1 + 0, ra);

                uint64_t ol = cpu_ldq_data_ra(env, a1 + 8, ra);

                ov = int128_make128(ol, oh);

                cc = !int128_eq(ov, cv);

                if (cc) {

                    nv = ov;

                }

                cpu_stq_data_ra(env, a1 + 0, int128_gethi(nv), ra);

                cpu_stq_data_ra(env, a1 + 8, int128_getlo(nv), ra);

            }

            env->regs[r3 + 0] = int128_gethi(ov);

            env->regs[r3 + 1] = int128_getlo(ov);

        }

        break;

    default:

        g_assert_not_reached();

    }

    /* Store only if the comparison succeeded.  Note that above we use a pair

       of 64-bit big-endian loads, so for sc < 3 we must extract the value

       from the most-significant bits of svh.  */

    if (cc == 0) {

        switch (sc) {

        case 0:

            cpu_stb_data_ra(env, a2, svh >> 56, ra);

            break;

        case 1:

            cpu_stw_data_ra(env, a2, svh >> 48, ra);

            break;

        case 2:

            cpu_stl_data_ra(env, a2, svh >> 32, ra);

            break;

        case 3:

            cpu_stq_data_ra(env, a2, svh, ra);

            break;

        case 4:

            if (parallel_cpus) {

#ifdef CONFIG_ATOMIC128

                TCGMemOpIdx oi = make_memop_idx(MO_TEQ | MO_ALIGN_16, mem_idx);

                Int128 sv = int128_make128(svl, svh);

                helper_atomic_sto_be_mmu(env, a2, sv, oi, ra);

#else

                /* Note that we asserted !parallel_cpus above.  */

                g_assert_not_reached();

#endif

            } else {

                cpu_stq_data_ra(env, a2 + 0, svh, ra);

                cpu_stq_data_ra(env, a2 + 8, svl, ra);

            }

            break;

        default:

            g_assert_not_reached();

        }

    }

    return cc;

 spec_exception:

    cpu_restore_state(ENV_GET_CPU(env), ra);

    program_interrupt(env, PGM_SPECIFICATION, 6);

    g_assert_not_reached();

}


static void nbd_request_put(NBDRequest *req)

{

    NBDClient *client = req->client;

    if (req->data) {

        qemu_vfree(req->data);

    }

    g_slice_free(NBDRequest, req);

    if (client->nb_requests-- == MAX_NBD_REQUESTS) {

        qemu_notify_event();

    }

    nbd_client_put(client);

}


void timerlistgroup_deinit(QEMUTimerListGroup *tlg)

{

    QEMUClockType type;

    for (type = 0; type < QEMU_CLOCK_MAX; type++) {

        timerlist_free(tlg->tl[type]);

    }

}


static int nbd_receive_options(NBDClient *client)

{

    int csock = client->sock;

    uint32_t flags;

    /* Client sends:

        [ 0 ..   3]   client flags

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   NBD option

        [12 ..  15]   Data length

        ...           Rest of request

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   Second NBD option

        [12 ..  15]   Data length

        ...           Rest of request

    */

    if (read_sync(csock, &flags, sizeof(flags)) != sizeof(flags)) {

        LOG("read failed");

        return -EIO;

    }

    TRACE("Checking client flags");

    be32_to_cpus(&flags);

    if (flags != 0 && flags != NBD_FLAG_C_FIXED_NEWSTYLE) {

        LOG("Bad client flags received");

        return -EIO;

    }

    while (1) {

        int ret;

        uint32_t tmp, length;

        uint64_t magic;

        if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {

            LOG("read failed");

            return -EINVAL;

        }

        TRACE("Checking opts magic");

        if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {

            LOG("Bad magic received");

            return -EINVAL;

        }

        if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {

            LOG("read failed");

            return -EINVAL;

        }

        if (read_sync(csock, &length, sizeof(length)) != sizeof(length)) {

            LOG("read failed");

            return -EINVAL;

        }

        length = be32_to_cpu(length);

        TRACE("Checking option");

        switch (be32_to_cpu(tmp)) {

        case NBD_OPT_LIST:

            ret = nbd_handle_list(client, length);

            if (ret < 0) {

                return ret;

            }

            break;

        case NBD_OPT_ABORT:

            return -EINVAL;

        case NBD_OPT_EXPORT_NAME:

            return nbd_handle_export_name(client, length);

        default:

            tmp = be32_to_cpu(tmp);

            LOG("Unsupported option 0x%x", tmp);

            nbd_send_rep(client->sock, NBD_REP_ERR_UNSUP, tmp);

            return -EINVAL;

        }

    }

}


void xtensa_breakpoint_handler(CPUState *cs)

{

    XtensaCPU *cpu = XTENSA_CPU(cs);

    CPUXtensaState *env = &cpu->env;

    if (cs->watchpoint_hit) {

        if (cs->watchpoint_hit->flags & BP_CPU) {

            uint32_t cause;

            cs->watchpoint_hit = NULL;

            cause = check_hw_breakpoints(env);

            if (cause) {

                debug_exception_env(env, cause);

            }

            cpu_resume_from_signal(cs, NULL);

        }

    }

}


static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)

{

    const QCowHeader *cow_header = (const void *)buf;

    if (buf_size >= sizeof(QCowHeader) &&

        be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&

        be32_to_cpu(cow_header->version) >= QCOW_VERSION)

        return 100;

    else

        return 0;

}


static int read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    BinkDemuxContext *bink = s->priv_data;

    AVIOContext *pb = s->pb;

    uint32_t fps_num, fps_den;

    AVStream *vst, *ast;

    unsigned int i;

    uint32_t pos, next_pos;

    uint16_t flags;

    int keyframe;

    vst = av_new_stream(s, 0);

    if (!vst)

        return AVERROR(ENOMEM);

    vst->codec->codec_tag = avio_rl32(pb);

    bink->file_size = avio_rl32(pb) + 8;

    vst->duration   = avio_rl32(pb);

    if (vst->duration > 1000000) {

        av_log(s, AV_LOG_ERROR, "invalid header: more than 1000000 frames\n");

        return AVERROR(EIO);

    }

    if (avio_rl32(pb) > bink->file_size) {

        av_log(s, AV_LOG_ERROR,

               "invalid header: largest frame size greater than file size\n");

        return AVERROR(EIO);

    }

    avio_skip(pb, 4);

    vst->codec->width  = avio_rl32(pb);

    vst->codec->height = avio_rl32(pb);

    fps_num = avio_rl32(pb);

    fps_den = avio_rl32(pb);

    if (fps_num == 0 || fps_den == 0) {

        av_log(s, AV_LOG_ERROR, "invalid header: invalid fps (%d/%d)\n", fps_num, fps_den);

        return AVERROR(EIO);

    }

    av_set_pts_info(vst, 64, fps_den, fps_num);

    vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    vst->codec->codec_id   = CODEC_ID_BINKVIDEO;

    vst->codec->extradata  = av_mallocz(4 + FF_INPUT_BUFFER_PADDING_SIZE);

    vst->codec->extradata_size = 4;

    avio_read(pb, vst->codec->extradata, 4);

    bink->num_audio_tracks = avio_rl32(pb);

    if (bink->num_audio_tracks > BINK_MAX_AUDIO_TRACKS) {

        av_log(s, AV_LOG_ERROR,

               "invalid header: more than "AV_STRINGIFY(BINK_MAX_AUDIO_TRACKS)" audio tracks (%d)\n",

               bink->num_audio_tracks);

        return AVERROR(EIO);

    }

    if (bink->num_audio_tracks) {

        avio_skip(pb, 4 * bink->num_audio_tracks);

        for (i = 0; i < bink->num_audio_tracks; i++) {

            ast = av_new_stream(s, 1);

            if (!ast)

                return AVERROR(ENOMEM);

            ast->codec->codec_type  = AVMEDIA_TYPE_AUDIO;

            ast->codec->codec_tag   = vst->codec->codec_tag;

            ast->codec->sample_rate = avio_rl16(pb);

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

            flags = avio_rl16(pb);

            ast->codec->codec_id = flags & BINK_AUD_USEDCT ?

                                   CODEC_ID_BINKAUDIO_DCT : CODEC_ID_BINKAUDIO_RDFT;

            ast->codec->channels = flags & BINK_AUD_STEREO ? 2 : 1;

        }

        for (i = 0; i < bink->num_audio_tracks; i++)

            s->streams[i + 1]->id = avio_rl32(pb);

    }

    /* frame index table */

    next_pos = avio_rl32(pb);

    for (i = 0; i < vst->duration; i++) {

        pos = next_pos;

        if (i == vst->duration - 1) {

            next_pos = bink->file_size;

            keyframe = 0;

        } else {

            next_pos = avio_rl32(pb);

            keyframe = pos & 1;

        }

        pos &= ~1;

        next_pos &= ~1;

        if (next_pos <= pos) {

            av_log(s, AV_LOG_ERROR, "invalid frame index table\n");

            return AVERROR(EIO);

        }

        av_add_index_entry(vst, pos, i, next_pos - pos, 0,

                           keyframe ? AVINDEX_KEYFRAME : 0);

    }

    avio_skip(pb, 4);

    bink->current_track = -1;

    return 0;

}


static int ftp_status(FTPContext *s, char **line, const int response_codes[])

{

    int err, i, result = 0, pref_code_found = 0, wait_count = 100;

    char buf[CONTROL_BUFFER_SIZE];

    /* Set blocking mode */

    s->conn_control_block_flag = 0;

    for (;;) {

        if ((err = ftp_get_line(s, buf, sizeof(buf))) < 0) {

            if (err == AVERROR_EXIT) {

                if (!pref_code_found && wait_count--) {

                    av_usleep(10000);

                    continue;

                }

            }

            return result;

        }

        av_log(s, AV_LOG_DEBUG, "%s\n", buf);

        if (!pref_code_found) {

            if (strlen(buf) < 3)

                continue;

            err = 0;

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

                if (buf[i] < '0' || buf[i] > '9')

                    continue;

                err *= 10;

                err += buf[i] - '0';

            }

            for (i = 0; response_codes[i]; ++i) {

                if (err == response_codes[i]) {

                    /* first code received. Now get all lines in non blocking mode */

                    s->conn_control_block_flag = 1;

                    pref_code_found = 1;

                    result = err;

                    if (line)

                        *line = av_strdup(buf);

                    break;

                }

            }

        }

    }

    return result;

}


static void unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)

{

    int i, j, k;

    int coding_mode;

    int motion_x[6];

    int motion_y[6];

    int last_motion_x = 0;

    int last_motion_y = 0;

    int prior_last_motion_x = 0;

    int prior_last_motion_y = 0;

    int current_macroblock;

    int current_fragment;

    debug_vp3("  vp3: unpacking motion vectors\n");

    if (s->keyframe) {

        debug_vp3("    keyframe-- there are no motion vectors\n");

    } else {

        memset(motion_x, 0, 6 * sizeof(int));

        memset(motion_y, 0, 6 * sizeof(int));

        /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */

        coding_mode = get_bits(gb, 1);

        debug_vectors("    using %s scheme for unpacking motion vectors\n",

            (coding_mode == 0) ? "VLC" : "fixed-length");

        /* iterate through all of the macroblocks that contain 1 or more

         * coded fragments */

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

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

                current_macroblock = s->superblock_macroblocks[i * 4 + j];

                if ((current_macroblock == -1) ||

                    (!s->macroblock_coded[current_macroblock]))

                    continue;

                current_fragment = s->macroblock_fragments[current_macroblock * 6];

                switch (s->all_fragments[current_fragment].coding_method) {

                case MODE_INTER_PLUS_MV:

                case MODE_GOLDEN_MV:

                    /* all 6 fragments use the same motion vector */

                    if (coding_mode == 0) {

                        motion_x[0] = get_motion_vector_vlc(gb);

                        motion_y[0] = get_motion_vector_vlc(gb);

                    } else {

                        motion_x[0] = get_motion_vector_fixed(gb);

                        motion_y[0] = get_motion_vector_fixed(gb);

                    }

                    for (k = 1; k < 6; k++) {

                        motion_x[k] = motion_x[0];

                        motion_y[k] = motion_y[0];

                    }

                    /* vector maintenance, only on MODE_INTER_PLUS_MV */

                    if (s->all_fragments[current_fragment].coding_method ==

                        MODE_INTER_PLUS_MV) {

                        prior_last_motion_x = last_motion_x;

                        prior_last_motion_y = last_motion_y;

                        last_motion_x = motion_x[0];

                        last_motion_y = motion_y[0];

                    }

                    break;

                case MODE_INTER_FOURMV:

                    /* fetch 4 vectors from the bitstream, one for each

                     * Y fragment, then average for the C fragment vectors */

                    motion_x[4] = motion_y[4] = 0;

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

                        if (coding_mode == 0) {

                            motion_x[k] = get_motion_vector_vlc(gb);

                            motion_y[k] = get_motion_vector_vlc(gb);

                        } else {

                            motion_x[k] = get_motion_vector_fixed(gb);

                            motion_y[k] = get_motion_vector_fixed(gb);

                        }

                        motion_x[4] += motion_x[k];

                        motion_y[4] += motion_y[k];

                    }

                    if (motion_x[4] >= 0)

                        motion_x[4] = (motion_x[4] + 2) / 4;

                    else

                        motion_x[4] = (motion_x[4] - 2) / 4;

                    motion_x[5] = motion_x[4];

                    if (motion_y[4] >= 0)

                        motion_y[4] = (motion_y[4] + 2) / 4;

                    else

                        motion_y[4] = (motion_y[4] - 2) / 4;

                    motion_y[5] = motion_y[4];

                    /* vector maintenance; vector[3] is treated as the

                     * last vector in this case */

                    prior_last_motion_x = last_motion_x;

                    prior_last_motion_y = last_motion_y;

                    last_motion_x = motion_x[3];

                    last_motion_y = motion_y[3];

                    break;

                case MODE_INTER_LAST_MV:

                    /* all 6 fragments use the last motion vector */

                    motion_x[0] = last_motion_x;

                    motion_y[0] = last_motion_y;

                    for (k = 1; k < 6; k++) {

                        motion_x[k] = motion_x[0];

                        motion_y[k] = motion_y[0];

                    }

                    /* no vector maintenance (last vector remains the

                     * last vector) */

                    break;

                case MODE_INTER_PRIOR_LAST:

                    /* all 6 fragments use the motion vector prior to the

                     * last motion vector */

                    motion_x[0] = prior_last_motion_x;

                    motion_y[0] = prior_last_motion_y;

                    for (k = 1; k < 6; k++) {

                        motion_x[k] = motion_x[0];

                        motion_y[k] = motion_y[0];

                    }

                    /* vector maintenance */

                    prior_last_motion_x = last_motion_x;

                    prior_last_motion_y = last_motion_y;

                    last_motion_x = motion_x[0];

                    last_motion_y = motion_y[0];

                    break;

                default:

                    /* covers intra, inter without MV, golden without MV */

                    memset(motion_x, 0, 6 * sizeof(int));

                    memset(motion_y, 0, 6 * sizeof(int));

                    /* no vector maintenance */

                    break;

                }

                /* assign the motion vectors to the correct fragments */

                debug_vectors("    vectors for macroblock starting @ fragment %d (coding method %d):\n",

                    current_fragment,

                    s->all_fragments[current_fragment].coding_method);

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

                    current_fragment =

                        s->macroblock_fragments[current_macroblock * 6 + k];

                    s->all_fragments[current_fragment].motion_halfpel_index =

                        adjust_vector(&motion_x[k], &motion_y[k],

                        ((k == 4) || (k == 5)));

                    s->all_fragments[current_fragment].motion_x = motion_x[k];

                    s->all_fragments[current_fragment].motion_y = motion_y[k];

                    debug_vectors("    vector %d: fragment %d = (%d, %d), index %d\n",

                        k, current_fragment, motion_x[k], motion_y[k],

                        s->all_fragments[current_fragment].motion_halfpel_index);

                }

            }

        }

    }

}


static void ipvideo_decode_opcodes(IpvideoContext *s, AVFrame *frame)

{

    int x, y;

    unsigned char opcode;

    int ret;

    GetBitContext gb;

    bytestream2_skip(&s->stream_ptr, 14); /* data starts 14 bytes in */

    if (!s->is_16bpp) {

        /* this is PAL8, so make the palette available */

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

        s->stride = frame->linesize[0];

    } else {

        s->stride = frame->linesize[0] >> 1;

        s->mv_ptr = s->stream_ptr;

        bytestream2_skip(&s->mv_ptr, bytestream2_get_le16(&s->stream_ptr));

    }

    s->line_inc = s->stride - 8;

    s->upper_motion_limit_offset = (s->avctx->height - 8) * frame->linesize[0]

                                  + (s->avctx->width - 8) * (1 + s->is_16bpp);

    init_get_bits(&gb, s->decoding_map, s->decoding_map_size * 8);

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

        for (x = 0; x < s->avctx->width; x += 8) {

            if (get_bits_left(&gb) < 4)

                return;

            opcode = get_bits(&gb, 4);

            ff_tlog(s->avctx,

                    "  block @ (%3d, %3d): encoding 0x%X, data ptr offset %d\n",

                    x, y, opcode, bytestream2_tell(&s->stream_ptr));

            if (!s->is_16bpp) {

                s->pixel_ptr = frame->data[0] + x

                              + y*frame->linesize[0];

                ret = ipvideo_decode_block[opcode](s, frame);

            } else {

                s->pixel_ptr = frame->data[0] + x*2

                              + y*frame->linesize[0];

                ret = ipvideo_decode_block16[opcode](s, frame);

            }

            if (ret != 0) {

                av_log(s->avctx, AV_LOG_ERROR, "decode problem on frame %d, @ block (%d, %d)\n",

                       s->avctx->frame_number, x, y);

                return;

            }

        }

    }

    if (bytestream2_get_bytes_left(&s->stream_ptr) > 1) {

        av_log(s->avctx, AV_LOG_DEBUG,

               "decode finished with %d bytes left over\n",

               bytestream2_get_bytes_left(&s->stream_ptr));

    }

}