static void gd_update_geometry_hints(VirtualConsole *vc)

{

    GtkDisplayState *s = vc->s;

    GdkWindowHints mask = 0;

    GdkGeometry geo = {};

    GtkWidget *geo_widget = NULL;

    GtkWindow *geo_window;

    if (vc->type == GD_VC_GFX) {

        if (!vc->gfx.ds) {

            return;

        }

        if (s->free_scale) {

            geo.min_width  = surface_width(vc->gfx.ds) * VC_SCALE_MIN;

            geo.min_height = surface_height(vc->gfx.ds) * VC_SCALE_MIN;

            mask |= GDK_HINT_MIN_SIZE;

        } else {

            geo.min_width  = surface_width(vc->gfx.ds) * vc->gfx.scale_x;

            geo.min_height = surface_height(vc->gfx.ds) * vc->gfx.scale_y;

            mask |= GDK_HINT_MIN_SIZE;

        }

        geo_widget = vc->gfx.drawing_area;

        gtk_widget_set_size_request(geo_widget, geo.min_width, geo.min_height);

#if defined(CONFIG_VTE)

    } else if (vc->type == GD_VC_VTE) {

        VteTerminal *term = VTE_TERMINAL(vc->vte.terminal);

        GtkBorder *ib;

        geo.width_inc  = vte_terminal_get_char_width(term);

        geo.height_inc = vte_terminal_get_char_height(term);

        mask |= GDK_HINT_RESIZE_INC;

        geo.base_width  = geo.width_inc;

        geo.base_height = geo.height_inc;

        mask |= GDK_HINT_BASE_SIZE;

        geo.min_width  = geo.width_inc * VC_TERM_X_MIN;

        geo.min_height = geo.height_inc * VC_TERM_Y_MIN;

        mask |= GDK_HINT_MIN_SIZE;

        gtk_widget_style_get(vc->vte.terminal, "inner-border", &ib, NULL);

        geo.base_width  += ib->left + ib->right;

        geo.base_height += ib->top + ib->bottom;

        geo.min_width   += ib->left + ib->right;

        geo.min_height  += ib->top + ib->bottom;

        geo_widget = vc->vte.terminal;

#endif

    }

    geo_window = GTK_WINDOW(vc->window ? vc->window : s->window);

    gtk_window_set_geometry_hints(geo_window, geo_widget, &geo, mask);

}


static uint32_t cc_calc_abs_64(int64_t dst)

{

    if ((uint64_t)dst == 0x8000000000000000ULL) {

        return 3;

    } else if (dst) {

        return 1;

    } else {

        return 0;

    }

}


static void virtio_serial_device_unrealize(DeviceState *dev, Error **errp)
{
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOSerial *vser = VIRTIO_SERIAL(dev);
    QLIST_REMOVE(vser, next);
    g_free(vser->ivqs);
    g_free(vser->ovqs);
    g_free(vser->ports_map);
    if (vser->post_load) {
        g_free(vser->post_load->connected);
        timer_del(vser->post_load->timer);
        timer_free(vser->post_load->timer);
        g_free(vser->post_load);
    }
    virtio_cleanup(vdev);
}


static int flashsv2_prime(FlashSVContext *s, uint8_t *src, int size)
{
    z_stream zs;
    int zret; // Zlib return code
    zs.zalloc = NULL;
    zs.zfree  = NULL;
    zs.opaque = NULL;
    s->zstream.next_in   = src;
    s->zstream.avail_in  = size;
    s->zstream.next_out  = s->tmpblock;
    s->zstream.avail_out = s->block_size * 3;
    inflate(&s->zstream, Z_SYNC_FLUSH);
    if (deflateInit(&zs, 0) != Z_OK)
        return -1;
    zs.next_in   = s->tmpblock;
    zs.avail_in  = s->block_size * 3 - s->zstream.avail_out;
    zs.next_out  = s->deflate_block;
    zs.avail_out = s->deflate_block_size;
    deflate(&zs, Z_SYNC_FLUSH);
    deflateEnd(&zs);
    if ((zret = inflateReset(&s->zstream)) != Z_OK) {
        av_log(s->avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);
        return AVERROR_UNKNOWN;
    }
    s->zstream.next_in   = s->deflate_block;
    s->zstream.avail_in  = s->deflate_block_size - zs.avail_out;
    s->zstream.next_out  = s->tmpblock;
    s->zstream.avail_out = s->block_size * 3;
    inflate(&s->zstream, Z_SYNC_FLUSH);
    return 0;
}


static void sbr_hf_assemble(int Y1[38][64][2],

                            const int X_high[64][40][2],

                            SpectralBandReplication *sbr, SBRData *ch_data,

                            const int e_a[2])

{

    int e, i, j, m;

    const int h_SL = 4 * !sbr->bs_smoothing_mode;

    const int kx = sbr->kx[1];

    const int m_max = sbr->m[1];

    static const SoftFloat h_smooth[5] = {

      { 715827883, -1 },

      { 647472402, -1 },

      { 937030863, -2 },

      { 989249804, -3 },

      { 546843842, -4 },

    };

    SoftFloat (*g_temp)[48] = ch_data->g_temp, (*q_temp)[48] = ch_data->q_temp;

    int indexnoise = ch_data->f_indexnoise;

    int indexsine  = ch_data->f_indexsine;

    if (sbr->reset) {

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

            memcpy(g_temp[i + 2*ch_data->t_env[0]], sbr->gain[0], m_max * sizeof(sbr->gain[0][0]));

            memcpy(q_temp[i + 2*ch_data->t_env[0]], sbr->q_m[0],  m_max * sizeof(sbr->q_m[0][0]));

        }

    } else if (h_SL) {

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

            memcpy(g_temp[i + 2 * ch_data->t_env[0]],

                   g_temp[i + 2 * ch_data->t_env_num_env_old],

                   sizeof(g_temp[0]));

            memcpy(q_temp[i + 2 * ch_data->t_env[0]],

                   q_temp[i + 2 * ch_data->t_env_num_env_old],

                   sizeof(q_temp[0]));

        }

    }

    for (e = 0; e < ch_data->bs_num_env; e++) {

        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {

            memcpy(g_temp[h_SL + i], sbr->gain[e], m_max * sizeof(sbr->gain[0][0]));

            memcpy(q_temp[h_SL + i], sbr->q_m[e],  m_max * sizeof(sbr->q_m[0][0]));

        }

    }

    for (e = 0; e < ch_data->bs_num_env; e++) {

        for (i = 2 * ch_data->t_env[e]; i < 2 * ch_data->t_env[e + 1]; i++) {

            SoftFloat g_filt_tab[48];

            SoftFloat q_filt_tab[48];

            SoftFloat *g_filt, *q_filt;

            if (h_SL && e != e_a[0] && e != e_a[1]) {

                g_filt = g_filt_tab;

                q_filt = q_filt_tab;

                for (m = 0; m < m_max; m++) {

                    const int idx1 = i + h_SL;

                    g_filt[m].mant = g_filt[m].exp = 0;

                    q_filt[m].mant = q_filt[m].exp = 0;

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

                        g_filt[m] = av_add_sf(g_filt[m],

                                        av_mul_sf(g_temp[idx1 - j][m],

                                            h_smooth[j]));

                        q_filt[m] = av_add_sf(q_filt[m],

                                        av_mul_sf(q_temp[idx1 - j][m],

                                            h_smooth[j]));

                    }

                }

            } else {

                g_filt = g_temp[i + h_SL];

                q_filt = q_temp[i];

            }

            sbr->dsp.hf_g_filt(Y1[i] + kx, X_high + kx, g_filt, m_max,

                               i + ENVELOPE_ADJUSTMENT_OFFSET);

            if (e != e_a[0] && e != e_a[1]) {

                sbr->dsp.hf_apply_noise[indexsine](Y1[i] + kx, sbr->s_m[e],

                                                   q_filt, indexnoise,

                                                   kx, m_max);

            } else {

                int idx = indexsine&1;

                int A = (1-((indexsine+(kx & 1))&2));

                int B = (A^(-idx)) + idx;

                int *out = &Y1[i][kx][idx];

                int shift, round;

                SoftFloat *in  = sbr->s_m[e];

                for (m = 0; m+1 < m_max; m+=2) {

                    shift = 22 - in[m  ].exp;

                    if (shift < 32) {

                        round = 1 << (shift-1);

                        out[2*m  ] += (in[m  ].mant * A + round) >> shift;

                    }

                    shift = 22 - in[m+1].exp;

                    if (shift < 32) {

                        round = 1 << (shift-1);

                        out[2*m+2] += (in[m+1].mant * B + round) >> shift;

                    }

                }

                if(m_max&1)

                {

                    shift = 22 - in[m  ].exp;

                    if (shift < 32) {

                        round = 1 << (shift-1);

                        out[2*m  ] += (in[m  ].mant * A + round) >> shift;

                    }

                }

            }

            indexnoise = (indexnoise + m_max) & 0x1ff;

            indexsine = (indexsine + 1) & 3;

        }

    }

    ch_data->f_indexnoise = indexnoise;

    ch_data->f_indexsine  = indexsine;

}


static int vid_probe(AVProbeData *p)

{

    // little endian VID tag, file starts with "VID\0"

    if (p->buf_size < 4 || AV_RL32(p->buf) != MKTAG('V', 'I', 'D', 0))

        return 0;

    return AVPROBE_SCORE_MAX;

}


static inline void gen_intermediate_code_internal(X86CPU *cpu,

                                                  TranslationBlock *tb,

                                                  bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUX86State *env = &cpu->env;

    DisasContext dc1, *dc = &dc1;

    target_ulong pc_ptr;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj;

    uint64_t flags;

    target_ulong pc_start;

    target_ulong cs_base;

    int num_insns;

    int max_insns;

    /* generate intermediate code */

    pc_start = tb->pc;

    cs_base = tb->cs_base;

    flags = tb->flags;

    dc->pe = (flags >> HF_PE_SHIFT) & 1;

    dc->code32 = (flags >> HF_CS32_SHIFT) & 1;

    dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;

    dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;

    dc->f_st = 0;

    dc->vm86 = (flags >> VM_SHIFT) & 1;

    dc->cpl = (flags >> HF_CPL_SHIFT) & 3;

    dc->iopl = (flags >> IOPL_SHIFT) & 3;

    dc->tf = (flags >> TF_SHIFT) & 1;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->cc_op = CC_OP_DYNAMIC;

    dc->cc_op_dirty = false;

    dc->cs_base = cs_base;

    dc->tb = tb;

    dc->popl_esp_hack = 0;

    /* select memory access functions */

    dc->mem_index = 0;

    if (flags & HF_SOFTMMU_MASK) {

        dc->mem_index = cpu_mmu_index(env);

    }

    dc->cpuid_features = env->features[FEAT_1_EDX];

    dc->cpuid_ext_features = env->features[FEAT_1_ECX];

    dc->cpuid_ext2_features = env->features[FEAT_8000_0001_EDX];

    dc->cpuid_ext3_features = env->features[FEAT_8000_0001_ECX];

    dc->cpuid_7_0_ebx_features = env->features[FEAT_7_0_EBX];

#ifdef TARGET_X86_64

    dc->lma = (flags >> HF_LMA_SHIFT) & 1;

    dc->code64 = (flags >> HF_CS64_SHIFT) & 1;

#endif

    dc->flags = flags;

    dc->jmp_opt = !(dc->tf || cs->singlestep_enabled ||

                    (flags & HF_INHIBIT_IRQ_MASK)

#ifndef CONFIG_SOFTMMU

                    || (flags & HF_SOFTMMU_MASK)

#endif

                    );

#if 0

    /* check addseg logic */

    if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32))

        printf("ERROR addseg\n");

#endif

    cpu_T[0] = tcg_temp_new();

    cpu_T[1] = tcg_temp_new();

    cpu_A0 = tcg_temp_new();

    cpu_tmp0 = tcg_temp_new();

    cpu_tmp1_i64 = tcg_temp_new_i64();

    cpu_tmp2_i32 = tcg_temp_new_i32();

    cpu_tmp3_i32 = tcg_temp_new_i32();

    cpu_tmp4 = tcg_temp_new();

    cpu_ptr0 = tcg_temp_new_ptr();

    cpu_ptr1 = tcg_temp_new_ptr();

    cpu_cc_srcT = tcg_temp_local_new();

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    pc_ptr = pc_start;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_tb_start();

    for(;;) {

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

            QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

                if (bp->pc == pc_ptr &&

                    !((bp->flags & BP_CPU) && (tb->flags & HF_RF_MASK))) {

                    gen_debug(dc, pc_ptr - dc->cs_base);

                    break;

                }

            }

        }

        if (search_pc) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

            }

            tcg_ctx.gen_opc_pc[lj] = pc_ptr;

            gen_opc_cc_op[lj] = dc->cc_op;

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))

            gen_io_start();

        pc_ptr = disas_insn(env, dc, pc_ptr);

        num_insns++;

        /* stop translation if indicated */

        if (dc->is_jmp)

            break;

        /* if single step mode, we generate only one instruction and

           generate an exception */

        /* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear

           the flag and abort the translation to give the irqs a

           change to be happen */

        if (dc->tf || dc->singlestep_enabled ||

            (flags & HF_INHIBIT_IRQ_MASK)) {

            gen_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

        /* if too long translation, stop generation too */

        if (tcg_ctx.gen_opc_ptr >= gen_opc_end ||

            (pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32) ||

            num_insns >= max_insns) {

            gen_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

        if (singlestep) {

            gen_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    /* we don't forget to fill the last values */

    if (search_pc) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        lj++;

        while (lj <= j)

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

    }

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        int disas_flags;

        qemu_log("----------------\n");

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

#ifdef TARGET_X86_64

        if (dc->code64)

            disas_flags = 2;

        else

#endif

            disas_flags = !dc->code32;

        log_target_disas(env, pc_start, pc_ptr - pc_start, disas_flags);

        qemu_log("\n");

    }

#endif

    if (!search_pc) {

        tb->size = pc_ptr - pc_start;

        tb->icount = num_insns;

    }

}


static always_inline void gen_op_subfo (void)

{

    gen_op_move_T2_T0();

    gen_op_subf();

    gen_op_check_subfo();

}


static void fd_accept_incoming_migration(void *opaque)

{

    QEMUFile *f = opaque;

    qemu_set_fd_handler2(qemu_get_fd(f), NULL, NULL, NULL, NULL);

    process_incoming_migration(f);

}


hwaddr ppc_hash64_get_phys_page_debug(PowerPCCPU *cpu, target_ulong addr)

{

    CPUPPCState *env = &cpu->env;

    ppc_slb_t *slb;

    hwaddr pte_offset;

    ppc_hash_pte64_t pte;

    unsigned apshift;

    if (msr_dr == 0) {

        /* In real mode the top 4 effective address bits are ignored */

        return addr & 0x0FFFFFFFFFFFFFFFULL;

    }

    slb = slb_lookup(cpu, addr);

    if (!slb) {

        return -1;

    }

    pte_offset = ppc_hash64_htab_lookup(cpu, slb, addr, &pte);

    if (pte_offset == -1) {

        return -1;

    }

    apshift = hpte_page_shift(slb->sps, pte.pte0, pte.pte1);

    if (!apshift) {

        return -1;

    }

    return deposit64(pte.pte1 & HPTE64_R_RPN, 0, apshift, addr)

        & TARGET_PAGE_MASK;

}


static int adx_read_header(AVFormatContext *s)

{

    ADXDemuxerContext *c = s->priv_data;

    AVCodecParameters *par;

    AVStream *st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    par = s->streams[0]->codecpar;

    if (avio_rb16(s->pb) != 0x8000)

        return AVERROR_INVALIDDATA;

    c->header_size = avio_rb16(s->pb) + 4;

    avio_seek(s->pb, -4, SEEK_CUR);

    if (ff_get_extradata(s, par, s->pb, c->header_size) < 0)

        return AVERROR(ENOMEM);

    if (par->extradata_size < 12) {

        av_log(s, AV_LOG_ERROR, "Invalid extradata size.\n");

        return AVERROR_INVALIDDATA;

    }

    par->channels    = AV_RB8 (par->extradata + 7);

    par->sample_rate = AV_RB32(par->extradata + 8);

    if (par->channels <= 0) {

        av_log(s, AV_LOG_ERROR, "invalid number of channels %d\n", par->channels);

        return AVERROR_INVALIDDATA;

    }

    if (par->sample_rate <= 0) {

        av_log(s, AV_LOG_ERROR, "Invalid sample rate %d\n", par->sample_rate);

        return AVERROR_INVALIDDATA;

    }

    par->codec_type  = AVMEDIA_TYPE_AUDIO;

    par->codec_id    = s->iformat->raw_codec_id;

    par->bit_rate    = par->sample_rate * par->channels * BLOCK_SIZE * 8LL / BLOCK_SAMPLES;

    avpriv_set_pts_info(st, 64, BLOCK_SAMPLES, par->sample_rate);

    return 0;

}


static void virgl_cmd_get_capset(VirtIOGPU *g,

                                 struct virtio_gpu_ctrl_command *cmd)

{

    struct virtio_gpu_get_capset gc;

    struct virtio_gpu_resp_capset *resp;

    uint32_t max_ver, max_size;

    VIRTIO_GPU_FILL_CMD(gc);

    virgl_renderer_get_cap_set(gc.capset_id, &max_ver,

                               &max_size);

    if (!max_size) {

        cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;

        return;

    }

    resp = g_malloc(sizeof(*resp) + max_size);

    resp->hdr.type = VIRTIO_GPU_RESP_OK_CAPSET;

    virgl_renderer_fill_caps(gc.capset_id,

                             gc.capset_version,

                             (void *)resp->capset_data);

    virtio_gpu_ctrl_response(g, cmd, &resp->hdr, sizeof(*resp) + max_size);

    g_free(resp);

}


static int qcow2_open(BlockDriverState *bs, QDict *options, int flags)
{
    BDRVQcowState *s = bs->opaque;
    int len, i, ret = 0;
    QCowHeader header;
    QemuOpts *opts;
    Error *local_err = NULL;
    uint64_t ext_end;
    uint64_t l1_vm_state_index;
    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
    if (ret < 0) {
    be32_to_cpus(&header.magic);
    be32_to_cpus(&header.version);
    be64_to_cpus(&header.backing_file_offset);
    be32_to_cpus(&header.backing_file_size);
    be64_to_cpus(&header.size);
    be32_to_cpus(&header.cluster_bits);
    be32_to_cpus(&header.crypt_method);
    be64_to_cpus(&header.l1_table_offset);
    be32_to_cpus(&header.l1_size);
    be64_to_cpus(&header.refcount_table_offset);
    be32_to_cpus(&header.refcount_table_clusters);
    be64_to_cpus(&header.snapshots_offset);
    be32_to_cpus(&header.nb_snapshots);
    if (header.magic != QCOW_MAGIC) {
        ret = -EMEDIUMTYPE;
    if (header.version < 2 || header.version > 3) {
        report_unsupported(bs, "QCOW version %d", header.version);
        ret = -ENOTSUP;
    s->qcow_version = header.version;
    /* Initialise version 3 header fields */
    if (header.version == 2) {
        header.incompatible_features    = 0;
        header.compatible_features      = 0;
        header.autoclear_features       = 0;
        header.refcount_order           = 4;
        header.header_length            = 72;
    } else {
        be64_to_cpus(&header.incompatible_features);
        be64_to_cpus(&header.compatible_features);
        be64_to_cpus(&header.autoclear_features);
        be32_to_cpus(&header.refcount_order);
        be32_to_cpus(&header.header_length);
    if (header.header_length > sizeof(header)) {
        s->unknown_header_fields_size = header.header_length - sizeof(header);
        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
                         s->unknown_header_fields_size);
        if (ret < 0) {
    if (header.backing_file_offset) {
        ext_end = header.backing_file_offset;
    } else {
        ext_end = 1 << header.cluster_bits;
    /* Handle feature bits */
    s->incompatible_features    = header.incompatible_features;
    s->compatible_features      = header.compatible_features;
    s->autoclear_features       = header.autoclear_features;
    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
        void *feature_table = NULL;
        qcow2_read_extensions(bs, header.header_length, ext_end,
                              &feature_table);
        report_unsupported_feature(bs, feature_table,
                                   s->incompatible_features &
                                   ~QCOW2_INCOMPAT_MASK);
        ret = -ENOTSUP;
    /* Check support for various header values */
    if (header.refcount_order != 4) {
        report_unsupported(bs, "%d bit reference counts",
                           1 << header.refcount_order);
        ret = -ENOTSUP;
    if (header.cluster_bits < MIN_CLUSTER_BITS ||
        header.cluster_bits > MAX_CLUSTER_BITS) {
        ret = -EINVAL;
    if (header.crypt_method > QCOW_CRYPT_AES) {
        ret = -EINVAL;
    s->crypt_method_header = header.crypt_method;
    if (s->crypt_method_header) {
        bs->encrypted = 1;
    s->cluster_bits = header.cluster_bits;
    s->cluster_size = 1 << s->cluster_bits;
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
    s->l2_size = 1 << s->l2_bits;
    bs->total_sectors = header.size / 512;
    s->csize_shift = (62 - (s->cluster_bits - 8));
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
    s->refcount_table_offset = header.refcount_table_offset;
    s->refcount_table_size =
        header.refcount_table_clusters << (s->cluster_bits - 3);
    s->snapshots_offset = header.snapshots_offset;
    s->nb_snapshots = header.nb_snapshots;
    /* read the level 1 table */
    s->l1_size = header.l1_size;
    l1_vm_state_index = size_to_l1(s, header.size);
    if (l1_vm_state_index > INT_MAX) {
        ret = -EFBIG;
    s->l1_vm_state_index = l1_vm_state_index;
    /* the L1 table must contain at least enough entries to put
       header.size bytes */
    if (s->l1_size < s->l1_vm_state_index) {
        ret = -EINVAL;
    s->l1_table_offset = header.l1_table_offset;
    if (s->l1_size > 0) {
        s->l1_table = g_malloc0(
            align_offset(s->l1_size * sizeof(uint64_t), 512));
        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
                         s->l1_size * sizeof(uint64_t));
        if (ret < 0) {
        for(i = 0;i < s->l1_size; i++) {
            be64_to_cpus(&s->l1_table[i]);
    /* alloc L2 table/refcount block cache */
    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
    s->cluster_cache = g_malloc(s->cluster_size);
    /* one more sector for decompressed data alignment */
    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
                                  + 512);
    s->cluster_cache_offset = -1;
    s->flags = flags;
    ret = qcow2_refcount_init(bs);
    if (ret != 0) {
    QLIST_INIT(&s->cluster_allocs);
    QTAILQ_INIT(&s->discards);
    /* read qcow2 extensions */
    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {
        ret = -EINVAL;
    /* read the backing file name */
    if (header.backing_file_offset != 0) {
        len = header.backing_file_size;
        if (len > 1023) {
            len = 1023;
        ret = bdrv_pread(bs->file, header.backing_file_offset,
                         bs->backing_file, len);
        if (ret < 0) {
        bs->backing_file[len] = '\0';
    ret = qcow2_read_snapshots(bs);
    if (ret < 0) {
    /* Clear unknown autoclear feature bits */
    if (!bs->read_only && s->autoclear_features != 0) {
        s->autoclear_features = 0;
        ret = qcow2_update_header(bs);
        if (ret < 0) {
    /* Initialise locks */
    qemu_co_mutex_init(&s->lock);
    /* Repair image if dirty */
    if (!(flags & BDRV_O_CHECK) && !bs->read_only &&
        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
        BdrvCheckResult result = {0};
        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
        if (ret < 0) {
    /* Enable lazy_refcounts according to image and command line options */
    opts = qemu_opts_create_nofail(&qcow2_runtime_opts);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (error_is_set(&local_err)) {
        qerror_report_err(local_err);
        error_free(local_err);
        ret = -EINVAL;
    s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
        (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
    s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
    s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
    s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
                          flags & BDRV_O_UNMAP);
    s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
    s->discard_passthrough[QCOW2_DISCARD_OTHER] =
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
    qemu_opts_del(opts);
    if (s->use_lazy_refcounts && s->qcow_version < 3) {
        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Lazy refcounts require "
            "a qcow2 image with at least qemu 1.1 compatibility level");
        ret = -EINVAL;
#ifdef DEBUG_ALLOC
    {
        BdrvCheckResult result = {0};
        qcow2_check_refcounts(bs, &result, 0);
#endif
    return ret;
 fail:
    g_free(s->unknown_header_fields);
    cleanup_unknown_header_ext(bs);
    qcow2_free_snapshots(bs);
    qcow2_refcount_close(bs);
    g_free(s->l1_table);
    if (s->l2_table_cache) {
        qcow2_cache_destroy(bs, s->l2_table_cache);
    g_free(s->cluster_cache);
    qemu_vfree(s->cluster_data);
    return ret;


static void decode_subband(DiracContext *s, GetBitContext *gb, int quant,

                           int slice_x, int slice_y, int bits_end,

                           SubBand *b1, SubBand *b2)

{

    int left   = b1->width  * slice_x    / s->num_x;

    int right  = b1->width  *(slice_x+1) / s->num_x;

    int top    = b1->height * slice_y    / s->num_y;

    int bottom = b1->height *(slice_y+1) / s->num_y;

    int qfactor = qscale_tab[quant & 0x7f];

    int qoffset = qoffset_intra_tab[quant & 0x7f] + 2;

    uint8_t *buf1 =      b1->ibuf + top * b1->stride;

    uint8_t *buf2 = b2 ? b2->ibuf + top * b2->stride: NULL;

    int x, y;

    /* we have to constantly check for overread since the spec explicitly

       requires this, with the meaning that all remaining coeffs are set to 0 */

    if (get_bits_count(gb) >= bits_end)

        return;

    if (s->pshift) {

        for (y = top; y < bottom; y++) {

            for (x = left; x < right; x++) {

                PARSE_VALUES(int32_t, x, gb, bits_end, buf1, buf2);

            }

            buf1 += b1->stride;

            if (buf2)

                buf2 += b2->stride;

        }

    }

    else {

        for (y = top; y < bottom; y++) {

            for (x = left; x < right; x++) {

                PARSE_VALUES(int16_t, x, gb, bits_end, buf1, buf2);

            }

            buf1 += b1->stride;

            if (buf2)

                buf2 += b2->stride;

        }

    }

}


int spapr_h_cas_compose_response(sPAPRMachineState *spapr,

                                 target_ulong addr, target_ulong size,

                                 bool cpu_update,

                                 sPAPROptionVector *ov5_updates)

{

    void *fdt, *fdt_skel;

    sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 };

    size -= sizeof(hdr);

    /* Create sceleton */

    fdt_skel = g_malloc0(size);

    _FDT((fdt_create(fdt_skel, size)));

    _FDT((fdt_begin_node(fdt_skel, "")));

    _FDT((fdt_end_node(fdt_skel)));

    _FDT((fdt_finish(fdt_skel)));

    fdt = g_malloc0(size);

    _FDT((fdt_open_into(fdt_skel, fdt, size)));

    g_free(fdt_skel);

    /* Fixup cpu nodes */

    if (cpu_update) {

        _FDT((spapr_fixup_cpu_dt(fdt, spapr)));

    }

    if (spapr_dt_cas_updates(spapr, fdt, ov5_updates)) {

        return -1;

    }

    /* Pack resulting tree */

    _FDT((fdt_pack(fdt)));

    if (fdt_totalsize(fdt) + sizeof(hdr) > size) {

        trace_spapr_cas_failed(size);

        return -1;

    }

    cpu_physical_memory_write(addr, &hdr, sizeof(hdr));

    cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt));

    trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr));

    g_free(fdt);

    return 0;

}


void kvmppc_hash64_write_pte(CPUPPCState *env, target_ulong pte_index,

                             target_ulong pte0, target_ulong pte1)

{

    int htab_fd;

    struct kvm_get_htab_fd ghf;

    struct kvm_get_htab_buf hpte_buf;

    ghf.flags = 0;

    ghf.start_index = 0;     /* Ignored */

    htab_fd = kvm_vm_ioctl(kvm_state, KVM_PPC_GET_HTAB_FD, &ghf);

    if (htab_fd < 0) {

        goto error_out;

    }

    hpte_buf.header.n_valid = 1;

    hpte_buf.header.n_invalid = 0;

    hpte_buf.header.index = pte_index;

    hpte_buf.hpte[0] = pte0;

    hpte_buf.hpte[1] = pte1;

    /*

     * Write the hpte entry.

     * CAUTION: write() has the warn_unused_result attribute. Hence we

     * need to check the return value, even though we do nothing.

     */

    if (write(htab_fd, &hpte_buf, sizeof(hpte_buf)) < 0) {

        goto out_close;

    }

out_close:

    close(htab_fd);

    return;

error_out:

    return;

}


int tcp_start_outgoing_migration(MigrationState *s, const char *host_port,

                                 Error **errp)

{

    s->get_error = socket_errno;

    s->write = socket_write;

    s->close = tcp_close;

    s->fd = inet_connect(host_port, false, errp);

    if (!error_is_set(errp)) {

        migrate_fd_connect(s);

    } else if (error_is_type(*errp, QERR_SOCKET_CONNECT_IN_PROGRESS)) {

        DPRINTF("connect in progress\n");

        qemu_set_fd_handler2(s->fd, NULL, NULL, tcp_wait_for_connect, s);

    } else if (error_is_type(*errp, QERR_SOCKET_CREATE_FAILED)) {

        DPRINTF("connect failed\n");

        return -1;

    } else if (error_is_type(*errp, QERR_SOCKET_CONNECT_FAILED)) {

        DPRINTF("connect failed\n");

        migrate_fd_error(s);

        return -1;

    } else {

        DPRINTF("unknown error\n");

        return -1;

    }

    return 0;

}


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

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    V9fsVirtioState *v = VIRTIO_9P(dev);

    V9fsState *s = &v->state;

    if (v9fs_device_realize_common(s, errp)) {

        goto out;

    }

    v->config_size = sizeof(struct virtio_9p_config) + strlen(s->fsconf.tag);

    virtio_init(vdev, "virtio-9p", VIRTIO_ID_9P, v->config_size);

    v->vq = virtio_add_queue(vdev, MAX_REQ, handle_9p_output);

    v9fs_register_transport(s, &virtio_9p_transport);

out:

    return;

}


static void trigger_access_exception(CPUS390XState *env, uint32_t type,

                                     uint32_t ilen, uint64_t tec)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    if (kvm_enabled()) {

        kvm_s390_access_exception(cpu, type, tec);

    } else {

        CPUState *cs = CPU(cpu);

        stq_phys(cs->as, env->psa + offsetof(LowCore, trans_exc_code), tec);

        trigger_pgm_exception(env, type, ilen);

    }

}


static void spapr_memory_unplug_request(HotplugHandler *hotplug_dev,

                                        DeviceState *dev, Error **errp)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(hotplug_dev);

    Error *local_err = NULL;

    PCDIMMDevice *dimm = PC_DIMM(dev);

    PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);

    MemoryRegion *mr = ddc->get_memory_region(dimm);

    uint64_t size = memory_region_size(mr);

    uint32_t nr_lmbs = size / SPAPR_MEMORY_BLOCK_SIZE;

    uint64_t addr_start, addr;

    int i;

    sPAPRDRConnector *drc;

    sPAPRDRConnectorClass *drck;

    sPAPRDIMMState *ds;

    addr_start = object_property_get_int(OBJECT(dimm), PC_DIMM_ADDR_PROP,

                                         &local_err);

    if (local_err) {

        goto out;

    }

    ds = g_malloc0(sizeof(sPAPRDIMMState));

    ds->nr_lmbs = nr_lmbs;

    ds->dimm = dimm;

    spapr_pending_dimm_unplugs_add(spapr, ds);

    addr = addr_start;

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

        drc = spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_LMB,

                addr / SPAPR_MEMORY_BLOCK_SIZE);

        g_assert(drc);

        drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

        drck->detach(drc, dev, spapr_lmb_release, NULL, errp);

        addr += SPAPR_MEMORY_BLOCK_SIZE;

    }

    drc = spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_LMB,

                                   addr_start / SPAPR_MEMORY_BLOCK_SIZE);

    drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    spapr_hotplug_req_remove_by_count_indexed(SPAPR_DR_CONNECTOR_TYPE_LMB,

                                              nr_lmbs,

                                              drck->get_index(drc));

out:

    error_propagate(errp, local_err);

}


static void l2x0_priv_write(void *opaque, target_phys_addr_t offset,

                            uint64_t value, unsigned size)

{

    l2x0_state *s = (l2x0_state *)opaque;

    offset &= 0xfff;

    if (offset >= 0x730 && offset < 0x800) {

        /* ignore */

        return;

    }

    switch (offset) {

    case 0x100:

        s->ctrl = value & 1;

        break;

    case 0x104:

        s->aux_ctrl = value;

        break;

    case 0x108:

        s->tag_ctrl = value;

        break;

    case 0x10C:

        s->data_ctrl = value;

        break;

    case 0xC00:

        s->filter_start = value;

        break;

    case 0xC04:

        s->filter_end = value;

        break;

    case 0xF40:

        return;

    case 0xF60:

        return;

    case 0xF80:

        return;

    default:

        fprintf(stderr, "l2x0_priv_write: Bad offset %x\n", (int)offset);

        break;

    }

}


static void json_emit_element(QJSON *json, const char *name)

{

    /* Check whether we need to print a , before an element */

    if (json->omit_comma) {

        json->omit_comma = false;

    } else {

        qstring_append(json->str, ", ");

    }

    if (name) {

        qstring_append(json->str, "\"");

        qstring_append(json->str, name);

        qstring_append(json->str, "\" : ");

    }

}


static bool vfio_pci_host_match(PCIHostDeviceAddress *host1,

                                PCIHostDeviceAddress *host2)

{

    return (host1->domain == host2->domain && host1->bus == host2->bus &&

            host1->slot == host2->slot && host1->function == host2->function);

}


int ff_ivi_dec_huff_desc(GetBitContext *gb, int desc_coded, int which_tab,

                         IVIHuffTab *huff_tab, AVCodecContext *avctx)

{

    int         i, result;

    IVIHuffDesc new_huff;

    if (!desc_coded) {

        /* select default table */

        huff_tab->tab = (which_tab) ? &ff_ivi_blk_vlc_tabs[7]

            : &ff_ivi_mb_vlc_tabs [7];

    } else {

        huff_tab->tab_sel = get_bits(gb, 3);

        if (huff_tab->tab_sel == 7) {

            /* custom huffman table (explicitly encoded) */

            new_huff.num_rows = get_bits(gb, 4);

            for (i = 0; i < new_huff.num_rows; i++)

                new_huff.xbits[i] = get_bits(gb, 4);

            /* Have we got the same custom table? Rebuild if not. */

            if (ff_ivi_huff_desc_cmp(&new_huff, &huff_tab->cust_desc)) {

                ff_ivi_huff_desc_copy(&huff_tab->cust_desc, &new_huff);

                if (huff_tab->cust_tab.table)

                    ff_free_vlc(&huff_tab->cust_tab);

                result = ff_ivi_create_huff_from_desc(&huff_tab->cust_desc,

                        &huff_tab->cust_tab, 0);

                if (result) {

                    av_log(avctx, AV_LOG_ERROR,

                           "Error while initializing custom vlc table!\n");

                    return -1;

                }

            }

            huff_tab->tab = &huff_tab->cust_tab;

        } else {

            /* select one of predefined tables */

            huff_tab->tab = (which_tab) ? &ff_ivi_blk_vlc_tabs[huff_tab->tab_sel]

                : &ff_ivi_mb_vlc_tabs [huff_tab->tab_sel];

        }

    }

    return 0;

}


int check_params(char *buf, int buf_size,

                 const char * const *params, const char *str)

{

    const char *p;

    int i;

    p = str;

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

        p = get_opt_name(buf, buf_size, p, '=');

        if (*p != '=') {

            return -1;

        }

        p++;

        for (i = 0; params[i] != NULL; i++) {

            if (!strcmp(params[i], buf)) {

                break;

            }

        }

        if (params[i] == NULL) {

            return -1;

        }

        p = get_opt_value(NULL, 0, p);

        if (*p != ',') {

            break;

        }

        p++;

    }

    return 0;

}


static void memory_region_update_container_subregions(MemoryRegion *subregion)

{

    hwaddr offset = subregion->addr;

    MemoryRegion *mr = subregion->container;

    MemoryRegion *other;

    memory_region_transaction_begin();

    memory_region_ref(subregion);

    QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {

        if (subregion->may_overlap || other->may_overlap) {

            continue;

        }

        if (int128_ge(int128_make64(offset),

                      int128_add(int128_make64(other->addr), other->size))

            || int128_le(int128_add(int128_make64(offset), subregion->size),

                         int128_make64(other->addr))) {

            continue;

        }

#if 0

        printf("warning: subregion collision %llx/%llx (%s) "

               "vs %llx/%llx (%s)\n",

               (unsigned long long)offset,

               (unsigned long long)int128_get64(subregion->size),

               subregion->name,

               (unsigned long long)other->addr,

               (unsigned long long)int128_get64(other->size),

               other->name);

#endif

    }

    QTAILQ_FOREACH(other, &mr->subregions, subregions_link) {

        if (subregion->priority >= other->priority) {

            QTAILQ_INSERT_BEFORE(other, subregion, subregions_link);

            goto done;

        }

    }

    QTAILQ_INSERT_TAIL(&mr->subregions, subregion, subregions_link);

done:

    memory_region_update_pending |= mr->enabled && subregion->enabled;

    memory_region_transaction_commit();

}


static int64_t coroutine_fn bdrv_qed_co_get_block_status(BlockDriverState *bs,

                                                 int64_t sector_num,

                                                 int nb_sectors, int *pnum)

{

    BDRVQEDState *s = bs->opaque;

    size_t len = (size_t)nb_sectors * BDRV_SECTOR_SIZE;

    QEDIsAllocatedCB cb = {

        .bs = bs,

        .pos = (uint64_t)sector_num * BDRV_SECTOR_SIZE,

        .status = BDRV_BLOCK_OFFSET_MASK,

        .pnum = pnum,

    };

    QEDRequest request = { .l2_table = NULL };

    qed_find_cluster(s, &request, cb.pos, len, qed_is_allocated_cb, &cb);

    /* Now sleep if the callback wasn't invoked immediately */

    while (cb.status == BDRV_BLOCK_OFFSET_MASK) {

        cb.co = qemu_coroutine_self();

        qemu_coroutine_yield();

    }

    qed_unref_l2_cache_entry(request.l2_table);

    return cb.status;

}


static sPAPRPHBState *find_phb(sPAPREnvironment *spapr, uint64_t buid)

{

    sPAPRPHBState *sphb;

    QLIST_FOREACH(sphb, &spapr->phbs, list) {

        if (sphb->buid != buid) {

            continue;

        }

        return sphb;

    }

    return NULL;

}


static void ahci_mem_write(void *opaque, target_phys_addr_t addr,

                           uint64_t val, unsigned size)

{

    AHCIState *s = opaque;

    /* Only aligned reads are allowed on AHCI */

    if (addr & 3) {

        fprintf(stderr, "ahci: Mis-aligned write to addr 0x"

                TARGET_FMT_plx "\n", addr);

        return;

    }

    if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) {

        DPRINTF(-1, "(addr 0x%08X), val 0x%08"PRIX64"\n", (unsigned) addr, val);

        switch (addr) {

            case HOST_CAP: /* R/WO, RO */

                /* FIXME handle R/WO */

                break;

            case HOST_CTL: /* R/W */

                if (val & HOST_CTL_RESET) {

                    DPRINTF(-1, "HBA Reset\n");

                    ahci_reset(s);

                } else {

                    s->control_regs.ghc = (val & 0x3) | HOST_CTL_AHCI_EN;

                    ahci_check_irq(s);

                }

                break;

            case HOST_IRQ_STAT: /* R/WC, RO */

                s->control_regs.irqstatus &= ~val;

                ahci_check_irq(s);

                break;

            case HOST_PORTS_IMPL: /* R/WO, RO */

                /* FIXME handle R/WO */

                break;

            case HOST_VERSION: /* RO */

                /* FIXME report write? */

                break;

            default:

                DPRINTF(-1, "write to unknown register 0x%x\n", (unsigned)addr);

        }

    } else if ((addr >= AHCI_PORT_REGS_START_ADDR) &&

               (addr < (AHCI_PORT_REGS_START_ADDR +

                (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) {

        ahci_port_write(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7,

                        addr & AHCI_PORT_ADDR_OFFSET_MASK, val);

    }

}


static void jpeg_term_destination(j_compress_ptr cinfo)

{

    VncState *vs = cinfo->client_data;

    Buffer *buffer = &vs->tight_jpeg;

    buffer->offset = buffer->capacity - cinfo->dest->free_in_buffer;

}


static void qdict_destroy_obj(QObject *obj)

{

    int i;

    QDict *qdict;

    assert(obj != NULL);

    qdict = qobject_to_qdict(obj);

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

        QDictEntry *entry = QLIST_FIRST(&qdict->table[i]);

        while (entry) {

            QDictEntry *tmp = QLIST_NEXT(entry, next);

            QLIST_REMOVE(entry, next);

            qentry_destroy(entry);

            entry = tmp;

        }

    }

    g_free(qdict);

}


static int pte64_check (mmu_ctx_t *ctx,

                        target_ulong pte0, target_ulong pte1, int h, int rw)

{

    return _pte_check(ctx, 1, pte0, pte1, h, rw);

}


static GenericList *qobject_input_next_list(Visitor *v, GenericList *tail,

                                            size_t size)

{

    QObjectInputVisitor *qiv = to_qiv(v);

    StackObject *so = QSLIST_FIRST(&qiv->stack);

    if (!so->entry) {

        return NULL;

    }

    tail->next = g_malloc0(size);

    return tail->next;

}


static int coroutine_fn v9fs_do_readdir_with_stat(V9fsPDU *pdu,

                                                  V9fsFidState *fidp,

                                                  uint32_t max_count)

{

    V9fsPath path;

    V9fsStat v9stat;

    int len, err = 0;

    int32_t count = 0;

    struct stat stbuf;

    off_t saved_dir_pos;

    struct dirent *dent;

    /* save the directory position */

    saved_dir_pos = v9fs_co_telldir(pdu, fidp);

    if (saved_dir_pos < 0) {

        return saved_dir_pos;

    }

    while (1) {

        v9fs_path_init(&path);

        v9fs_readdir_lock(&fidp->fs.dir);

        err = v9fs_co_readdir(pdu, fidp, &dent);

        if (err || !dent) {

            break;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, dent->d_name, &path);

        if (err < 0) {

            break;

        }

        err = v9fs_co_lstat(pdu, &path, &stbuf);

        if (err < 0) {

            break;

        }

        err = stat_to_v9stat(pdu, &path, dent->d_name, &stbuf, &v9stat);

        if (err < 0) {

            break;

        }

        /* 11 = 7 + 4 (7 = start offset, 4 = space for storing count) */

        len = pdu_marshal(pdu, 11 + count, "S", &v9stat);

        v9fs_readdir_unlock(&fidp->fs.dir);

        if ((len != (v9stat.size + 2)) || ((count + len) > max_count)) {

            /* Ran out of buffer. Set dir back to old position and return */

            v9fs_co_seekdir(pdu, fidp, saved_dir_pos);

            v9fs_stat_free(&v9stat);

            v9fs_path_free(&path);

            return count;

        }

        count += len;

        v9fs_stat_free(&v9stat);

        v9fs_path_free(&path);

        saved_dir_pos = dent->d_off;

    }

    v9fs_readdir_unlock(&fidp->fs.dir);

    v9fs_path_free(&path);

    if (err < 0) {

        return err;

    }

    return count;

}


static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,

                        int ac_index, int16_t *quant_matrix,

                        int ss, int se, int Al, int *EOBRUN)

{

    int code, i=ss, j, sign, val, run;

    int last = FFMIN(se, *last_nnz);

    OPEN_READER(re, &s->gb);

    if(*EOBRUN)

        (*EOBRUN)--;

    else {

        for(;;i++) {

            UPDATE_CACHE(re, &s->gb);

            GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)

            /* Progressive JPEG use AC coeffs from zero and this decoder sets offset 16 by default */

            code -= 16;

            if(code & 0xF) {

                run = ((unsigned) code) >> 4;

                UPDATE_CACHE(re, &s->gb);

                val = SHOW_UBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

                ZERO_RUN;

                j = s->scantable.permutated[i];

                val--;

                block[j] = ((quant_matrix[j]^val)-val) << Al;

                if(i == se) {

                    if(i > *last_nnz)

                        *last_nnz = i;

                    CLOSE_READER(re, &s->gb)

                    return 0;

                }

            }else{

                run = ((unsigned) code) >> 4;

                if(run == 0xF){

                    ZERO_RUN;

                }else{

                    val = run;

                    run = (1 << run);

                    if(val) {

                        UPDATE_CACHE(re, &s->gb);

                        run += SHOW_UBITS(re, &s->gb, val);

                        LAST_SKIP_BITS(re, &s->gb, val);

                    }

                    *EOBRUN = run - 1;

                    break;

                }

            }

        }

        if(i > *last_nnz)

            *last_nnz = i;

    }

    for(;i<=last;i++) {

        j = s->scantable.permutated[i];

        if(block[j])

            REFINE_BIT(j)

    }

    CLOSE_READER(re, &s->gb);

    return 0;

}


static void destroy_buffers(SANMVideoContext *ctx)

{

    av_freep(&ctx->frm0);

    av_freep(&ctx->frm1);

    av_freep(&ctx->frm2);

    av_freep(&ctx->stored_frame);

    av_freep(&ctx->rle_buf);

    ctx->frm0_size =

    ctx->frm1_size =

    ctx->frm2_size = 0;

}


void cpu_state_reset(CPUMIPSState *env)
{
    MIPSCPU *cpu = mips_env_get_cpu(env);
    CPUState *cs = CPU(cpu);
    /* Reset registers to their default values */
    env->CP0_PRid = env->cpu_model->CP0_PRid;
    env->CP0_Config0 = env->cpu_model->CP0_Config0;
#ifdef TARGET_WORDS_BIGENDIAN
    env->CP0_Config0 |= (1 << CP0C0_BE);
#endif
    env->CP0_Config1 = env->cpu_model->CP0_Config1;
    env->CP0_Config2 = env->cpu_model->CP0_Config2;
    env->CP0_Config3 = env->cpu_model->CP0_Config3;
    env->CP0_Config4 = env->cpu_model->CP0_Config4;
    env->CP0_Config4_rw_bitmask = env->cpu_model->CP0_Config4_rw_bitmask;
    env->CP0_Config5 = env->cpu_model->CP0_Config5;
    env->CP0_Config5_rw_bitmask = env->cpu_model->CP0_Config5_rw_bitmask;
    env->CP0_Config6 = env->cpu_model->CP0_Config6;
    env->CP0_Config7 = env->cpu_model->CP0_Config7;
    env->CP0_LLAddr_rw_bitmask = env->cpu_model->CP0_LLAddr_rw_bitmask
                                 << env->cpu_model->CP0_LLAddr_shift;
    env->CP0_LLAddr_shift = env->cpu_model->CP0_LLAddr_shift;
    env->SYNCI_Step = env->cpu_model->SYNCI_Step;
    env->CCRes = env->cpu_model->CCRes;
    env->CP0_Status_rw_bitmask = env->cpu_model->CP0_Status_rw_bitmask;
    env->CP0_TCStatus_rw_bitmask = env->cpu_model->CP0_TCStatus_rw_bitmask;
    env->CP0_SRSCtl = env->cpu_model->CP0_SRSCtl;
    env->current_tc = 0;
    env->SEGBITS = env->cpu_model->SEGBITS;
    env->SEGMask = (target_ulong)((1ULL << env->cpu_model->SEGBITS) - 1);
#if defined(TARGET_MIPS64)
    if (env->cpu_model->insn_flags & ISA_MIPS3) {
        env->SEGMask |= 3ULL << 62;
    }
#endif
    env->PABITS = env->cpu_model->PABITS;
    env->CP0_SRSConf0_rw_bitmask = env->cpu_model->CP0_SRSConf0_rw_bitmask;
    env->CP0_SRSConf0 = env->cpu_model->CP0_SRSConf0;
    env->CP0_SRSConf1_rw_bitmask = env->cpu_model->CP0_SRSConf1_rw_bitmask;
    env->CP0_SRSConf1 = env->cpu_model->CP0_SRSConf1;
    env->CP0_SRSConf2_rw_bitmask = env->cpu_model->CP0_SRSConf2_rw_bitmask;
    env->CP0_SRSConf2 = env->cpu_model->CP0_SRSConf2;
    env->CP0_SRSConf3_rw_bitmask = env->cpu_model->CP0_SRSConf3_rw_bitmask;
    env->CP0_SRSConf3 = env->cpu_model->CP0_SRSConf3;
    env->CP0_SRSConf4_rw_bitmask = env->cpu_model->CP0_SRSConf4_rw_bitmask;
    env->CP0_SRSConf4 = env->cpu_model->CP0_SRSConf4;
    env->CP0_PageGrain_rw_bitmask = env->cpu_model->CP0_PageGrain_rw_bitmask;
    env->CP0_PageGrain = env->cpu_model->CP0_PageGrain;
    env->CP0_EBaseWG_rw_bitmask = env->cpu_model->CP0_EBaseWG_rw_bitmask;
    env->active_fpu.fcr0 = env->cpu_model->CP1_fcr0;
    env->active_fpu.fcr31_rw_bitmask = env->cpu_model->CP1_fcr31_rw_bitmask;
    env->active_fpu.fcr31 = env->cpu_model->CP1_fcr31;
    env->msair = env->cpu_model->MSAIR;
    env->insn_flags = env->cpu_model->insn_flags;
#if defined(CONFIG_USER_ONLY)
    env->CP0_Status = (MIPS_HFLAG_UM << CP0St_KSU);
# ifdef TARGET_MIPS64
    /* Enable 64-bit register mode.  */
    env->CP0_Status |= (1 << CP0St_PX);
# endif
# ifdef TARGET_ABI_MIPSN64
    /* Enable 64-bit address mode.  */
    env->CP0_Status |= (1 << CP0St_UX);
# endif
    /* Enable access to the CPUNum, SYNCI_Step, CC, and CCRes RDHWR
       hardware registers.  */
    env->CP0_HWREna |= 0x0000000F;
    if (env->CP0_Config1 & (1 << CP0C1_FP)) {
        env->CP0_Status |= (1 << CP0St_CU1);
    }
    if (env->CP0_Config3 & (1 << CP0C3_DSPP)) {
        env->CP0_Status |= (1 << CP0St_MX);
    }
# if defined(TARGET_MIPS64)
    /* For MIPS64, init FR bit to 1 if FPU unit is there and bit is writable. */
    if ((env->CP0_Config1 & (1 << CP0C1_FP)) &&
        (env->CP0_Status_rw_bitmask & (1 << CP0St_FR))) {
        env->CP0_Status |= (1 << CP0St_FR);
    }
# endif
#else
    if (env->hflags & MIPS_HFLAG_BMASK) {
        /* If the exception was raised from a delay slot,
           come back to the jump.  */
        env->CP0_ErrorEPC = (env->active_tc.PC
                             - (env->hflags & MIPS_HFLAG_B16 ? 2 : 4));
    } else {
        env->CP0_ErrorEPC = env->active_tc.PC;
    }
    env->active_tc.PC = env->exception_base;
    env->CP0_Random = env->tlb->nb_tlb - 1;
    env->tlb->tlb_in_use = env->tlb->nb_tlb;
    env->CP0_Wired = 0;
    env->CP0_GlobalNumber = (cs->cpu_index & 0xFF) << CP0GN_VPId;
    env->CP0_EBase = (cs->cpu_index & 0x3FF);
    if (kvm_enabled()) {
        env->CP0_EBase |= 0x40000000;
    } else {
        env->CP0_EBase |= (int32_t)0x80000000;
    }
    if (env->CP0_Config3 & (1 << CP0C3_CMGCR)) {
        env->CP0_CMGCRBase = 0x1fbf8000 >> 4;
    }
    env->CP0_EntryHi_ASID_mask = (env->CP0_Config4 & (1 << CP0C4_AE)) ?
                                 0x3ff : 0xff;
    env->CP0_Status = (1 << CP0St_BEV) | (1 << CP0St_ERL);
    /* vectored interrupts not implemented, timer on int 7,
       no performance counters. */
    env->CP0_IntCtl = 0xe0000000;
    {
        int i;
        for (i = 0; i < 7; i++) {
            env->CP0_WatchLo[i] = 0;
            env->CP0_WatchHi[i] = 0x80000000;
        }
        env->CP0_WatchLo[7] = 0;
        env->CP0_WatchHi[7] = 0;
    }
    /* Count register increments in debug mode, EJTAG version 1 */
    env->CP0_Debug = (1 << CP0DB_CNT) | (0x1 << CP0DB_VER);
    cpu_mips_store_count(env, 1);
    if (env->CP0_Config3 & (1 << CP0C3_MT)) {
        int i;
        /* Only TC0 on VPE 0 starts as active.  */
        for (i = 0; i < ARRAY_SIZE(env->tcs); i++) {
            env->tcs[i].CP0_TCBind = cs->cpu_index << CP0TCBd_CurVPE;
            env->tcs[i].CP0_TCHalt = 1;
        }
        env->active_tc.CP0_TCHalt = 1;
        cs->halted = 1;
        if (cs->cpu_index == 0) {
            /* VPE0 starts up enabled.  */
            env->mvp->CP0_MVPControl |= (1 << CP0MVPCo_EVP);
            env->CP0_VPEConf0 |= (1 << CP0VPEC0_MVP) | (1 << CP0VPEC0_VPA);
            /* TC0 starts up unhalted.  */
            cs->halted = 0;
            env->active_tc.CP0_TCHalt = 0;
            env->tcs[0].CP0_TCHalt = 0;
            /* With thread 0 active.  */
            env->active_tc.CP0_TCStatus = (1 << CP0TCSt_A);
            env->tcs[0].CP0_TCStatus = (1 << CP0TCSt_A);
        }
    }
#endif
    if ((env->insn_flags & ISA_MIPS32R6) &&
        (env->active_fpu.fcr0 & (1 << FCR0_F64))) {
        /* Status.FR = 0 mode in 64-bit FPU not allowed in R6 */
        env->CP0_Status |= (1 << CP0St_FR);
    }
    /* MSA */
    if (env->CP0_Config3 & (1 << CP0C3_MSAP)) {
        msa_reset(env);
    }
    compute_hflags(env);
    restore_fp_status(env);
    restore_pamask(env);
    cs->exception_index = EXCP_NONE;
    if (semihosting_get_argc()) {
        /* UHI interface can be used to obtain argc and argv */
        env->active_tc.gpr[4] = -1;
    }
}


static void spapr_vio_quiesce_one(VIOsPAPRDevice *dev)

{

    dev->flags &= ~VIO_PAPR_FLAG_DMA_BYPASS;

    if (dev->rtce_table) {

        size_t size = (dev->rtce_window_size >> SPAPR_VIO_TCE_PAGE_SHIFT)

            * sizeof(VIOsPAPR_RTCE);

        memset(dev->rtce_table, 0, size);

    }

    dev->crq.qladdr = 0;

    dev->crq.qsize = 0;

    dev->crq.qnext = 0;

}


int av_image_alloc(uint8_t *pointers[4], int linesizes[4],
                   int w, int h, enum AVPixelFormat pix_fmt, int align)
{
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
    int i, ret;
    uint8_t *buf;
    if (!desc)
        return AVERROR(EINVAL);
    if ((ret = av_image_check_size(w, h, 0, NULL)) < 0)
        return ret;
    if ((ret = av_image_fill_linesizes(linesizes, pix_fmt, align>7 ? FFALIGN(w, 8) : w)) < 0)
        return ret;
    for (i = 0; i < 4; i++)
        linesizes[i] = FFALIGN(linesizes[i], align);
    if ((ret = av_image_fill_pointers(pointers, pix_fmt, h, NULL, linesizes)) < 0)
        return ret;
    buf = av_malloc(ret + align);
    if (!buf)
        return AVERROR(ENOMEM);
    if ((ret = av_image_fill_pointers(pointers, pix_fmt, h, buf, linesizes)) < 0) {
        av_free(buf);
        return ret;
    if (desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
        avpriv_set_systematic_pal2((uint32_t*)pointers[1], pix_fmt);
    return ret;


static void do_dcbz(CPUPPCState *env, target_ulong addr, int dcache_line_size,

                    uintptr_t raddr)

{

    int i;

    addr &= ~(dcache_line_size - 1);

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

        cpu_stl_data_ra(env, addr + i, 0, raddr);

    }

    if (env->reserve_addr == addr) {

        env->reserve_addr = (target_ulong)-1ULL;

    }

}


static int32_t ide_nop_int32(IDEDMA *dma, int x)

{

    return 0;

}


static int read_password(char *buf, int buf_size)

{

    int c, i;

    printf("Password: ");

    fflush(stdout);

    i = 0;

    for(;;) {

        c = getchar();

        if (c == '\n')

            break;

        if (i < (buf_size - 1))

            buf[i++] = c;

    }

    buf[i] = '\0';

    return 0;

}


long do_rt_sigreturn(CPUARMState *env)

{

    struct target_rt_sigframe *frame;

    abi_ulong frame_addr = env->xregs[31];

    if (frame_addr & 15) {

        goto badframe;

    }

    if  (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    if (target_restore_sigframe(env, frame)) {

        goto badframe;

    }

    if (do_sigaltstack(frame_addr +

            offsetof(struct target_rt_sigframe, uc.tuc_stack),

            0, get_sp_from_cpustate(env)) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->xregs[0];

 badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


tcp_sockclosed(struct tcpcb *tp)

{

	DEBUG_CALL("tcp_sockclosed");

	DEBUG_ARG("tp = %p", tp);

	switch (tp->t_state) {

	case TCPS_CLOSED:

	case TCPS_LISTEN:

	case TCPS_SYN_SENT:

		tp->t_state = TCPS_CLOSED;

		tp = tcp_close(tp);

		break;

	case TCPS_SYN_RECEIVED:

	case TCPS_ESTABLISHED:

		tp->t_state = TCPS_FIN_WAIT_1;

		break;

	case TCPS_CLOSE_WAIT:

		tp->t_state = TCPS_LAST_ACK;

		break;

	}

	if (tp)

		tcp_output(tp);

}


static void icp_pit_write(void *opaque, target_phys_addr_t offset,

                          uint64_t value, unsigned size)

{

    icp_pit_state *s = (icp_pit_state *)opaque;

    int n;

    n = offset >> 8;

    if (n > 3) {

        hw_error("sp804_write: Bad timer %d\n", n);

    }

    arm_timer_write(s->timer[n], offset & 0xff, value);

}


static int exynos4210_combiner_init(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    Exynos4210CombinerState *s = EXYNOS4210_COMBINER(dev);

    unsigned int i;

    /* Allocate general purpose input signals and connect a handler to each of

     * them */

    qdev_init_gpio_in(dev, exynos4210_combiner_handler, IIC_NIRQ);

    /* Connect SysBusDev irqs to device specific irqs */

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

        sysbus_init_irq(sbd, &s->output_irq[i]);

    }

    memory_region_init_io(&s->iomem, OBJECT(s), &exynos4210_combiner_ops, s,

                          "exynos4210-combiner", IIC_REGION_SIZE);

    sysbus_init_mmio(sbd, &s->iomem);

    return 0;

}


static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,

                                         uint32_t *sums, int n, int pred_order)

{

    int i;

    int k, cnt, part;

    uint32_t all_bits;

    part = (1 << porder);

    all_bits = 0;

    cnt = (n >> porder) - pred_order;

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

        if(i == 1) cnt = (n >> porder);

        k = find_optimal_param(sums[i], cnt);

        rc->params[i] = k;

        all_bits += rice_encode_count(sums[i], cnt, k);

    }

    all_bits += (4 * part);

    rc->porder = porder;

    return all_bits;

}


static void raw_decode(uint8_t *dst, const int8_t *src, int src_size)

{

    while (src_size--)

        *dst++ = *src++ + 128;

}


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

                                const uint8_t *src, int src_size)

{

    int h, w;

    uint8_t *Y1, *Y2, *Y3, *Y4, *U, *V;

    int ret;

    if (src_size < avctx->width * avctx->height * 9LL / 8) {

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

        return AVERROR_INVALIDDATA;

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV410P;

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

        return ret;

    Y1 = pic->data[0];

    Y2 = pic->data[0] + pic->linesize[0];

    Y3 = pic->data[0] + pic->linesize[0] * 2;

    Y4 = pic->data[0] + pic->linesize[0] * 3;

    U  = pic->data[1];

    V  = pic->data[2];

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

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

            AV_COPY32U(Y1 + w, src);

            AV_COPY32U(Y2 + w, src + 4);

            AV_COPY32U(Y3 + w, src + 8);

            AV_COPY32U(Y4 + w, src + 12);

            U[w >> 2] = src[16] + 0x80;

            V[w >> 2] = src[17] + 0x80;

            src += 18;

        }

        Y1 += pic->linesize[0] << 2;

        Y2 += pic->linesize[0] << 2;

        Y3 += pic->linesize[0] << 2;

        Y4 += pic->linesize[0] << 2;

        U  += pic->linesize[1];

        V  += pic->linesize[2];

    }

    return 0;

}


static int ff_filter_frame_framed(AVFilterLink *link, AVFilterBufferRef *frame)

{

    int (*filter_frame)(AVFilterLink *, AVFilterBufferRef *);

    AVFilterPad *src = link->srcpad;

    AVFilterPad *dst = link->dstpad;

    AVFilterBufferRef *out;

    int perms, ret;

    AVFilterCommand *cmd= link->dst->command_queue;

    int64_t pts;

    if (link->closed) {

        avfilter_unref_buffer(frame);

        return AVERROR_EOF;

    }

    if (!(filter_frame = dst->filter_frame))

        filter_frame = default_filter_frame;

    av_assert1((frame->perms & src->min_perms) == src->min_perms);

    frame->perms &= ~ src->rej_perms;

    perms = frame->perms;

    if (frame->linesize[0] < 0)

        perms |= AV_PERM_NEG_LINESIZES;

    /* prepare to copy the frame if the buffer has insufficient permissions */

    if ((dst->min_perms & perms) != dst->min_perms ||

        dst->rej_perms & perms) {

        av_log(link->dst, AV_LOG_DEBUG,

               "Copying data in avfilter (have perms %x, need %x, reject %x)\n",

               perms, link->dstpad->min_perms, link->dstpad->rej_perms);

        /* Maybe use ff_copy_buffer_ref instead? */

        switch (link->type) {

        case AVMEDIA_TYPE_VIDEO:

            out = ff_get_video_buffer(link, dst->min_perms,

                                      link->w, link->h);

            break;

        case AVMEDIA_TYPE_AUDIO:

            out = ff_get_audio_buffer(link, dst->min_perms,

                                      frame->audio->nb_samples);

            break;

        default: return AVERROR(EINVAL);

        }

        if (!out) {

            avfilter_unref_buffer(frame);

            return AVERROR(ENOMEM);

        }

        avfilter_copy_buffer_ref_props(out, frame);

        switch (link->type) {

        case AVMEDIA_TYPE_VIDEO:

            av_image_copy(out->data, out->linesize, frame->data, frame->linesize,

                          frame->format, frame->video->w, frame->video->h);

            break;

        case AVMEDIA_TYPE_AUDIO:

            av_samples_copy(out->extended_data, frame->extended_data,

                            0, 0, frame->audio->nb_samples,

                            av_get_channel_layout_nb_channels(frame->audio->channel_layout),

                            frame->format);

            break;

        default: return AVERROR(EINVAL);

        }

        avfilter_unref_buffer(frame);

    } else

        out = frame;

    while(cmd && cmd->time <= frame->pts * av_q2d(link->time_base)){

        av_log(link->dst, AV_LOG_DEBUG,

               "Processing command time:%f command:%s arg:%s\n",

               cmd->time, cmd->command, cmd->arg);

        avfilter_process_command(link->dst, cmd->command, cmd->arg, 0, 0, cmd->flags);

        ff_command_queue_pop(link->dst);

        cmd= link->dst->command_queue;

    }

    pts = out->pts;

    ret = filter_frame(link, out);

    ff_update_link_current_pts(link, pts);

    return ret;

}


void bdrv_get_backing_filename(BlockDriverState *bs,

                               char *filename, int filename_size)

{

    if (!bs->backing_hd) {

        pstrcpy(filename, filename_size, "");

    } else {

        pstrcpy(filename, filename_size, bs->backing_file);

    }

}


static uint32_t e1000e_macreg_read(e1000e_device *d, uint32_t reg)

{

    return qpci_io_readl(d->pci_dev, d->mac_regs + reg);

}


static inline void direct_ref_list_init(H264Context * const h){

    MpegEncContext * const s = &h->s;

    Picture * const ref1 = &h->ref_list[1][0];

    Picture * const cur = s->current_picture_ptr;

    int list, i, j;

    if(cur->pict_type == I_TYPE)

        cur->ref_count[0] = 0;

    if(cur->pict_type != B_TYPE)

        cur->ref_count[1] = 0;

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

        cur->ref_count[list] = h->ref_count[list];

        for(j=0; j<h->ref_count[list]; j++)

            cur->ref_poc[list][j] = h->ref_list[list][j].poc;

    }

    if(cur->pict_type != B_TYPE || h->direct_spatial_mv_pred)

        return;

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

        for(i=0; i<ref1->ref_count[list]; i++){

            const int poc = ref1->ref_poc[list][i];

            h->map_col_to_list0[list][i] = PART_NOT_AVAILABLE;

            for(j=0; j<h->ref_count[list]; j++)

                if(h->ref_list[list][j].poc == poc){

                    h->map_col_to_list0[list][i] = j;

                    break;

                }

        }

    }

}


static void encode_rgb48_10bit(AVCodecContext *avctx, const AVPicture *pic, uint8_t *dst)

{

    DPXContext *s = avctx->priv_data;

    const uint8_t *src = pic->data[0];

    int x, y;

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

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

            int value;

            if (s->big_endian) {

                value = ((AV_RB16(src + 6*x + 4) & 0xFFC0) >> 4)

                      | ((AV_RB16(src + 6*x + 2) & 0xFFC0) << 6)

                      | ((AV_RB16(src + 6*x + 0) & 0xFFC0) << 16);

            } else {

                value = ((AV_RL16(src + 6*x + 4) & 0xFFC0) >> 4)

                      | ((AV_RL16(src + 6*x + 2) & 0xFFC0) << 6)

                      | ((AV_RL16(src + 6*x + 0) & 0xFFC0) << 16);

            }

            write32(dst, value);

            dst += 4;

        }

        src += pic->linesize[0];

    }

}


static int tgv_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TgvContext *s = avctx->priv_data;

    const uint8_t *buf_end = buf + buf_size;

    int chunk_type;

    if (buf_end - buf < EA_PREAMBLE_SIZE)

        return AVERROR_INVALIDDATA;

    chunk_type = AV_RL32(&buf[0]);

    buf += EA_PREAMBLE_SIZE;

    if (chunk_type==kVGT_TAG) {

        int pal_count, i;

        if(buf_end - buf < 12) {

            av_log(avctx, AV_LOG_WARNING, "truncated header\n");

            return -1;

        }

        s->width  = AV_RL16(&buf[0]);

        s->height = AV_RL16(&buf[2]);

        if (s->avctx->width!=s->width || s->avctx->height!=s->height) {

            avcodec_set_dimensions(s->avctx, s->width, s->height);

            cond_release_buffer(&s->frame);

            cond_release_buffer(&s->last_frame);

        }

        pal_count = AV_RL16(&buf[6]);

        buf += 12;

        for(i=0; i<pal_count && i<AVPALETTE_COUNT && buf_end - buf >= 3; i++) {

            s->palette[i] = 0xFF << 24 | AV_RB24(buf);

            buf += 3;

        }

    }

    if (av_image_check_size(s->width, s->height, 0, avctx))

        return -1;

    /* shuffle */

    FFSWAP(AVFrame, s->frame, s->last_frame);

    if (!s->frame.data[0]) {

        s->frame.reference = 3;

        s->frame.buffer_hints = FF_BUFFER_HINTS_VALID;

        s->frame.linesize[0] = s->width;

        /* allocate additional 12 bytes to accommodate av_memcpy_backptr() OUTBUF_PADDED optimisation */

        s->frame.data[0] = av_malloc(s->width*s->height + 12);

        if (!s->frame.data[0])

            return AVERROR(ENOMEM);

        s->frame.data[1] = av_malloc(AVPALETTE_SIZE);

        if (!s->frame.data[1]) {

            av_freep(&s->frame.data[0]);

            return AVERROR(ENOMEM);

        }

    }

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

    if(chunk_type==kVGT_TAG) {

        s->frame.key_frame = 1;

        s->frame.pict_type = AV_PICTURE_TYPE_I;

        if (unpack(buf, buf_end, s->frame.data[0], s->avctx->width, s->avctx->height)<0) {

            av_log(avctx, AV_LOG_WARNING, "truncated intra frame\n");

            return -1;

        }

    }else{

        if (!s->last_frame.data[0]) {

            av_log(avctx, AV_LOG_WARNING, "inter frame without corresponding intra frame\n");

            return buf_size;

        }

        s->frame.key_frame = 0;

        s->frame.pict_type = AV_PICTURE_TYPE_P;

        if (tgv_decode_inter(s, buf, buf_end)<0) {

            av_log(avctx, AV_LOG_WARNING, "truncated inter frame\n");

            return -1;

        }

    }

    *data_size = sizeof(AVFrame);

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

    return buf_size;

}


static void adjust_frame_information(ChannelElement *cpe, int chans)

{

    int i, w, w2, g, ch;

    int start, maxsfb, cmaxsfb;

    for (ch = 0; ch < chans; ch++) {

        IndividualChannelStream *ics = &cpe->ch[ch].ics;

        start = 0;

        maxsfb = 0;

        cpe->ch[ch].pulse.num_pulse = 0;

        for (w = 0; w < ics->num_windows*16; w += 16) {

            for (g = 0; g < ics->num_swb; g++) {

                //apply M/S

                if (cpe->common_window && !ch && cpe->ms_mask[w + g]) {

                    for (i = 0; i < ics->swb_sizes[g]; i++) {

                        cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0;

                        cpe->ch[1].coeffs[start+i] =  cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i];

                    }

                }

                start += ics->swb_sizes[g];

            }

            for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)

                ;

            maxsfb = FFMAX(maxsfb, cmaxsfb);

        }

        ics->max_sfb = maxsfb;

        //adjust zero bands for window groups

        for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {

            for (g = 0; g < ics->max_sfb; g++) {

                i = 1;

                for (w2 = w; w2 < w + ics->group_len[w]; w2++) {

                    if (!cpe->ch[ch].zeroes[w2*16 + g]) {

                        i = 0;

                        break;

                    }

                }

                cpe->ch[ch].zeroes[w*16 + g] = i;

            }

        }

    }

    if (chans > 1 && cpe->common_window) {

        IndividualChannelStream *ics0 = &cpe->ch[0].ics;

        IndividualChannelStream *ics1 = &cpe->ch[1].ics;

        int msc = 0;

        ics0->max_sfb = FFMAX(ics0->max_sfb, ics1->max_sfb);

        ics1->max_sfb = ics0->max_sfb;

        for (w = 0; w < ics0->num_windows*16; w += 16)

            for (i = 0; i < ics0->max_sfb; i++)

                if (cpe->ms_mask[w+i])

                    msc++;

        if (msc == 0 || ics0->max_sfb == 0)

            cpe->ms_mode = 0;

        else

            cpe->ms_mode = msc < ics0->max_sfb * ics0->num_windows ? 1 : 2;

    }

}


int ff_img_read_header(AVFormatContext *s1)

{

    VideoDemuxData *s = s1->priv_data;

    int first_index, last_index;

    AVStream *st;

    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;

    s1->ctx_flags |= AVFMTCTX_NOHEADER;

    st = avformat_new_stream(s1, NULL);

    if (!st) {

        return AVERROR(ENOMEM);

    }

    if (s->pixel_format &&

        (pix_fmt = av_get_pix_fmt(s->pixel_format)) == AV_PIX_FMT_NONE) {

        av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n",

               s->pixel_format);

        return AVERROR(EINVAL);

    }

    av_strlcpy(s->path, s1->filename, sizeof(s->path));

    s->img_number = 0;

    s->img_count  = 0;

    /* find format */

    if (s1->iformat->flags & AVFMT_NOFILE)

        s->is_pipe = 0;

    else {

        s->is_pipe       = 1;

        st->need_parsing = AVSTREAM_PARSE_FULL;

    }

    if (s->ts_from_file == 2) {

#if !HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC

        av_log(s1, AV_LOG_ERROR, "POSIX.1-2008 not supported, nanosecond file timestamps unavailable\n");

        return AVERROR(ENOSYS);

#endif

        avpriv_set_pts_info(st, 64, 1, 1000000000);

    } else if (s->ts_from_file)

        avpriv_set_pts_info(st, 64, 1, 1);

    else

        avpriv_set_pts_info(st, 64, s->framerate.den, s->framerate.num);

    if (s->width && s->height) {

        st->codec->width  = s->width;

        st->codec->height = s->height;

    }

    if (!s->is_pipe) {

        if (s->pattern_type == PT_GLOB_SEQUENCE) {

        s->use_glob = is_glob(s->path);

        if (s->use_glob) {

#if HAVE_GLOB

            char *p = s->path, *q, *dup;

            int gerr;

#endif

            av_log(s1, AV_LOG_WARNING, "Pattern type 'glob_sequence' is deprecated: "

                   "use pattern_type 'glob' instead\n");

#if HAVE_GLOB

            dup = q = av_strdup(p);

            while (*q) {

                /* Do we have room for the next char and a \ insertion? */

                if ((p - s->path) >= (sizeof(s->path) - 2))

                  break;

                if (*q == '%' && strspn(q + 1, "%*?[]{}"))

                    ++q;

                else if (strspn(q, "\\*?[]{}"))

                    *p++ = '\\';

                *p++ = *q++;

            }

            *p = 0;

            av_free(dup);

            gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);

            if (gerr != 0) {

                return AVERROR(ENOENT);

            }

            first_index = 0;

            last_index = s->globstate.gl_pathc - 1;

#endif

        }

        }

        if ((s->pattern_type == PT_GLOB_SEQUENCE && !s->use_glob) || s->pattern_type == PT_SEQUENCE) {

            if (find_image_range(&first_index, &last_index, s->path,

                                 s->start_number, s->start_number_range) < 0) {

                av_log(s1, AV_LOG_ERROR,

                       "Could find no file with path '%s' and index in the range %d-%d\n",

                       s->path, s->start_number, s->start_number + s->start_number_range - 1);

                return AVERROR(ENOENT);

            }

        } else if (s->pattern_type == PT_GLOB) {

#if HAVE_GLOB

            int gerr;

            gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);

            if (gerr != 0) {

                return AVERROR(ENOENT);

            }

            first_index = 0;

            last_index = s->globstate.gl_pathc - 1;

            s->use_glob = 1;

#else

            av_log(s1, AV_LOG_ERROR,

                   "Pattern type 'glob' was selected but globbing "

                   "is not supported by this libavformat build\n");

            return AVERROR(ENOSYS);

#endif

        } else if (s->pattern_type != PT_GLOB_SEQUENCE) {

            av_log(s1, AV_LOG_ERROR,

                   "Unknown value '%d' for pattern_type option\n", s->pattern_type);

            return AVERROR(EINVAL);

        }

        s->img_first  = first_index;

        s->img_last   = last_index;

        s->img_number = first_index;

        /* compute duration */

        if (!s->ts_from_file) {

            st->start_time = 0;

            st->duration   = last_index - first_index + 1;

        }

    }

    if (s1->video_codec_id) {

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->codec->codec_id   = s1->video_codec_id;

    } else if (s1->audio_codec_id) {

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id   = s1->audio_codec_id;

    } else if (s1->iformat->raw_codec_id) {

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->codec->codec_id   = s1->iformat->raw_codec_id;

    } else {

        const char *str = strrchr(s->path, '.');

        s->split_planes       = str && !av_strcasecmp(str + 1, "y");

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        if (s1->pb) {

            int probe_buffer_size = 2048;

            uint8_t *probe_buffer = av_realloc(NULL, probe_buffer_size + AVPROBE_PADDING_SIZE);

            AVInputFormat *fmt = NULL;

            AVProbeData pd = { 0 };

            if (!probe_buffer)

                return AVERROR(ENOMEM);

            probe_buffer_size = avio_read(s1->pb, probe_buffer, probe_buffer_size);

            if (probe_buffer_size < 0) {

                av_free(probe_buffer);

                return probe_buffer_size;

            }

            memset(probe_buffer + probe_buffer_size, 0, AVPROBE_PADDING_SIZE);

            pd.buf = probe_buffer;

            pd.buf_size = probe_buffer_size;

            pd.filename = s1->filename;

            while ((fmt = av_iformat_next(fmt))) {

                if (fmt->read_header != ff_img_read_header ||

                    !fmt->read_probe ||

                    (fmt->flags & AVFMT_NOFILE) ||

                    !fmt->raw_codec_id)

                    continue;

                if (fmt->read_probe(&pd) > 0) {

                    st->codec->codec_id = fmt->raw_codec_id;

                    break;

                }

            }

            ffio_rewind_with_probe_data(s1->pb, &probe_buffer, probe_buffer_size);

        }

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

            st->codec->codec_id = ff_guess_image2_codec(s->path);

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

            st->codec->codec_id = AV_CODEC_ID_MJPEG;

        if (st->codec->codec_id == AV_CODEC_ID_ALIAS_PIX) // we cannot distingiush this from BRENDER_PIX

            st->codec->codec_id = AV_CODEC_ID_NONE;

    }

    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

        pix_fmt != AV_PIX_FMT_NONE)

        st->codec->pix_fmt = pix_fmt;

    return 0;

}


static void hpet_ram_write(void *opaque, hwaddr addr,

                           uint64_t value, unsigned size)

{

    int i;

    HPETState *s = opaque;

    uint64_t old_val, new_val, val, index;

    DPRINTF("qemu: Enter hpet_ram_writel at %" PRIx64 " = %#x\n", addr, value);

    index = addr;

    old_val = hpet_ram_read(opaque, addr, 4);

    new_val = value;

    /*address range of all TN regs*/

    if (index >= 0x100 && index <= 0x3ff) {

        uint8_t timer_id = (addr - 0x100) / 0x20;

        HPETTimer *timer = &s->timer[timer_id];

        DPRINTF("qemu: hpet_ram_writel timer_id = %#x\n", timer_id);

        if (timer_id > s->num_timers) {

            DPRINTF("qemu: timer id out of range\n");

            return;

        }

        switch ((addr - 0x100) % 0x20) {

        case HPET_TN_CFG:

            DPRINTF("qemu: hpet_ram_writel HPET_TN_CFG\n");

            if (activating_bit(old_val, new_val, HPET_TN_FSB_ENABLE)) {

                update_irq(timer, 0);

            }

            val = hpet_fixup_reg(new_val, old_val, HPET_TN_CFG_WRITE_MASK);

            timer->config = (timer->config & 0xffffffff00000000ULL) | val;

            if (new_val & HPET_TN_32BIT) {

                timer->cmp = (uint32_t)timer->cmp;

                timer->period = (uint32_t)timer->period;

            }

            if (activating_bit(old_val, new_val, HPET_TN_ENABLE)) {

                hpet_set_timer(timer);

            } else if (deactivating_bit(old_val, new_val, HPET_TN_ENABLE)) {

                hpet_del_timer(timer);

            }

            break;

        case HPET_TN_CFG + 4: // Interrupt capabilities

            DPRINTF("qemu: invalid HPET_TN_CFG+4 write\n");

            break;

        case HPET_TN_CMP: // comparator register

            DPRINTF("qemu: hpet_ram_writel HPET_TN_CMP\n");

            if (timer->config & HPET_TN_32BIT) {

                new_val = (uint32_t)new_val;

            }

            if (!timer_is_periodic(timer)

                || (timer->config & HPET_TN_SETVAL)) {

                timer->cmp = (timer->cmp & 0xffffffff00000000ULL) | new_val;

            }

            if (timer_is_periodic(timer)) {

                /*

                 * FIXME: Clamp period to reasonable min value?

                 * Clamp period to reasonable max value

                 */

                new_val &= (timer->config & HPET_TN_32BIT ? ~0u : ~0ull) >> 1;

                timer->period =

                    (timer->period & 0xffffffff00000000ULL) | new_val;

            }

            timer->config &= ~HPET_TN_SETVAL;

            if (hpet_enabled(s)) {

                hpet_set_timer(timer);

            }

            break;

        case HPET_TN_CMP + 4: // comparator register high order

            DPRINTF("qemu: hpet_ram_writel HPET_TN_CMP + 4\n");

            if (!timer_is_periodic(timer)

                || (timer->config & HPET_TN_SETVAL)) {

                timer->cmp = (timer->cmp & 0xffffffffULL) | new_val << 32;

            } else {

                /*

                 * FIXME: Clamp period to reasonable min value?

                 * Clamp period to reasonable max value

                 */

                new_val &= (timer->config & HPET_TN_32BIT ? ~0u : ~0ull) >> 1;

                timer->period =

                    (timer->period & 0xffffffffULL) | new_val << 32;

                }

                timer->config &= ~HPET_TN_SETVAL;

                if (hpet_enabled(s)) {

                    hpet_set_timer(timer);

                }

                break;

        case HPET_TN_ROUTE:

            timer->fsb = (timer->fsb & 0xffffffff00000000ULL) | new_val;

            break;

        case HPET_TN_ROUTE + 4:

            timer->fsb = (new_val << 32) | (timer->fsb & 0xffffffff);

            break;

        default:

            DPRINTF("qemu: invalid hpet_ram_writel\n");

            break;

        }

        return;

    } else {

        switch (index) {

        case HPET_ID:

            return;

        case HPET_CFG:

            val = hpet_fixup_reg(new_val, old_val, HPET_CFG_WRITE_MASK);

            s->config = (s->config & 0xffffffff00000000ULL) | val;

            if (activating_bit(old_val, new_val, HPET_CFG_ENABLE)) {

                /* Enable main counter and interrupt generation. */

                s->hpet_offset =

                    ticks_to_ns(s->hpet_counter) - qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

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

                    if ((&s->timer[i])->cmp != ~0ULL) {

                        hpet_set_timer(&s->timer[i]);

                    }

                }

            } else if (deactivating_bit(old_val, new_val, HPET_CFG_ENABLE)) {

                /* Halt main counter and disable interrupt generation. */

                s->hpet_counter = hpet_get_ticks(s);

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

                    hpet_del_timer(&s->timer[i]);

                }

            }

            /* i8254 and RTC output pins are disabled

             * when HPET is in legacy mode */

            if (activating_bit(old_val, new_val, HPET_CFG_LEGACY)) {

                qemu_set_irq(s->pit_enabled, 0);

                qemu_irq_lower(s->irqs[0]);

                qemu_irq_lower(s->irqs[RTC_ISA_IRQ]);

            } else if (deactivating_bit(old_val, new_val, HPET_CFG_LEGACY)) {

                qemu_irq_lower(s->irqs[0]);

                qemu_set_irq(s->pit_enabled, 1);

                qemu_set_irq(s->irqs[RTC_ISA_IRQ], s->rtc_irq_level);

            }

            break;

        case HPET_CFG + 4:

            DPRINTF("qemu: invalid HPET_CFG+4 write\n");

            break;

        case HPET_STATUS:

            val = new_val & s->isr;

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

                if (val & (1 << i)) {

                    update_irq(&s->timer[i], 0);

                }

            }

            break;

        case HPET_COUNTER:

            if (hpet_enabled(s)) {

                DPRINTF("qemu: Writing counter while HPET enabled!\n");

            }

            s->hpet_counter =

                (s->hpet_counter & 0xffffffff00000000ULL) | value;

            DPRINTF("qemu: HPET counter written. ctr = %#x -> %" PRIx64 "\n",

                    value, s->hpet_counter);

            break;

        case HPET_COUNTER + 4:

            if (hpet_enabled(s)) {

                DPRINTF("qemu: Writing counter while HPET enabled!\n");

            }

            s->hpet_counter =

                (s->hpet_counter & 0xffffffffULL) | (((uint64_t)value) << 32);

            DPRINTF("qemu: HPET counter + 4 written. ctr = %#x -> %" PRIx64 "\n",

                    value, s->hpet_counter);

            break;

        default:

            DPRINTF("qemu: invalid hpet_ram_writel\n");

            break;

        }

    }

}


static abi_ulong copy_elf_strings(int argc,char ** argv, void **page,

                                  abi_ulong p)

{

    char *tmp, *tmp1, *pag = NULL;

    int len, offset = 0;

    if (!p) {

        return 0;       /* bullet-proofing */

    }

    while (argc-- > 0) {

        tmp = argv[argc];

        if (!tmp) {

            fprintf(stderr, "VFS: argc is wrong");

            exit(-1);

        }

        tmp1 = tmp;

        while (*tmp++);

        len = tmp - tmp1;

        if (p < len) {  /* this shouldn't happen - 128kB */

            return 0;

        }

        while (len) {

            --p; --tmp; --len;

            if (--offset < 0) {

                offset = p % TARGET_PAGE_SIZE;

                pag = (char *)page[p/TARGET_PAGE_SIZE];

                if (!pag) {

                    pag = (char *)malloc(TARGET_PAGE_SIZE);

                    memset(pag, 0, TARGET_PAGE_SIZE);

                    page[p/TARGET_PAGE_SIZE] = pag;

                    if (!pag)

                        return 0;

                }

            }

            if (len == 0 || offset == 0) {

                *(pag + offset) = *tmp;

            }

            else {

                int bytes_to_copy = (len > offset) ? offset : len;

                tmp -= bytes_to_copy;

                p -= bytes_to_copy;

                offset -= bytes_to_copy;

                len -= bytes_to_copy;

                memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1);

            }

        }

    }

    return p;

}


static int mov_text_decode_close(AVCodecContext *avctx)

{

    MovTextContext *m = avctx->priv_data;

    mov_text_cleanup_ftab(m);

    return 0;

}


static void xhci_intr_raise(XHCIState *xhci, int v)

{

    PCIDevice *pci_dev = PCI_DEVICE(xhci);

    xhci->intr[v].erdp_low |= ERDP_EHB;

    xhci->intr[v].iman |= IMAN_IP;

    xhci->usbsts |= USBSTS_EINT;

    if (!(xhci->intr[v].iman & IMAN_IE)) {

    if (!(xhci->usbcmd & USBCMD_INTE)) {

    if (msix_enabled(pci_dev)) {

        trace_usb_xhci_irq_msix(v);

        msix_notify(pci_dev, v);

    if (msi_enabled(pci_dev)) {

        trace_usb_xhci_irq_msi(v);

        msi_notify(pci_dev, v);

    if (v == 0) {

        trace_usb_xhci_irq_intx(1);

        pci_irq_assert(pci_dev);


int qemu_chr_fe_get_msgfd(CharDriverState *s)

{

    int fd;

    return (qemu_chr_fe_get_msgfds(s, &fd, 1) >= 0) ? fd : -1;

}


void qemu_set_dfilter_ranges(const char *filter_spec)
{
    gchar **ranges = g_strsplit(filter_spec, ",", 0);
    if (ranges) {
        gchar **next = ranges;
        gchar *r = *next++;
        debug_regions = g_array_sized_new(FALSE, FALSE,
                                          sizeof(Range), g_strv_length(ranges));
        while (r) {
            char *range_op = strstr(r, "-");
            char *r2 = range_op ? range_op + 1 : NULL;
            if (!range_op) {
                range_op = strstr(r, "+");
                r2 = range_op ? range_op + 1 : NULL;
            if (!range_op) {
                range_op = strstr(r, "..");
                r2 = range_op ? range_op + 2 : NULL;
            if (range_op) {
                const char *e = NULL;
                uint64_t r1val, r2val;
                if ((qemu_strtoull(r, &e, 0, &r1val) == 0) &&
                    (qemu_strtoull(r2, NULL, 0, &r2val) == 0) &&
                    r2val > 0) {
                    struct Range range;
                    g_assert(e == range_op);
                    switch (*range_op) {
                    case '+':
                    {
                        range.begin = r1val;
                        range.end = r1val + (r2val - 1);
                        break;
                    case '-':
                    {
                        range.end = r1val;
                        range.begin = r1val - (r2val - 1);
                        break;
                    case '.':
                        range.begin = r1val;
                        range.end = r2val;
                        break;
                    default:
                        g_assert_not_reached();
                    g_array_append_val(debug_regions, range);
                } else {
                    g_error("Failed to parse range in: %s", r);
            } else {
                g_error("Bad range specifier in: %s", r);
            r = *next++;
        g_strfreev(ranges);


static void flush(AVCodecContext *avctx)

{

    WmallDecodeCtx *s    = avctx->priv_data;

    s->packet_loss       = 1;

    s->packet_done       = 0;

    s->num_saved_bits    = 0;

    s->frame_offset      = 0;

    s->next_packet_start = 0;

    s->cdlms[0][0].order = 0;

    s->frame.nb_samples  = 0;

    init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);

}


avs_decode_frame(AVCodecContext * avctx,

                 void *data, int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    const uint8_t *buf_end = avpkt->data + avpkt->size;

    int buf_size = avpkt->size;

    AvsContext *const avs = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame *const p =  &avs->picture;

    const uint8_t *table, *vect;

    uint8_t *out;

    int i, j, x, y, stride, vect_w = 3, vect_h = 3;

    AvsVideoSubType sub_type;

    AvsBlockType type;

    GetBitContext change_map;

    if (avctx->reget_buffer(avctx, p)) {

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

        return -1;

    }

    p->reference = 3;

    p->pict_type = AV_PICTURE_TYPE_P;

    p->key_frame = 0;

    out = avs->picture.data[0];

    stride = avs->picture.linesize[0];

    if (buf_end - buf < 4)

        return AVERROR_INVALIDDATA;

    sub_type = buf[0];

    type = buf[1];

    buf += 4;

    if (type == AVS_PALETTE) {

        int first, last;

        uint32_t *pal = (uint32_t *) avs->picture.data[1];

        first = AV_RL16(buf);

        last = first + AV_RL16(buf + 2);

        if (first >= 256 || last > 256 || buf_end - buf < 4 + 4 + 3 * (last - first))

            return AVERROR_INVALIDDATA;

        buf += 4;

        for (i=first; i<last; i++, buf+=3) {

            pal[i] = (buf[0] << 18) | (buf[1] << 10) | (buf[2] << 2);

            pal[i] |= 0xFF << 24 | (pal[i] >> 6) & 0x30303;

        }

        sub_type = buf[0];

        type = buf[1];

        buf += 4;

    }

    if (type != AVS_VIDEO)

        return -1;

    switch (sub_type) {

    case AVS_I_FRAME:

        p->pict_type = AV_PICTURE_TYPE_I;

        p->key_frame = 1;

    case AVS_P_FRAME_3X3:

        vect_w = 3;

        vect_h = 3;

        break;

    case AVS_P_FRAME_2X2:

        vect_w = 2;

        vect_h = 2;

        break;

    case AVS_P_FRAME_2X3:

        vect_w = 2;

        vect_h = 3;

        break;

    default:

      return -1;

    }

    if (buf_end - buf < 256 * vect_w * vect_h)

        return AVERROR_INVALIDDATA;

    table = buf + (256 * vect_w * vect_h);

    if (sub_type != AVS_I_FRAME) {

        int map_size = ((318 / vect_w + 7) / 8) * (198 / vect_h);

        if (buf_end - table < map_size)

            return AVERROR_INVALIDDATA;

        init_get_bits(&change_map, table, map_size * 8);

        table += map_size;

    }

    for (y=0; y<198; y+=vect_h) {

        for (x=0; x<318; x+=vect_w) {

            if (sub_type == AVS_I_FRAME || get_bits1(&change_map)) {

                if (buf_end - table < 1)

                    return AVERROR_INVALIDDATA;

                vect = &buf[*table++ * (vect_w * vect_h)];

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

                    out[(y + 0) * stride + x + j] = vect[(0 * vect_w) + j];

                    out[(y + 1) * stride + x + j] = vect[(1 * vect_w) + j];

                    if (vect_h == 3)

                        out[(y + 2) * stride + x + j] =

                            vect[(2 * vect_w) + j];

                }

            }

        }

        if (sub_type != AVS_I_FRAME)

            align_get_bits(&change_map);

    }

    *picture   = avs->picture;

    *data_size = sizeof(AVPicture);

    return buf_size;

}


static void uc32_cpu_realizefn(DeviceState *dev, Error **errp)
{
    UniCore32CPUClass *ucc = UNICORE32_CPU_GET_CLASS(dev);
    ucc->parent_realize(dev, errp);
}


void parse_option_size(const char *name, const char *value,

                       uint64_t *ret, Error **errp)

{

    char *postfix;

    double sizef;

    sizef = strtod(value, &postfix);

    if (sizef < 0 || sizef > UINT64_MAX) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name,

                   "a non-negative number below 2^64");

        return;

    }

    switch (*postfix) {

    case 'T':

        sizef *= 1024;

        /* fall through */

    case 'G':

        sizef *= 1024;

        /* fall through */

    case 'M':

        sizef *= 1024;

        /* fall through */

    case 'K':

    case 'k':

        sizef *= 1024;

        /* fall through */

    case 'b':

    case '\0':

        *ret = (uint64_t) sizef;

        break;

    default:

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name, "a size");

        error_append_hint(errp, "You may use k, M, G or T suffixes for "

                          "kilobytes, megabytes, gigabytes and terabytes.\n");

        return;

    }

}


static void gen_ove_cy(DisasContext *dc, TCGv cy)

{

    if (dc->tb_flags & SR_OVE) {

        gen_helper_ove(cpu_env, cy);

    }

}


static void limits_nesting(void)

{

    enum { max_nesting = 1024 }; /* see qobject/json-streamer.c */

    char buf[2 * (max_nesting + 1) + 1];

    QObject *obj;

    obj = qobject_from_json(make_nest(buf, max_nesting), NULL);

    g_assert(obj != NULL);

    qobject_decref(obj);

    obj = qobject_from_json(make_nest(buf, max_nesting + 1), NULL);

    g_assert(obj == NULL);

}


static int decode_end(AVCodecContext *avctx)

{

    H264Context *h = avctx->priv_data;

    MpegEncContext *s = &h->s;

    free_tables(h); //FIXME cleanup init stuff perhaps

    MPV_common_end(s);

//    memset(h, 0, sizeof(H264Context));

    return 0;

}


static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)

{

    int i, j;

    if (!avctx->channel_layout) {

        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "

                                      "encoder will guess the layout, but it "

                                      "might be incorrect.\n");

    }

    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {

        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");

        return -1;

    }

    /* frequency */

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

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

            if ((ff_ac3_sample_rate_tab[j] >> i) == avctx->sample_rate)

                goto found;

    }

    return -1;

 found:

    s->sample_rate        = avctx->sample_rate;

    s->bit_alloc.sr_shift = i;

    s->bit_alloc.sr_code  = j;

    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;

    s->bitstream_mode     = 0; /* complete main audio service */

    /* bitrate & frame size */

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

        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)

            break;

    }

    if (i == 19)

        return -1;

    s->bit_rate        = avctx->bit_rate;

    s->frame_size_code = i << 1;

    return 0;

}


static NvencSurface *get_free_frame(NvencContext *ctx)

{

    int i;

    for (i = 0; i < ctx->nb_surfaces; i++) {

        if (!ctx->surfaces[i].lockCount) {

            ctx->surfaces[i].lockCount = 1;

            return &ctx->surfaces[i];

        }

    }

    return NULL;

}


int ff_ccitt_unpack(AVCodecContext *avctx,

                    const uint8_t *src, int srcsize,

                    uint8_t *dst, int height, int stride,

                    enum TiffCompr compr, int opts)

{

    int j;

    GetBitContext gb;

    int *runs, *ref, *runend;

    int ret;

    int runsize= avctx->width + 2;

    runs = av_malloc(runsize * sizeof(runs[0]));

    ref  = av_malloc(runsize * sizeof(ref[0]));

    ref[0] = avctx->width;

    ref[1] = 0;

    ref[2] = 0;

    init_get_bits(&gb, src, srcsize*8);

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

        runend = runs + runsize;

        if(compr == TIFF_G4){

            ret = decode_group3_2d_line(avctx, &gb, avctx->width, runs, runend, ref);

            if(ret < 0){

                av_free(runs);

                av_free(ref);

                return -1;

            }

        }else{

            int g3d1 = (compr == TIFF_G3) && !(opts & 1);

            if(compr!=TIFF_CCITT_RLE && find_group3_syncmarker(&gb, srcsize*8) < 0)

                break;

            if(compr==TIFF_CCITT_RLE || g3d1 || get_bits1(&gb))

                ret = decode_group3_1d_line(avctx, &gb, avctx->width, runs, runend);

            else

                ret = decode_group3_2d_line(avctx, &gb, avctx->width, runs, runend, ref);

            if(compr==TIFF_CCITT_RLE)

                align_get_bits(&gb);

        }

        if(ret < 0){

            put_line(dst, stride, avctx->width, ref);

        }else{

            put_line(dst, stride, avctx->width, runs);

            FFSWAP(int*, runs, ref);

        }

        dst += stride;

    }

    av_free(runs);

    av_free(ref);

    return 0;

}


static int exif_decode_tag(void *logctx, GetByteContext *gbytes, int le,

                           int depth, AVDictionary **metadata)

{

    int ret, cur_pos;

    unsigned id, count;

    enum TiffTypes type;

    if (depth > 2) {

        return 0;

    }

    ff_tread_tag(gbytes, le, &id, &type, &count, &cur_pos);

    if (!bytestream2_tell(gbytes)) {

        bytestream2_seek(gbytes, cur_pos, SEEK_SET);

        return 0;

    }

    // read count values and add it metadata

    // store metadata or proceed with next IFD

    ret = ff_tis_ifd(id);

    if (ret) {

        ret = avpriv_exif_decode_ifd(logctx, gbytes, le, depth + 1, metadata);

    } else {

        const char *name = exif_get_tag_name(id);

        char *use_name   = (char*) name;

        if (!use_name) {

            use_name = av_malloc(7);

            if (!use_name) {

                return AVERROR(ENOMEM);

            }

            snprintf(use_name, 7, "0x%04X", id);

        }

        ret = exif_add_metadata(logctx, count, type, use_name, NULL,

                                gbytes, le, metadata);

        if (!name) {

            av_freep(&use_name);

        }

    }

    bytestream2_seek(gbytes, cur_pos, SEEK_SET);

    return ret;

}


static int pci_bridge_dev_initfn(PCIDevice *dev)

{

    PCIBridge *br = DO_UPCAST(PCIBridge, dev, dev);

    PCIBridgeDev *bridge_dev = DO_UPCAST(PCIBridgeDev, bridge, br);

    int err;

    pci_bridge_map_irq(br, NULL, pci_bridge_dev_map_irq_fn);

    err = pci_bridge_initfn(dev);

    if (err) {

        goto bridge_error;

    }

    memory_region_init(&bridge_dev->bar, "shpc-bar", shpc_bar_size(dev));

    err = shpc_init(dev, &br->sec_bus, &bridge_dev->bar, 0);

    if (err) {

        goto shpc_error;

    }

    err = slotid_cap_init(dev, 0, bridge_dev->chassis_nr, 0);

    if (err) {

        goto slotid_error;

    }

    if ((bridge_dev->flags & (1 << PCI_BRIDGE_DEV_F_MSI_REQ)) &&

        msi_supported) {

        err = msi_init(dev, 0, 1, true, true);

        if (err < 0) {

            goto msi_error;

        }

    }

    /* TODO: spec recommends using 64 bit prefetcheable BAR.

     * Check whether that works well. */

    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |

		     PCI_BASE_ADDRESS_MEM_TYPE_64, &bridge_dev->bar);

    dev->config[PCI_INTERRUPT_PIN] = 0x1;

    return 0;

msi_error:

    slotid_cap_cleanup(dev);

slotid_error:

    shpc_cleanup(dev, &bridge_dev->bar);

shpc_error:

    memory_region_destroy(&bridge_dev->bar);

bridge_error:

    return err;

}