MemTxAttrs kvm_arch_post_run(CPUState *cs, struct kvm_run *run)

{

    ARMCPU *cpu;

    uint32_t switched_level;

    if (kvm_irqchip_in_kernel()) {

        /*

         * We only need to sync timer states with user-space interrupt

         * controllers, so return early and save cycles if we don't.

         */

        return MEMTXATTRS_UNSPECIFIED;

    }

    cpu = ARM_CPU(cs);

    /* Synchronize our shadowed in-kernel device irq lines with the kvm ones */

    if (run->s.regs.device_irq_level != cpu->device_irq_level) {

        switched_level = cpu->device_irq_level ^ run->s.regs.device_irq_level;

        qemu_mutex_lock_iothread();

        if (switched_level & KVM_ARM_DEV_EL1_VTIMER) {

            qemu_set_irq(cpu->gt_timer_outputs[GTIMER_VIRT],

                         !!(run->s.regs.device_irq_level &

                            KVM_ARM_DEV_EL1_VTIMER));

            switched_level &= ~KVM_ARM_DEV_EL1_VTIMER;

        }

        if (switched_level & KVM_ARM_DEV_EL1_PTIMER) {

            qemu_set_irq(cpu->gt_timer_outputs[GTIMER_PHYS],

                         !!(run->s.regs.device_irq_level &

                            KVM_ARM_DEV_EL1_PTIMER));

            switched_level &= ~KVM_ARM_DEV_EL1_PTIMER;

        }

        /* XXX PMU IRQ is missing */

        if (switched_level) {

            qemu_log_mask(LOG_UNIMP, "%s: unhandled in-kernel device IRQ %x\n",

                          __func__, switched_level);

        }

        /* We also mark unknown levels as processed to not waste cycles */

        cpu->device_irq_level = run->s.regs.device_irq_level;

        qemu_mutex_unlock_iothread();

    }

    return MEMTXATTRS_UNSPECIFIED;

}


static int avi_write_trailer(AVFormatContext *s)

{

    AVIContext *avi = s->priv_data;

    AVIOContext *pb = s->pb;

    int res = 0;

    int i, j, n, nb_frames;

    int64_t file_size;

    if (pb->seekable) {

        if (avi->riff_id == 1) {

            ff_end_tag(pb, avi->movi_list);

            res = avi_write_idx1(s);

            ff_end_tag(pb, avi->riff_start);

        } else {

            avi_write_ix(s);

            ff_end_tag(pb, avi->movi_list);

            ff_end_tag(pb, avi->riff_start);

            file_size = avio_tell(pb);

            avio_seek(pb, avi->odml_list - 8, SEEK_SET);

            ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */

            avio_skip(pb, 16);

            for (n = nb_frames = 0; n < s->nb_streams; n++) {

                AVCodecParameters *par = s->streams[n]->codecpar;

                AVIStream *avist       = s->streams[n]->priv_data;

                if (par->codec_type == AVMEDIA_TYPE_VIDEO) {

                    if (nb_frames < avist->packet_count)

                        nb_frames = avist->packet_count;

                } else {

                    if (par->codec_id == AV_CODEC_ID_MP2 ||

                        par->codec_id == AV_CODEC_ID_MP3)

                        nb_frames += avist->packet_count;

                }

            }

            avio_wl32(pb, nb_frames);

            avio_seek(pb, file_size, SEEK_SET);

            avi_write_counters(s, avi->riff_id);

        }

    }

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

        AVIStream *avist = s->streams[i]->priv_data;

        for (j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)

            av_free(avist->indexes.cluster[j]);

        av_freep(&avist->indexes.cluster);

        avist->indexes.ents_allocated = avist->indexes.entry = 0;

    }

    return res;

}


static uint64_t omap_mpui_io_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    if (addr == OMAP_MPUI_BASE)	/* CMR */

        return 0xfe4d;

    OMAP_BAD_REG(addr);

    return 0;

}


static void nam_writeb (void *opaque, uint32_t addr, uint32_t val)

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    dolog ("U nam writeb %#x <- %#x\n", addr, val);

    s->cas = 0;

}


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

{

    S390FLICState *fs = S390_FLIC_COMMON(dev);

    uint32_t max_batch = fs->adapter_routes_max_batch;

    if (max_batch > ADAPTER_ROUTES_MAX_GSI) {

        error_setg(errp, "flic property adapter_routes_max_batch too big"

                   " (%d > %d)", max_batch, ADAPTER_ROUTES_MAX_GSI);

    }

    fs->ais_supported = true;

}


static int dxva2_get_buffer(AVCodecContext *s, AVFrame *frame, int flags)

{

    InputStream  *ist = s->opaque;

    DXVA2Context *ctx = ist->hwaccel_ctx;

    return av_hwframe_get_buffer(ctx->hw_frames_ctx, frame, 0);

}


void ff_h264_idct8_add_c(uint8_t *dst, DCTELEM *block, int stride){

    int i;

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    block[0] += 32;

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

    {

        const int a0 =  block[0+i*8] + block[4+i*8];

        const int a2 =  block[0+i*8] - block[4+i*8];

        const int a4 = (block[2+i*8]>>1) - block[6+i*8];

        const int a6 = (block[6+i*8]>>1) + block[2+i*8];

        const int b0 = a0 + a6;

        const int b2 = a2 + a4;

        const int b4 = a2 - a4;

        const int b6 = a0 - a6;

        const int a1 = -block[3+i*8] + block[5+i*8] - block[7+i*8] - (block[7+i*8]>>1);

        const int a3 =  block[1+i*8] + block[7+i*8] - block[3+i*8] - (block[3+i*8]>>1);

        const int a5 = -block[1+i*8] + block[7+i*8] + block[5+i*8] + (block[5+i*8]>>1);

        const int a7 =  block[3+i*8] + block[5+i*8] + block[1+i*8] + (block[1+i*8]>>1);

        const int b1 = (a7>>2) + a1;

        const int b3 =  a3 + (a5>>2);

        const int b5 = (a3>>2) - a5;

        const int b7 =  a7 - (a1>>2);

        block[0+i*8] = b0 + b7;

        block[7+i*8] = b0 - b7;

        block[1+i*8] = b2 + b5;

        block[6+i*8] = b2 - b5;

        block[2+i*8] = b4 + b3;

        block[5+i*8] = b4 - b3;

        block[3+i*8] = b6 + b1;

        block[4+i*8] = b6 - b1;

    }

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

    {

        const int a0 =  block[i+0*8] + block[i+4*8];

        const int a2 =  block[i+0*8] - block[i+4*8];

        const int a4 = (block[i+2*8]>>1) - block[i+6*8];

        const int a6 = (block[i+6*8]>>1) + block[i+2*8];

        const int b0 = a0 + a6;

        const int b2 = a2 + a4;

        const int b4 = a2 - a4;

        const int b6 = a0 - a6;

        const int a1 = -block[i+3*8] + block[i+5*8] - block[i+7*8] - (block[i+7*8]>>1);

        const int a3 =  block[i+1*8] + block[i+7*8] - block[i+3*8] - (block[i+3*8]>>1);

        const int a5 = -block[i+1*8] + block[i+7*8] + block[i+5*8] + (block[i+5*8]>>1);

        const int a7 =  block[i+3*8] + block[i+5*8] + block[i+1*8] + (block[i+1*8]>>1);

        const int b1 = (a7>>2) + a1;

        const int b3 =  a3 + (a5>>2);

        const int b5 = (a3>>2) - a5;

        const int b7 =  a7 - (a1>>2);

        dst[i + 0*stride] = cm[ dst[i + 0*stride] + ((b0 + b7) >> 6) ];

        dst[i + 1*stride] = cm[ dst[i + 1*stride] + ((b2 + b5) >> 6) ];

        dst[i + 2*stride] = cm[ dst[i + 2*stride] + ((b4 + b3) >> 6) ];

        dst[i + 3*stride] = cm[ dst[i + 3*stride] + ((b6 + b1) >> 6) ];

        dst[i + 4*stride] = cm[ dst[i + 4*stride] + ((b6 - b1) >> 6) ];

        dst[i + 5*stride] = cm[ dst[i + 5*stride] + ((b4 - b3) >> 6) ];

        dst[i + 6*stride] = cm[ dst[i + 6*stride] + ((b2 - b5) >> 6) ];

        dst[i + 7*stride] = cm[ dst[i + 7*stride] + ((b0 - b7) >> 6) ];

    }

}


void do_load_dcr (void)

{

    target_ulong val;

    if (unlikely(env->dcr_env == NULL)) {

        if (loglevel != 0) {

            fprintf(logfile, "No DCR environment\n");

        }

        do_raise_exception_err(EXCP_PROGRAM, EXCP_INVAL | EXCP_INVAL_INVAL);

    } else if (unlikely(ppc_dcr_read(env->dcr_env, T0, &val) != 0)) {

        if (loglevel != 0) {

            fprintf(logfile, "DCR read error %d %03x\n", (int)T0, (int)T0);

        }

        do_raise_exception_err(EXCP_PROGRAM, EXCP_INVAL | EXCP_PRIV_REG);

    } else {

        T0 = val;

    }

}


void tlb_set_page(CPUArchState *env, target_ulong vaddr,

                  target_phys_addr_t paddr, int prot,

                  int mmu_idx, target_ulong size)

{

    MemoryRegionSection *section;

    unsigned int index;

    target_ulong address;

    target_ulong code_address;

    uintptr_t addend;

    CPUTLBEntry *te;

    target_phys_addr_t iotlb;

    assert(size >= TARGET_PAGE_SIZE);

    if (size != TARGET_PAGE_SIZE) {

        tlb_add_large_page(env, vaddr, size);

    }

    section = phys_page_find(paddr >> TARGET_PAGE_BITS);

#if defined(DEBUG_TLB)

    printf("tlb_set_page: vaddr=" TARGET_FMT_lx " paddr=0x" TARGET_FMT_plx

           " prot=%x idx=%d pd=0x%08lx\n",

           vaddr, paddr, prot, mmu_idx, pd);

#endif

    address = vaddr;

    if (!(memory_region_is_ram(section->mr) ||

          memory_region_is_romd(section->mr))) {

        /* IO memory case (romd handled later) */

        address |= TLB_MMIO;

    }

    if (memory_region_is_ram(section->mr) ||

        memory_region_is_romd(section->mr)) {

        addend = (uintptr_t)memory_region_get_ram_ptr(section->mr)

        + memory_region_section_addr(section, paddr);

    } else {

        addend = 0;

    }

    code_address = address;

    iotlb = memory_region_section_get_iotlb(env, section, vaddr, paddr, prot,

                                            &address);

    index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);

    env->iotlb[mmu_idx][index] = iotlb - vaddr;

    te = &env->tlb_table[mmu_idx][index];

    te->addend = addend - vaddr;

    if (prot & PAGE_READ) {

        te->addr_read = address;

    } else {

        te->addr_read = -1;

    }

    if (prot & PAGE_EXEC) {

        te->addr_code = code_address;

    } else {

        te->addr_code = -1;

    }

    if (prot & PAGE_WRITE) {

        if ((memory_region_is_ram(section->mr) && section->readonly)

            || memory_region_is_romd(section->mr)) {

            /* Write access calls the I/O callback.  */

            te->addr_write = address | TLB_MMIO;

        } else if (memory_region_is_ram(section->mr)

                   && !cpu_physical_memory_is_dirty(

                           section->mr->ram_addr

                           + memory_region_section_addr(section, paddr))) {

            te->addr_write = address | TLB_NOTDIRTY;

        } else {

            te->addr_write = address;

        }

    } else {

        te->addr_write = -1;

    }

}


static void rtl8139_io_writeb(void *opaque, uint8_t addr, uint32_t val)

{

    RTL8139State *s = opaque;

    addr &= 0xff;

    switch (addr)

    {

        case MAC0 ... MAC0+5:

            s->phys[addr - MAC0] = val;

            break;

        case MAC0+6 ... MAC0+7:

            /* reserved */

            break;

        case MAR0 ... MAR0+7:

            s->mult[addr - MAR0] = val;

            break;

        case ChipCmd:

            rtl8139_ChipCmd_write(s, val);

            break;

        case Cfg9346:

            rtl8139_Cfg9346_write(s, val);

            break;

        case TxConfig: /* windows driver sometimes writes using byte-lenth call */

            rtl8139_TxConfig_writeb(s, val);

            break;

        case Config0:

            rtl8139_Config0_write(s, val);

            break;

        case Config1:

            rtl8139_Config1_write(s, val);

            break;

        case Config3:

            rtl8139_Config3_write(s, val);

            break;

        case Config4:

            rtl8139_Config4_write(s, val);

            break;

        case Config5:

            rtl8139_Config5_write(s, val);

            break;

        case MediaStatus:

            /* ignore */

            DPRINTF("not implemented write(b) to MediaStatus val=0x%02x\n",

                val);

            break;

        case HltClk:

            DPRINTF("HltClk write val=0x%08x\n", val);

            if (val == 'R')

            {

                s->clock_enabled = 1;

            }

            else if (val == 'H')

            {

                s->clock_enabled = 0;

            }

            break;

        case TxThresh:

            DPRINTF("C+ TxThresh write(b) val=0x%02x\n", val);

            s->TxThresh = val;

            break;

        case TxPoll:

            DPRINTF("C+ TxPoll write(b) val=0x%02x\n", val);

            if (val & (1 << 7))

            {

                DPRINTF("C+ TxPoll high priority transmission (not "

                    "implemented)\n");

                //rtl8139_cplus_transmit(s);

            }

            if (val & (1 << 6))

            {

                DPRINTF("C+ TxPoll normal priority transmission\n");

                rtl8139_cplus_transmit(s);

            }

            break;

        default:

            DPRINTF("not implemented write(b) addr=0x%x val=0x%02x\n", addr,

                val);

            break;

    }

}


static void rv40_h_weak_loop_filter(uint8_t *src, const int stride,

                                    const int filter_p1, const int filter_q1,

                                    const int alpha, const int beta,

                                    const int lim_p0q0, const int lim_q1,

                                    const int lim_p1)

{

    rv40_weak_loop_filter(src, stride, 1, filter_p1, filter_q1,

                          alpha, beta, lim_p0q0, lim_q1, lim_p1);

}


static int decode_subframe(WmallDecodeCtx *s)

{

    int offset        = s->samples_per_frame;

    int subframe_len  = s->samples_per_frame;

    int total_samples = s->samples_per_frame * s->num_channels;

    int i, j, rawpcm_tile, padding_zeroes, res;

    s->subframe_offset = get_bits_count(&s->gb);

    /* reset channel context and find the next block offset and size

        == the next block of the channel with the smallest number of

        decoded samples */

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

        if (offset > s->channel[i].decoded_samples) {

            offset = s->channel[i].decoded_samples;

            subframe_len =

                s->channel[i].subframe_len[s->channel[i].cur_subframe];

        }

    }

    /* get a list of all channels that contain the estimated block */

    s->channels_for_cur_subframe = 0;

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

        const int cur_subframe = s->channel[i].cur_subframe;

        /* subtract already processed samples */

        total_samples -= s->channel[i].decoded_samples;

        /* and count if there are multiple subframes that match our profile */

        if (offset == s->channel[i].decoded_samples &&

            subframe_len == s->channel[i].subframe_len[cur_subframe]) {

            total_samples -= s->channel[i].subframe_len[cur_subframe];

            s->channel[i].decoded_samples +=

                s->channel[i].subframe_len[cur_subframe];

            s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;

            ++s->channels_for_cur_subframe;

        }

    }

    /* check if the frame will be complete after processing the

        estimated block */

    if (!total_samples)

        s->parsed_all_subframes = 1;

    s->seekable_tile = get_bits1(&s->gb);

    if (s->seekable_tile) {

        clear_codec_buffers(s);

        s->do_arith_coding    = get_bits1(&s->gb);

        if (s->do_arith_coding) {

            avpriv_request_sample(s->avctx, "Arithmetic coding");

            return AVERROR_PATCHWELCOME;

        }

        s->do_ac_filter       = get_bits1(&s->gb);

        s->do_inter_ch_decorr = get_bits1(&s->gb);

        s->do_mclms           = get_bits1(&s->gb);

        if (s->do_ac_filter)

            decode_ac_filter(s);

        if (s->do_mclms)

            decode_mclms(s);

        if ((res = decode_cdlms(s)) < 0)

            return res;

        s->movave_scaling = get_bits(&s->gb, 3);

        s->quant_stepsize = get_bits(&s->gb, 8) + 1;

        reset_codec(s);

    } else if (!s->cdlms[0][0].order) {

        av_log(s->avctx, AV_LOG_DEBUG,

               "Waiting for seekable tile\n");

        s->frame.nb_samples = 0;

        return -1;

    }

    rawpcm_tile = get_bits1(&s->gb);

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

        s->is_channel_coded[i] = 1;

    if (!rawpcm_tile) {

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

            s->is_channel_coded[i] = get_bits1(&s->gb);

        if (s->bV3RTM) {

            // LPC

            s->do_lpc = get_bits1(&s->gb);

            if (s->do_lpc) {

                decode_lpc(s);

                avpriv_request_sample(s->avctx, "Expect wrong output since "

                                      "inverse LPC filter");

            }

        } else

            s->do_lpc = 0;

    }

    if (get_bits1(&s->gb))

        padding_zeroes = get_bits(&s->gb, 5);

    else

        padding_zeroes = 0;

    if (rawpcm_tile) {

        int bits = s->bits_per_sample - padding_zeroes;

        if (bits <= 0) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Invalid number of padding bits in raw PCM tile\n");

            return AVERROR_INVALIDDATA;

        }

        av_dlog(s->avctx, "RAWPCM %d bits per sample. "

                "total %d bits, remain=%d\n", bits,

                bits * s->num_channels * subframe_len, get_bits_count(&s->gb));

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

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

                s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);

    } else {

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

            if (s->is_channel_coded[i]) {

                decode_channel_residues(s, i, subframe_len);

                if (s->seekable_tile)

                    use_high_update_speed(s, i);

                else

                    use_normal_update_speed(s, i);

                revert_cdlms(s, i, 0, subframe_len);

            } else {

                memset(s->channel_residues[i], 0, sizeof(**s->channel_residues) * subframe_len);

            }

    }

    if (s->do_mclms)

        revert_mclms(s, subframe_len);

    if (s->do_inter_ch_decorr)

        revert_inter_ch_decorr(s, subframe_len);

    if (s->do_ac_filter)

        revert_acfilter(s, subframe_len);

    /* Dequantize */

    if (s->quant_stepsize != 1)

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

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

                s->channel_residues[i][j] *= s->quant_stepsize;

    /* Write to proper output buffer depending on bit-depth */

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

        int c = s->channel_indexes_for_cur_subframe[i];

        int subframe_len = s->channel[c].subframe_len[s->channel[c].cur_subframe];

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

            if (s->bits_per_sample == 16) {

                *s->samples_16[c]++ = (int16_t) s->channel_residues[c][j] << padding_zeroes;

            } else {

                *s->samples_32[c]++ = s->channel_residues[c][j] << padding_zeroes;

            }

        }

    }

    /* handled one subframe */

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

        int c = s->channel_indexes_for_cur_subframe[i];

        if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {

            av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");

            return AVERROR_INVALIDDATA;

        }

        ++s->channel[c].cur_subframe;

    }

    return 0;

}


static void RENAME(yuv2rgb565_1)(SwsContext *c, const int16_t *buf0,

                                 const int16_t *ubuf[2], const int16_t *bguf[2],

                                 const int16_t *abuf0, uint8_t *dest,

                                 int dstW, int uvalpha, int y)

{

    const int16_t *ubuf0 = ubuf[0], *ubuf1 = ubuf[1];

    const int16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

            "mov        %4, %%"REG_b"               \n\t"

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

            "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

            "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

            "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

            WRITERGB16(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    } else {

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

            "mov        %4, %%"REG_b"               \n\t"

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1b(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

            "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

            "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

            "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

            WRITERGB16(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    }

}


void hmp_memchar_write(Monitor *mon, const QDict *qdict)

{

    uint32_t size;

    const char *chardev = qdict_get_str(qdict, "device");

    const char *data = qdict_get_str(qdict, "data");

    Error *errp = NULL;

    size = strlen(data);

    qmp_memchar_write(chardev, size, data, false, 0, &errp);

    hmp_handle_error(mon, &errp);

}


static int do_bit_allocation(AC3DecodeContext *ctx, int flags)

{

    ac3_audio_block *ab = &ctx->audio_block;

    int i, snroffst = 0;

    if (!flags) /* bit allocation is not required */

        return 0;

    if (ab->flags & AC3_AB_SNROFFSTE) { /* check whether snroffsts are zero */

        snroffst += ab->csnroffst;

        if (ab->flags & AC3_AB_CPLINU)

            snroffst += ab->cplfsnroffst;

        for (i = 0; i < ctx->bsi.nfchans; i++)

            snroffst += ab->fsnroffst[i];

        if (ctx->bsi.flags & AC3_BSI_LFEON)

            snroffst += ab->lfefsnroffst;

        if (!snroffst) {

            memset(ab->cplbap, 0, sizeof (ab->cplbap));

            for (i = 0; i < ctx->bsi.nfchans; i++)

                memset(ab->bap[i], 0, sizeof (ab->bap[i]));

            memset(ab->lfebap, 0, sizeof (ab->lfebap));

            return 0;

        }

    }

    /* perform bit allocation */

    if ((ab->flags & AC3_AB_CPLINU) && (flags & 64))

        if (_do_bit_allocation(ctx, 5))

            return -1;

    for (i = 0; i < ctx->bsi.nfchans; i++)

        if (flags & (1 << i))

            if (_do_bit_allocation(ctx, i))

                return -1;

    if ((ctx->bsi.flags & AC3_BSI_LFEON) && (flags & 32))

        if (_do_bit_allocation(ctx, 6))

            return -1;

    return 0;

}


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

                      bool has_format, const char *format,

                      enum MirrorSyncMode sync,

                      bool has_mode, enum NewImageMode mode,

                      bool has_speed, int64_t speed,

                      bool has_on_source_error, BlockdevOnError on_source_error,

                      bool has_on_target_error, BlockdevOnError on_target_error,

                      Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    BlockDriverState *source = NULL;

    BlockDriver *drv = NULL;

    Error *local_err = NULL;

    int flags;

    int64_t size;

    int ret;

    if (!has_speed) {

        speed = 0;

    }

    if (!has_on_source_error) {

        on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_on_target_error) {

        on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!has_mode) {

        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (!bdrv_is_inserted(bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (!has_format) {

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

    }

    if (format) {

        drv = bdrv_find_format(format);

        if (!drv) {

            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

            return;

        }

    }

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

        return;

    }

    flags = bs->open_flags | BDRV_O_RDWR;

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

     * on top of. */

    if (sync == MIRROR_SYNC_MODE_TOP) {

        source = bs->backing_hd;

        if (!source) {

            sync = MIRROR_SYNC_MODE_FULL;

        }

    }

    if (sync == MIRROR_SYNC_MODE_NONE) {

        source = bs;

    }

    size = bdrv_getlength(bs);

    if (size < 0) {

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

        return;

    }

    if (mode != NEW_IMAGE_MODE_EXISTING) {

        assert(format && drv);

        if (source) {

            bdrv_img_create(target, format, source->filename,

                            source->drv->format_name, NULL,

                            size, flags, &local_err, false);

        } else {

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

                            size, flags, &local_err, false);

        }

    }

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    target_bs = NULL;

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

    if (ret < 0) {

        error_propagate(errp, local_err);

        return;

    }

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

                 block_job_cb, bs, &local_err);

    if (local_err != NULL) {

        bdrv_unref(target_bs);

        error_propagate(errp, local_err);

        return;

    }

}


static void malta_fpga_write(void *opaque, hwaddr addr,

                             uint64_t val, unsigned size)

{

    MaltaFPGAState *s = opaque;

    uint32_t saddr;

    saddr = (addr & 0xfffff);

    switch (saddr) {

    /* SWITCH Register */

    case 0x00200:

        break;

    /* JMPRS Register */

    case 0x00210:

        break;

    /* LEDBAR Register */

    case 0x00408:

        s->leds = val & 0xff;

        malta_fpga_update_display(s);

        break;

    /* ASCIIWORD Register */

    case 0x00410:

        snprintf(s->display_text, 9, "%08X", (uint32_t)val);

        malta_fpga_update_display(s);

        break;

    /* ASCIIPOS0 to ASCIIPOS7 Registers */

    case 0x00418:

    case 0x00420:

    case 0x00428:

    case 0x00430:

    case 0x00438:

    case 0x00440:

    case 0x00448:

    case 0x00450:

        s->display_text[(saddr - 0x00418) >> 3] = (char) val;

        malta_fpga_update_display(s);

        break;

    /* SOFTRES Register */

    case 0x00500:

        if (val == 0x42)

            qemu_system_reset_request ();

        break;

    /* BRKRES Register */

    case 0x00508:

        s->brk = val & 0xff;

        break;

    /* UART Registers are handled directly by the serial device */

    /* GPOUT Register */

    case 0x00a00:

        s->gpout = val & 0xff;

        break;

    /* I2COE Register */

    case 0x00b08:

        s->i2coe = val & 0x03;

        break;

    /* I2COUT Register */

    case 0x00b10:

        eeprom24c0x_write(val & 0x02, val & 0x01);

        s->i2cout = val;

        break;

    /* I2CSEL Register */

    case 0x00b18:

        s->i2csel = val & 0x01;

        break;

    default:

#if 0

        printf ("malta_fpga_write: Bad register offset 0x" TARGET_FMT_lx "\n",

                addr);

#endif

        break;

    }

}


static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd,

                                       ALSChannelData **cd, int *reverted,

                                       unsigned int offset, int c)

{

    ALSChannelData *ch = cd[c];

    unsigned int   dep = 0;

    unsigned int channels = ctx->avctx->channels;

    if (reverted[c])

        return 0;

    reverted[c] = 1;

    while (dep < channels && !ch[dep].stop_flag) {

        revert_channel_correlation(ctx, bd, cd, reverted, offset,

                                   ch[dep].master_channel);

        dep++;

    }

    if (dep == channels) {

        av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel correlation!\n");

        return AVERROR_INVALIDDATA;

    }

    bd->const_block = ctx->const_block + c;

    bd->shift_lsbs  = ctx->shift_lsbs + c;

    bd->opt_order   = ctx->opt_order + c;

    bd->store_prev_samples = ctx->store_prev_samples + c;

    bd->use_ltp     = ctx->use_ltp + c;

    bd->ltp_lag     = ctx->ltp_lag + c;

    bd->ltp_gain    = ctx->ltp_gain[c];

    bd->lpc_cof     = ctx->lpc_cof[c];

    bd->quant_cof   = ctx->quant_cof[c];

    bd->raw_samples = ctx->raw_samples[c] + offset;

    dep = 0;

    while (!ch[dep].stop_flag) {

        unsigned int smp;

        unsigned int begin = 1;

        unsigned int end   = bd->block_length - 1;

        int64_t y;

        int32_t *master = ctx->raw_samples[ch[dep].master_channel] + offset;

        if (ch[dep].time_diff_flag) {

            int t = ch[dep].time_diff_index;

            if (ch[dep].time_diff_sign) {

                t      = -t;

                begin -= t;

            } else {

                end   -= t;

            }

            for (smp = begin; smp < end; smp++) {

                y  = (1 << 6) +

                     MUL64(ch[dep].weighting[0], master[smp - 1    ]) +

                     MUL64(ch[dep].weighting[1], master[smp        ]) +

                     MUL64(ch[dep].weighting[2], master[smp + 1    ]) +

                     MUL64(ch[dep].weighting[3], master[smp - 1 + t]) +

                     MUL64(ch[dep].weighting[4], master[smp     + t]) +

                     MUL64(ch[dep].weighting[5], master[smp + 1 + t]);

                bd->raw_samples[smp] += y >> 7;

            }

        } else {

            for (smp = begin; smp < end; smp++) {

                y  = (1 << 6) +

                     MUL64(ch[dep].weighting[0], master[smp - 1]) +

                     MUL64(ch[dep].weighting[1], master[smp    ]) +

                     MUL64(ch[dep].weighting[2], master[smp + 1]);

                bd->raw_samples[smp] += y >> 7;

            }

        }

        dep++;

    }

    return 0;

}


build_hpet(GArray *table_data, GArray *linker)

{

    Acpi20Hpet *hpet;

    hpet = acpi_data_push(table_data, sizeof(*hpet));

    /* Note timer_block_id value must be kept in sync with value advertised by

     * emulated hpet

     */

    hpet->timer_block_id = cpu_to_le32(0x8086a201);

    hpet->addr.address = cpu_to_le64(HPET_BASE);

    build_header(linker, table_data,

                 (void *)hpet, "HPET", sizeof(*hpet), 1, NULL);

}


static inline void downmix_3f_1r_to_mono(float *samples)

{

    int i;

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

        samples[i] += (samples[i + 256] + samples[i + 512] + samples[i + 768]);

        samples[i + 256] = samples[i + 512] = samples[i + 768] = 0;

    }

}


static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q)

{

    const AVPixFmtDescriptor *desc;

    mfxSession session = NULL;

    int iopattern = 0;

    mfxVideoParam param = { { 0 } };

    int frame_width  = avctx->coded_width;

    int frame_height = avctx->coded_height;

    int ret;

    desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);

    if (!desc)

        return AVERROR_BUG;

    if (!q->async_fifo) {

        q->async_fifo = av_fifo_alloc((1 + q->async_depth) *

                                      (sizeof(mfxSyncPoint*) + sizeof(QSVFrame*)));

        if (!q->async_fifo)

            return AVERROR(ENOMEM);

    }

    if (avctx->pix_fmt == AV_PIX_FMT_QSV && avctx->hwaccel_context) {

        AVQSVContext *user_ctx = avctx->hwaccel_context;

        session           = user_ctx->session;

        iopattern         = user_ctx->iopattern;

        q->ext_buffers    = user_ctx->ext_buffers;

        q->nb_ext_buffers = user_ctx->nb_ext_buffers;

    }

    if (avctx->hw_frames_ctx) {

        AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

        AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;

        if (!iopattern) {

            if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)

                iopattern = MFX_IOPATTERN_OUT_OPAQUE_MEMORY;

            else if (frames_hwctx->frame_type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)

                iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;

        }

        frame_width  = frames_hwctx->surfaces[0].Info.Width;

        frame_height = frames_hwctx->surfaces[0].Info.Height;

    }

    if (!iopattern)

        iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;

    q->iopattern = iopattern;

    ret = qsv_init_session(avctx, q, session, avctx->hw_frames_ctx);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");

        return ret;

    }

    ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);

    if (ret < 0)

        return ret;

    param.mfx.CodecId      = ret;

    param.mfx.CodecProfile = avctx->profile;

    param.mfx.CodecLevel   = avctx->level;

    param.mfx.FrameInfo.BitDepthLuma   = desc->comp[0].depth;

    param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;

    param.mfx.FrameInfo.Shift          = desc->comp[0].depth > 8;

    param.mfx.FrameInfo.FourCC         = q->fourcc;

    param.mfx.FrameInfo.Width          = frame_width;

    param.mfx.FrameInfo.Height         = frame_height;

    param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;

    param.IOPattern   = q->iopattern;

    param.AsyncDepth  = q->async_depth;

    param.ExtParam    = q->ext_buffers;

    param.NumExtParam = q->nb_ext_buffers;

    ret = MFXVideoDECODE_Init(q->session, &param);

    if (ret < 0)

        return ff_qsv_print_error(avctx, ret,

                                  "Error initializing the MFX video decoder");

    q->frame_info = param.mfx.FrameInfo;

    return 0;

}


static void virtio_pci_modern_region_map(VirtIOPCIProxy *proxy,

                                         VirtIOPCIRegion *region,

                                         struct virtio_pci_cap *cap)

{

    memory_region_add_subregion(&proxy->modern_bar,

                                region->offset,

                                &region->mr);

    cap->cfg_type = region->type;

    cap->offset = cpu_to_le32(region->offset);

    cap->length = cpu_to_le32(memory_region_size(&region->mr));

    virtio_pci_add_mem_cap(proxy, cap);

}


static void mixer_reset (AC97LinkState *s)

{

    uint8_t active[LAST_INDEX];

    dolog ("mixer_reset\n");

    memset (s->mixer_data, 0, sizeof (s->mixer_data));

    memset (active, 0, sizeof (active));

    mixer_store (s, AC97_Reset                   , 0x0000); /* 6940 */

    mixer_store (s, AC97_Master_Volume_Mono_Mute , 0x8000);

    mixer_store (s, AC97_PC_BEEP_Volume_Mute     , 0x0000);

    mixer_store (s, AC97_Phone_Volume_Mute       , 0x8008);

    mixer_store (s, AC97_Mic_Volume_Mute         , 0x8008);

    mixer_store (s, AC97_CD_Volume_Mute          , 0x8808);

    mixer_store (s, AC97_Aux_Volume_Mute         , 0x8808);

    mixer_store (s, AC97_Record_Gain_Mic_Mute    , 0x8000);

    mixer_store (s, AC97_General_Purpose         , 0x0000);

    mixer_store (s, AC97_3D_Control              , 0x0000);

    mixer_store (s, AC97_Powerdown_Ctrl_Stat     , 0x000f);

    /*

     * Sigmatel 9700 (STAC9700)

     */

    mixer_store (s, AC97_Vendor_ID1              , 0x8384);

    mixer_store (s, AC97_Vendor_ID2              , 0x7600); /* 7608 */

    mixer_store (s, AC97_Extended_Audio_ID       , 0x0809);

    mixer_store (s, AC97_Extended_Audio_Ctrl_Stat, 0x0009);

    mixer_store (s, AC97_PCM_Front_DAC_Rate      , 0xbb80);

    mixer_store (s, AC97_PCM_Surround_DAC_Rate   , 0xbb80);

    mixer_store (s, AC97_PCM_LFE_DAC_Rate        , 0xbb80);

    mixer_store (s, AC97_PCM_LR_ADC_Rate         , 0xbb80);

    mixer_store (s, AC97_MIC_ADC_Rate            , 0xbb80);

    record_select (s, 0);

    set_volume (s, AC97_Master_Volume_Mute, 0x8000);

    set_volume (s, AC97_PCM_Out_Volume_Mute, 0x8808);

    set_volume (s, AC97_Line_In_Volume_Mute, 0x8808);

    reset_voices (s, active);

}


int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int count)

{

    Coroutine *co;

    DiscardCo rwco = {

        .bs = bs,

        .offset = offset,

        .count = count,

        .ret = NOT_DONE,

    };

    if (qemu_in_coroutine()) {

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

        bdrv_pdiscard_co_entry(&rwco);

    } else {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);

        qemu_coroutine_enter(co);

        while (rwco.ret == NOT_DONE) {

            aio_poll(aio_context, true);

        }

    }

    return rwco.ret;

}


void HELPER(stby_b)(CPUHPPAState *env, target_ulong addr, target_ulong val)

{

    uintptr_t ra = GETPC();

    switch (addr & 3) {

    case 3:

        cpu_stb_data_ra(env, addr, val, ra);

        break;

    case 2:

        cpu_stw_data_ra(env, addr, val, ra);

        break;

    case 1:

        /* The 3 byte store must appear atomic.  */

        if (parallel_cpus) {

            atomic_store_3(env, addr, val, 0x00ffffffu, ra);

        } else {

            cpu_stb_data_ra(env, addr, val >> 16, ra);

            cpu_stw_data_ra(env, addr + 1, val, ra);

        }

        break;

    default:

        cpu_stl_data_ra(env, addr, val, ra);

        break;

    }

}


int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar)

{

    int64_t scaled_dim;

    if (!sar.den)

        return AVERROR(EINVAL);

    if (!sar.num || sar.num == sar.den)

        return 0;

    if (sar.num < sar.den)

        scaled_dim = av_rescale_rnd(w, sar.num, sar.den, AV_ROUND_ZERO);

    else

        scaled_dim = av_rescale_rnd(h, sar.den, sar.num, AV_ROUND_ZERO);

    if (scaled_dim > 0)

        return 0;

    return AVERROR(EINVAL);

}


static void decode_gray_bitstream(HYuvContext *s, int count)

{

    int i;

    OPEN_READER(re, &s->gb);

    count /= 2;

    if (count >= (get_bits_left(&s->gb)) / (32 * 2)) {

        for (i = 0; i < count && get_bits_left(&s->gb) > 0; i++) {

            READ_2PIX(s->temp[0][2 * i], s->temp[0][2 * i + 1], 0);

        }

    } else {

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

            READ_2PIX(s->temp[0][2 * i], s->temp[0][2 * i + 1], 0);

        }

    }

    CLOSE_READER(re, &s->gb);

}


static void memory_region_destructor_alias(MemoryRegion *mr)

{

    memory_region_unref(mr->alias);

}


int ppc_hash64_handle_mmu_fault(PowerPCCPU *cpu, target_ulong eaddr,

                                int rwx, int mmu_idx)

{

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    ppc_slb_t *slb;

    hwaddr pte_offset;

    ppc_hash_pte64_t pte;

    int pp_prot, amr_prot, prot;

    uint64_t new_pte1;

    const int need_prot[] = {PAGE_READ, PAGE_WRITE, PAGE_EXEC};

    hwaddr raddr;

    assert((rwx == 0) || (rwx == 1) || (rwx == 2));

    /* 1. Handle real mode accesses */

    if (((rwx == 2) && (msr_ir == 0)) || ((rwx != 2) && (msr_dr == 0))) {

        /* Translation is off */

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

        raddr = eaddr & 0x0FFFFFFFFFFFFFFFULL;

        tlb_set_page(cs, eaddr & TARGET_PAGE_MASK, raddr & TARGET_PAGE_MASK,

                     PAGE_READ | PAGE_WRITE | PAGE_EXEC, mmu_idx,

                     TARGET_PAGE_SIZE);

        return 0;

    }

    /* 2. Translation is on, so look up the SLB */

    slb = slb_lookup(cpu, eaddr);

    if (!slb) {

        if (rwx == 2) {

            cs->exception_index = POWERPC_EXCP_ISEG;

            env->error_code = 0;

        } else {

            cs->exception_index = POWERPC_EXCP_DSEG;

            env->error_code = 0;

            env->spr[SPR_DAR] = eaddr;

        }

        return 1;

    }

    /* 3. Check for segment level no-execute violation */

    if ((rwx == 2) && (slb->vsid & SLB_VSID_N)) {

        cs->exception_index = POWERPC_EXCP_ISI;

        env->error_code = 0x10000000;

        return 1;

    }

    /* 4. Locate the PTE in the hash table */

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

    if (pte_offset == -1) {

        if (rwx == 2) {

            cs->exception_index = POWERPC_EXCP_ISI;

            env->error_code = 0x40000000;

        } else {

            cs->exception_index = POWERPC_EXCP_DSI;

            env->error_code = 0;

            env->spr[SPR_DAR] = eaddr;

            if (rwx == 1) {

                env->spr[SPR_DSISR] = 0x42000000;

            } else {

                env->spr[SPR_DSISR] = 0x40000000;

            }

        }

        return 1;

    }

    qemu_log_mask(CPU_LOG_MMU,

                "found PTE at offset %08" HWADDR_PRIx "\n", pte_offset);

    /* 5. Check access permissions */

    pp_prot = ppc_hash64_pte_prot(cpu, slb, pte);

    amr_prot = ppc_hash64_amr_prot(cpu, pte);

    prot = pp_prot & amr_prot;

    if ((need_prot[rwx] & ~prot) != 0) {

        /* Access right violation */

        qemu_log_mask(CPU_LOG_MMU, "PTE access rejected\n");

        if (rwx == 2) {

            cs->exception_index = POWERPC_EXCP_ISI;

            env->error_code = 0x08000000;

        } else {

            target_ulong dsisr = 0;

            cs->exception_index = POWERPC_EXCP_DSI;

            env->error_code = 0;

            env->spr[SPR_DAR] = eaddr;

            if (need_prot[rwx] & ~pp_prot) {

                dsisr |= 0x08000000;

            }

            if (rwx == 1) {

                dsisr |= 0x02000000;

            }

            if (need_prot[rwx] & ~amr_prot) {

                dsisr |= 0x00200000;

            }

            env->spr[SPR_DSISR] = dsisr;

        }

        return 1;

    }

    qemu_log_mask(CPU_LOG_MMU, "PTE access granted !\n");

    /* 6. Update PTE referenced and changed bits if necessary */

    new_pte1 = pte.pte1 | HPTE64_R_R; /* set referenced bit */

    if (rwx == 1) {

        new_pte1 |= HPTE64_R_C; /* set changed (dirty) bit */

    } else {

        /* Treat the page as read-only for now, so that a later write

         * will pass through this function again to set the C bit */

        prot &= ~PAGE_WRITE;

    }

    if (new_pte1 != pte.pte1) {

        ppc_hash64_store_hpte(cpu, pte_offset / HASH_PTE_SIZE_64,

                              pte.pte0, new_pte1);

    }

    /* 7. Determine the real address from the PTE */

    raddr = deposit64(pte.pte1 & HPTE64_R_RPN, 0, slb->sps->page_shift, eaddr);

    tlb_set_page(cs, eaddr & TARGET_PAGE_MASK, raddr & TARGET_PAGE_MASK,

                 prot, mmu_idx, TARGET_PAGE_SIZE);

    return 0;

}


static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                            AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    PCXContext * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    int compressed, xmin, ymin, xmax, ymax;

    unsigned int w, h, bits_per_pixel, bytes_per_line, nplanes, stride, y, x,

                 bytes_per_scanline;

    uint8_t *ptr;

    uint8_t const *bufstart = buf;

    uint8_t *scanline;

    int ret = -1;

    if (buf[0] != 0x0a || buf[1] > 5) {

        av_log(avctx, AV_LOG_ERROR, "this is not PCX encoded data\n");

        return AVERROR_INVALIDDATA;

    }

    compressed = buf[2];

    xmin = AV_RL16(buf+ 4);

    ymin = AV_RL16(buf+ 6);

    xmax = AV_RL16(buf+ 8);

    ymax = AV_RL16(buf+10);

    if (xmax < xmin || ymax < ymin) {

        av_log(avctx, AV_LOG_ERROR, "invalid image dimensions\n");

        return AVERROR_INVALIDDATA;

    }

    w = xmax - xmin + 1;

    h = ymax - ymin + 1;

    bits_per_pixel     = buf[3];

    bytes_per_line     = AV_RL16(buf+66);

    nplanes            = buf[65];

    bytes_per_scanline = nplanes * bytes_per_line;

    if (bytes_per_scanline < w * bits_per_pixel * nplanes / 8) {

        av_log(avctx, AV_LOG_ERROR, "PCX data is corrupted\n");

        return AVERROR_INVALIDDATA;

    }

    switch ((nplanes<<8) + bits_per_pixel) {

        case 0x0308:

            avctx->pix_fmt = AV_PIX_FMT_RGB24;

            break;

        case 0x0108:

        case 0x0104:

        case 0x0102:

        case 0x0101:

        case 0x0401:

        case 0x0301:

        case 0x0201:

            avctx->pix_fmt = AV_PIX_FMT_PAL8;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "invalid PCX file\n");

            return AVERROR_INVALIDDATA;

    }

    buf += 128;

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    if (av_image_check_size(w, h, 0, avctx))

        return AVERROR_INVALIDDATA;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    if ((ret = avctx->get_buffer(avctx, p)) < 0) {

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

        return ret;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

    scanline = av_malloc(bytes_per_scanline);

    if (!scanline)

        return AVERROR(ENOMEM);

    if (nplanes == 3 && bits_per_pixel == 8) {

        for (y=0; y<h; y++) {

            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);

            for (x=0; x<w; x++) {

                ptr[3*x  ] = scanline[x                    ];

                ptr[3*x+1] = scanline[x+ bytes_per_line    ];

                ptr[3*x+2] = scanline[x+(bytes_per_line<<1)];

            }

            ptr += stride;

        }

    } else if (nplanes == 1 && bits_per_pixel == 8) {

        const uint8_t *palstart = bufstart + buf_size - 769;

        for (y=0; y<h; y++, ptr+=stride) {

            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);

            memcpy(ptr, scanline, w);

        }

        if (buf != palstart) {

            av_log(avctx, AV_LOG_WARNING, "image data possibly corrupted\n");

            buf = palstart;

        }

        if (*buf++ != 12) {

            av_log(avctx, AV_LOG_ERROR, "expected palette after image data\n");

            ret = AVERROR_INVALIDDATA;

            goto end;

        }

    } else if (nplanes == 1) {   /* all packed formats, max. 16 colors */

        GetBitContext s;

        for (y=0; y<h; y++) {

            init_get_bits(&s, scanline, bytes_per_scanline<<3);

            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);

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

                ptr[x] = get_bits(&s, bits_per_pixel);

            ptr += stride;

        }

    } else {    /* planar, 4, 8 or 16 colors */

        int i;

        for (y=0; y<h; y++) {

            buf = pcx_rle_decode(buf, scanline, bytes_per_scanline, compressed);

            for (x=0; x<w; x++) {

                int m = 0x80 >> (x&7), v = 0;

                for (i=nplanes - 1; i>=0; i--) {

                    v <<= 1;

                    v  += !!(scanline[i*bytes_per_line + (x>>3)] & m);

                }

                ptr[x] = v;

            }

            ptr += stride;

        }

    }

    if (nplanes == 1 && bits_per_pixel == 8) {

        pcx_palette(&buf, (uint32_t *) p->data[1], 256);

    } else if (bits_per_pixel * nplanes == 1) {

        AV_WN32A(p->data[1]  , 0xFF000000);

        AV_WN32A(p->data[1]+4, 0xFFFFFFFF);

    } else if (bits_per_pixel < 8) {

        const uint8_t *palette = bufstart+16;

        pcx_palette(&palette, (uint32_t *) p->data[1], 16);

    }

    *picture = s->picture;

    *data_size = sizeof(AVFrame);

    ret = buf - bufstart;

end:

    av_free(scanline);

    return ret;

}


QemuOpts *qemu_opts_from_qdict(QemuOptsList *list, const QDict *qdict)

{

    QemuOpts *opts;

    opts = qemu_opts_create(list, qdict_get_try_str(qdict, "id"), 1);

    if (opts == NULL)

        return NULL;

    qdict_iter(qdict, qemu_opts_from_qdict_1, opts);

    return opts;

}


static void conditional_branch(DBDMA_channel *ch)

{

    dbdma_cmd *current = &ch->current;

    uint16_t br;

    uint16_t sel_mask, sel_value;

    uint32_t status;

    int cond;

    DBDMA_DPRINTF("conditional_branch\n");

    /* check if we must branch */

    br = le16_to_cpu(current->command) & BR_MASK;

    switch(br) {

    case BR_NEVER:  /* don't branch */

        next(ch);

        return;

    case BR_ALWAYS: /* always branch */

        branch(ch);

        return;

    }

    status = be32_to_cpu(ch->regs[DBDMA_STATUS]) & DEVSTAT;

    sel_mask = (be32_to_cpu(ch->regs[DBDMA_BRANCH_SEL]) >> 16) & 0x0f;

    sel_value = be32_to_cpu(ch->regs[DBDMA_BRANCH_SEL]) & 0x0f;

    cond = (status & sel_mask) == (sel_value & sel_mask);

    switch(br) {

    case BR_IFSET:  /* branch if condition bit is 1 */

        if (cond)

            branch(ch);

        else

            next(ch);

        return;

    case BR_IFCLR:  /* branch if condition bit is 0 */

        if (!cond)

            branch(ch);

        else

            next(ch);

        return;

    }

}


static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,

                               Jpeg2000Component *comp,

                               Jpeg2000T1Context *t1, Jpeg2000Band *band)

{

    int i, j;

    int w = cblk->coord[0][1] - cblk->coord[0][0];

    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {

        int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];

        int *src = t1->data[j];

        if (band->i_stepsize == 16384) {

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

                datap[i] = src[i] / 2;

        } else {

            // This should be VERY uncommon

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

                datap[i] = (src[i] * (int64_t)band->i_stepsize) / 32768;

        }

    }

}


static void gdb_accept(void)

{

    GDBState *s;

    struct sockaddr_in sockaddr;

    socklen_t len;

    int fd;

    for(;;) {

        len = sizeof(sockaddr);

        fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);

        if (fd < 0 && errno != EINTR) {

            perror("accept");

            return;

        } else if (fd >= 0) {

#ifndef _WIN32

            fcntl(fd, F_SETFD, FD_CLOEXEC);

#endif

            break;

        }

    }

    /* set short latency */

    socket_set_nodelay(fd);

    s = g_malloc0(sizeof(GDBState));

    s->c_cpu = first_cpu;

    s->g_cpu = first_cpu;

    s->fd = fd;

    gdb_has_xml = false;

    gdbserver_state = s;

    fcntl(fd, F_SETFL, O_NONBLOCK);

}


static int vaapi_encode_h265_init_sequence_params(AVCodecContext *avctx)

{

    VAAPIEncodeContext                 *ctx = avctx->priv_data;

    VAEncSequenceParameterBufferHEVC  *vseq = ctx->codec_sequence_params;

    VAEncPictureParameterBufferHEVC   *vpic = ctx->codec_picture_params;

    VAAPIEncodeH265Context            *priv = ctx->priv_data;

    VAAPIEncodeH265MiscSequenceParams *mseq = &priv->misc_sequence_params;

    int i;

    {

        // general_profile_space == 0.

        vseq->general_profile_idc = 1; // Main profile (ctx->codec_profile?)

        vseq->general_tier_flag = 0;

        vseq->general_level_idc = avctx->level * 3;

        vseq->intra_period = 0;

        vseq->intra_idr_period = 0;

        vseq->ip_period = 0;

        vseq->pic_width_in_luma_samples  = ctx->aligned_width;

        vseq->pic_height_in_luma_samples = ctx->aligned_height;

        vseq->seq_fields.bits.chroma_format_idc = 1; // 4:2:0.

        vseq->seq_fields.bits.separate_colour_plane_flag = 0;

        vseq->seq_fields.bits.bit_depth_luma_minus8 = 0; // 8-bit luma.

        vseq->seq_fields.bits.bit_depth_chroma_minus8 = 0; // 8-bit chroma.

        // Other misc flags all zero.

        // These have to come from the capabilities of the encoder.  We have

        // no way to query it, so just hardcode ones which worked for me...

        // CTB size from 8x8 to 32x32.

        vseq->log2_min_luma_coding_block_size_minus3 = 0;

        vseq->log2_diff_max_min_luma_coding_block_size = 2;

        // Transform size from 4x4 to 32x32.

        vseq->log2_min_transform_block_size_minus2 = 0;

        vseq->log2_diff_max_min_transform_block_size = 3;

        // Full transform hierarchy allowed (2-5).

        vseq->max_transform_hierarchy_depth_inter = 3;

        vseq->max_transform_hierarchy_depth_intra = 3;

        vseq->vui_parameters_present_flag = 0;

        vseq->bits_per_second = avctx->bit_rate;

        if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {

            vseq->vui_num_units_in_tick = avctx->framerate.num;

            vseq->vui_time_scale        = avctx->framerate.den;

        } else {

            vseq->vui_num_units_in_tick = avctx->time_base.num;

            vseq->vui_time_scale        = avctx->time_base.den;

        }

        vseq->intra_period     = ctx->p_per_i * (ctx->b_per_p + 1);

        vseq->intra_idr_period = vseq->intra_period;

        vseq->ip_period        = ctx->b_per_p + 1;

    }

    {

        vpic->decoded_curr_pic.picture_id = VA_INVALID_ID;

        vpic->decoded_curr_pic.flags      = VA_PICTURE_HEVC_INVALID;

        for (i = 0; i < FF_ARRAY_ELEMS(vpic->reference_frames); i++) {

            vpic->reference_frames[i].picture_id = VA_INVALID_ID;

            vpic->reference_frames[i].flags      = VA_PICTURE_HEVC_INVALID;

        }

        vpic->collocated_ref_pic_index = 0xff;

        vpic->last_picture = 0;

        vpic->pic_init_qp = priv->fixed_qp_idr;

        vpic->diff_cu_qp_delta_depth = 0;

        vpic->pps_cb_qp_offset = 0;

        vpic->pps_cr_qp_offset = 0;

        // tiles_enabled_flag == 0, so ignore num_tile_(rows|columns)_minus1.

        vpic->log2_parallel_merge_level_minus2 = 0;

        // No limit on size.

        vpic->ctu_max_bitsize_allowed = 0;

        vpic->num_ref_idx_l0_default_active_minus1 = 0;

        vpic->num_ref_idx_l1_default_active_minus1 = 0;

        vpic->slice_pic_parameter_set_id = 0;

        vpic->pic_fields.bits.screen_content_flag = 0;

        vpic->pic_fields.bits.enable_gpu_weighted_prediction = 0;

        // Per-CU QP changes are required for non-constant-QP modes.

        vpic->pic_fields.bits.cu_qp_delta_enabled_flag =

            ctx->va_rc_mode != VA_RC_CQP;

    }

    {

        mseq->video_parameter_set_id = 5;

        mseq->seq_parameter_set_id = 5;

        mseq->vps_max_layers_minus1 = 0;

        mseq->vps_max_sub_layers_minus1 = 0;

        mseq->vps_temporal_id_nesting_flag = 1;

        mseq->sps_max_sub_layers_minus1 = 0;

        mseq->sps_temporal_id_nesting_flag = 1;

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

            mseq->general_profile_compatibility_flag[i] =

                (i == vseq->general_profile_idc);

        }

        mseq->general_progressive_source_flag    = 1;

        mseq->general_interlaced_source_flag     = 0;

        mseq->general_non_packed_constraint_flag = 0;

        mseq->general_frame_only_constraint_flag = 1;

        mseq->general_inbld_flag = 0;

        mseq->log2_max_pic_order_cnt_lsb_minus4 = 8;

        mseq->vps_sub_layer_ordering_info_present_flag = 0;

        mseq->vps_max_dec_pic_buffering_minus1[0] = 1;

        mseq->vps_max_num_reorder_pics[0]         = ctx->b_per_p;

        mseq->vps_max_latency_increase_plus1[0]   = 0;

        mseq->sps_sub_layer_ordering_info_present_flag = 0;

        mseq->sps_max_dec_pic_buffering_minus1[0] = 1;

        mseq->sps_max_num_reorder_pics[0]         = ctx->b_per_p;

        mseq->sps_max_latency_increase_plus1[0]   = 0;

        mseq->vps_timing_info_present_flag = 1;

        mseq->vps_num_units_in_tick = avctx->time_base.num;

        mseq->vps_time_scale        = avctx->time_base.den;

        mseq->vps_poc_proportional_to_timing_flag = 1;

        mseq->vps_num_ticks_poc_diff_minus1 = 0;

        if (ctx->input_width  != ctx->aligned_width ||

            ctx->input_height != ctx->aligned_height) {

            mseq->conformance_window_flag = 1;

            mseq->conf_win_left_offset   = 0;

            mseq->conf_win_right_offset  =

                (ctx->aligned_width - ctx->input_width) / 2;

            mseq->conf_win_top_offset    = 0;

            mseq->conf_win_bottom_offset =

                (ctx->aligned_height - ctx->input_height) / 2;

        } else {

            mseq->conformance_window_flag = 0;

        }

        mseq->num_short_term_ref_pic_sets = 0;

        // STRPSs should ideally be here rather than repeated in each slice.

        mseq->vui_parameters_present_flag = 1;

        if (avctx->sample_aspect_ratio.num != 0) {

            mseq->aspect_ratio_info_present_flag = 1;

            if (avctx->sample_aspect_ratio.num ==

                avctx->sample_aspect_ratio.den) {

                mseq->aspect_ratio_idc = 1;

            } else {

                mseq->aspect_ratio_idc = 255; // Extended SAR.

                mseq->sar_width  = avctx->sample_aspect_ratio.num;

                mseq->sar_height = avctx->sample_aspect_ratio.den;

            }

        }

        if (1) {

            // Should this be conditional on some of these being set?

            mseq->video_signal_type_present_flag = 1;

            mseq->video_format = 5; // Unspecified.

            mseq->video_full_range_flag = 0;

            mseq->colour_description_present_flag = 1;

            mseq->colour_primaries = avctx->color_primaries;

            mseq->transfer_characteristics = avctx->color_trc;

            mseq->matrix_coeffs = avctx->colorspace;

        }

    }

    return 0;

}


static void rdft_calc_c(RDFTContext *s, FFTSample *data)

{

    int i, i1, i2;

    FFTComplex ev, od;

    const int n = 1 << s->nbits;

    const float k1 = 0.5;

    const float k2 = 0.5 - s->inverse;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    if (!s->inverse) {

        s->fft.fft_permute(&s->fft, (FFTComplex*)data);

        s->fft.fft_calc(&s->fft, (FFTComplex*)data);

    }

    /* i=0 is a special case because of packing, the DC term is real, so we

       are going to throw the N/2 term (also real) in with it. */

    ev.re = data[0];

    data[0] = ev.re+data[1];

    data[1] = ev.re-data[1];

    for (i = 1; i < (n>>2); i++) {

        i1 = 2*i;

        i2 = n-i1;

        /* Separate even and odd FFTs */

        ev.re =  k1*(data[i1  ]+data[i2  ]);

        od.im = -k2*(data[i1  ]-data[i2  ]);

        ev.im =  k1*(data[i1+1]-data[i2+1]);

        od.re =  k2*(data[i1+1]+data[i2+1]);

        /* Apply twiddle factors to the odd FFT and add to the even FFT */

        data[i1  ] =  ev.re + od.re*tcos[i] - od.im*tsin[i];

        data[i1+1] =  ev.im + od.im*tcos[i] + od.re*tsin[i];

        data[i2  ] =  ev.re - od.re*tcos[i] + od.im*tsin[i];

        data[i2+1] = -ev.im + od.im*tcos[i] + od.re*tsin[i];

    }

    data[2*i+1]=s->sign_convention*data[2*i+1];

    if (s->inverse) {

        data[0] *= k1;

        data[1] *= k1;

        s->fft.fft_permute(&s->fft, (FFTComplex*)data);

        s->fft.fft_calc(&s->fft, (FFTComplex*)data);

    }

}


static av_cold int g726_init(AVCodecContext * avctx)

{

    AVG726Context* c = (AVG726Context*)avctx->priv_data;

    unsigned int index= (avctx->bit_rate + avctx->sample_rate/2) / avctx->sample_rate - 2;

    if (

        (avctx->bit_rate != 16000 && avctx->bit_rate != 24000 &&

         avctx->bit_rate != 32000 && avctx->bit_rate != 40000)) {

        av_log(avctx, AV_LOG_ERROR, "G726: unsupported audio format\n");

        return -1;

    }

    if (avctx->sample_rate != 8000 && avctx->strict_std_compliance>FF_COMPLIANCE_INOFFICIAL) {

        av_log(avctx, AV_LOG_ERROR, "G726: unsupported audio format\n");

        return -1;

    }

    if(avctx->channels != 1){

        av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");

        return -1;

    }

    if(index>3){

        av_log(avctx, AV_LOG_ERROR, "Unsupported number of bits %d\n", index+2);

        return -1;

    }

    g726_reset(&c->c, index);

    c->code_size = c->c.tbls->bits;

    c->bit_buffer = 0;

    c->bits_left = 0;

    avctx->coded_frame = avcodec_alloc_frame();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    avctx->coded_frame->key_frame = 1;

    return 0;

}


unsigned long find_next_zero_bit(const unsigned long *addr, unsigned long size,

				 unsigned long offset)

{

    const unsigned long *p = addr + BITOP_WORD(offset);

    unsigned long result = offset & ~(BITS_PER_LONG-1);

    unsigned long tmp;

    if (offset >= size) {

        return size;

    }

    size -= result;

    offset %= BITS_PER_LONG;

    if (offset) {

        tmp = *(p++);

        tmp |= ~0UL >> (BITS_PER_LONG - offset);

        if (size < BITS_PER_LONG) {

            goto found_first;

        }

        if (~tmp) {

            goto found_middle;

        }

        size -= BITS_PER_LONG;

        result += BITS_PER_LONG;

    }

    while (size & ~(BITS_PER_LONG-1)) {

        if (~(tmp = *(p++))) {

            goto found_middle;

        }

        result += BITS_PER_LONG;

        size -= BITS_PER_LONG;

    }

    if (!size) {

        return result;

    }

    tmp = *p;

found_first:

    tmp |= ~0UL << size;

    if (tmp == ~0UL) {	/* Are any bits zero? */

        return result + size;	/* Nope. */

    }

found_middle:

    return result + ffz(tmp);

}


void visit_end_implicit_struct(Visitor *v, Error **errp)

{

    assert(!error_is_set(errp));

    if (v->end_implicit_struct) {

        v->end_implicit_struct(v, errp);

    }

}


static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)

{

    int ret;

    assert(client->optlen);

    if (nbd_drop(client->ioc, client->optlen, errp) < 0) {

        return -EIO;

    }

    ret = nbd_negotiate_send_rep_err(client, NBD_REP_ERR_INVALID, errp,

                                     "option '%s' should have zero length",

                                     nbd_opt_lookup(client->opt));

    if (fatal && !ret) {

        error_setg(errp, "option '%s' should have zero length",

                   nbd_opt_lookup(client->opt));

        return -EINVAL;

    }

    return ret;

}


static int kvmppc_read_host_property(const char *node_path, const char *prop,

                                     void *val, size_t len)

{

    char *path;

    FILE *f;

    int ret;

    int pathlen;

    pathlen = snprintf(NULL, 0, "%s/%s/%s", PROC_DEVTREE_PATH, node_path, prop)

              + 1;

    path = qemu_malloc(pathlen);

    if (path == NULL) {

        ret = -ENOMEM;

        goto out;

    }

    snprintf(path, pathlen, "%s/%s/%s", PROC_DEVTREE_PATH, node_path, prop);

    f = fopen(path, "rb");

    if (f == NULL) {

        ret = errno;

        goto free;

    }

    len = fread(val, len, 1, f);

    if (len != 1) {

        ret = ferror(f);

        goto close;

    }

close:

    fclose(f);

free:

    free(path);

out:

    return ret;

}


static void tcg_out_qemu_ld(TCGContext *s, TCGReg data, TCGReg addr,

                            TCGMemOpIdx oi, bool is_64)

{

    TCGMemOp memop = get_memop(oi);

#ifdef CONFIG_SOFTMMU

    unsigned memi = get_mmuidx(oi);

    TCGReg addrz, param;

    tcg_insn_unit *func;

    tcg_insn_unit *label_ptr;

    addrz = tcg_out_tlb_load(s, addr, memi, memop,

                             offsetof(CPUTLBEntry, addr_read));

    /* The fast path is exactly one insn.  Thus we can perform the

       entire TLB Hit in the (annulled) delay slot of the branch

       over the TLB Miss case.  */

    /* beq,a,pt %[xi]cc, label0 */

    label_ptr = s->code_ptr;

    tcg_out_bpcc0(s, COND_E, BPCC_A | BPCC_PT

                  | (TARGET_LONG_BITS == 64 ? BPCC_XCC : BPCC_ICC), 0);

    /* delay slot */

    tcg_out_ldst_rr(s, data, addrz, TCG_REG_O1,

                    qemu_ld_opc[memop & (MO_BSWAP | MO_SSIZE)]);

    /* TLB Miss.  */

    param = TCG_REG_O1;

    if (!SPARC64 && TARGET_LONG_BITS == 64) {

        /* Skip the high-part; we'll perform the extract in the trampoline.  */

        param++;

    }

    tcg_out_mov(s, TCG_TYPE_REG, param++, addr);

    /* We use the helpers to extend SB and SW data, leaving the case

       of SL needing explicit extending below.  */

    if ((memop & MO_SSIZE) == MO_SL) {

        func = qemu_ld_trampoline[memop & (MO_BSWAP | MO_SIZE)];

    } else {

        func = qemu_ld_trampoline[memop & (MO_BSWAP | MO_SSIZE)];

    }

    tcg_debug_assert(func != NULL);

    tcg_out_call_nodelay(s, func);

    /* delay slot */

    tcg_out_movi(s, TCG_TYPE_I32, param, oi);

    /* Recall that all of the helpers return 64-bit results.

       Which complicates things for sparcv8plus.  */

    if (SPARC64) {

        /* We let the helper sign-extend SB and SW, but leave SL for here.  */

        if (is_64 && (memop & MO_SSIZE) == MO_SL) {

            tcg_out_arithi(s, data, TCG_REG_O0, 0, SHIFT_SRA);

        } else {

            tcg_out_mov(s, TCG_TYPE_REG, data, TCG_REG_O0);

        }

    } else {

        if ((memop & MO_SIZE) == MO_64) {

            tcg_out_arithi(s, TCG_REG_O0, TCG_REG_O0, 32, SHIFT_SLLX);

            tcg_out_arithi(s, TCG_REG_O1, TCG_REG_O1, 0, SHIFT_SRL);

            tcg_out_arith(s, data, TCG_REG_O0, TCG_REG_O1, ARITH_OR);

        } else if (is_64) {

            /* Re-extend from 32-bit rather than reassembling when we

               know the high register must be an extension.  */

            tcg_out_arithi(s, data, TCG_REG_O1, 0,

                           memop & MO_SIGN ? SHIFT_SRA : SHIFT_SRL);

        } else {

            tcg_out_mov(s, TCG_TYPE_I32, data, TCG_REG_O1);

        }

    }

    *label_ptr |= INSN_OFF19(tcg_ptr_byte_diff(s->code_ptr, label_ptr));

#else

    if (SPARC64 && TARGET_LONG_BITS == 32) {

        tcg_out_arithi(s, TCG_REG_T1, addr, 0, SHIFT_SRL);

        addr = TCG_REG_T1;

    }

    tcg_out_ldst_rr(s, data, addr,

                    (guest_base ? TCG_GUEST_BASE_REG : TCG_REG_G0),

                    qemu_ld_opc[memop & (MO_BSWAP | MO_SSIZE)]);

#endif /* CONFIG_SOFTMMU */

}


opts_visitor_cleanup(OptsVisitor *ov)

{

    if (ov->unprocessed_opts != NULL) {

        g_hash_table_destroy(ov->unprocessed_opts);

    }

    g_free(ov->fake_id_opt);

    memset(ov, '\0', sizeof *ov);

}


static int usb_host_open(USBHostDevice *s, libusb_device *dev)

{

    USBDevice *udev = USB_DEVICE(s);

    int bus_num = libusb_get_bus_number(dev);

    int addr    = libusb_get_device_address(dev);

    int rc;

    trace_usb_host_open_started(bus_num, addr);

    if (s->dh != NULL) {

        goto fail;

    }

    rc = libusb_open(dev, &s->dh);

    if (rc != 0) {

        goto fail;

    }

    s->dev     = dev;

    s->bus_num = bus_num;

    s->addr    = addr;

    usb_host_detach_kernel(s);

    libusb_get_device_descriptor(dev, &s->ddesc);

    usb_host_get_port(s->dev, s->port, sizeof(s->port));

    usb_ep_init(udev);

    usb_host_ep_update(s);

    udev->speed     = speed_map[libusb_get_device_speed(dev)];

    usb_host_speed_compat(s);

    if (s->ddesc.iProduct) {

        libusb_get_string_descriptor_ascii(s->dh, s->ddesc.iProduct,

                                           (unsigned char *)udev->product_desc,

                                           sizeof(udev->product_desc));

    } else {

        snprintf(udev->product_desc, sizeof(udev->product_desc),

                 "host:%d.%d", bus_num, addr);

    }

    rc = usb_device_attach(udev);

    if (rc) {

        goto fail;

    }

    trace_usb_host_open_success(bus_num, addr);

    return 0;

fail:

    trace_usb_host_open_failure(bus_num, addr);

    if (s->dh != NULL) {

        libusb_close(s->dh);

        s->dh = NULL;

        s->dev = NULL;

    }

    return -1;

}


int64_t xbzrle_cache_resize(int64_t new_size, Error **errp)

{

    PageCache *new_cache;

    int64_t ret;

    /* Check for truncation */

    if (new_size != (size_t)new_size) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",

                   "exceeding address space");

        return -1;

    }

    /* Cache should not be larger than guest ram size */

    if (new_size > ram_bytes_total()) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",

                   "exceeds guest ram size");

        return -1;

    }

    XBZRLE_cache_lock();

    if (XBZRLE.cache != NULL) {

        if (pow2floor(new_size) == migrate_xbzrle_cache_size()) {

            goto out_new_size;

        }

        new_cache = cache_init(new_size, TARGET_PAGE_SIZE, errp);

        if (!new_cache) {

            ret = -1;

            goto out;

        }

        cache_fini(XBZRLE.cache);

        XBZRLE.cache = new_cache;

    }

out_new_size:

    ret = pow2floor(new_size);

out:

    XBZRLE_cache_unlock();

    return ret;

}


static void setup_rt_frame(int sig, struct target_sigaction *ka,

                           target_siginfo_t *info,

                           target_sigset_t *set, CPUAlphaState *env)

{

    abi_ulong frame_addr, r26;

    struct target_rt_sigframe *frame;

    int i, err = 0;

    frame_addr = get_sigframe(ka, env, sizeof(*frame));

    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {

        goto give_sigsegv;

    }

    err |= copy_siginfo_to_user(&frame->info, info);

    __put_user(0, &frame->uc.tuc_flags);

    __put_user(0, &frame->uc.tuc_link);

    __put_user(set->sig[0], &frame->uc.tuc_osf_sigmask);

    __put_user(target_sigaltstack_used.ss_sp,

               &frame->uc.tuc_stack.ss_sp);

    __put_user(sas_ss_flags(env->ir[IR_SP]),

               &frame->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size,

               &frame->uc.tuc_stack.ss_size);

    err |= setup_sigcontext(&frame->uc.tuc_mcontext, env, frame_addr, set);

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

        __put_user(set->sig[i], &frame->uc.tuc_sigmask.sig[i]);

    }

    if (ka->sa_restorer) {

        r26 = ka->sa_restorer;

    } else {

        __put_user(INSN_MOV_R30_R16, &frame->retcode[0]);

        __put_user(INSN_LDI_R0 + TARGET_NR_rt_sigreturn,

                   &frame->retcode[1]);

        __put_user(INSN_CALLSYS, &frame->retcode[2]);

        /* imb(); */

        r26 = frame_addr;

    }

    if (err) {

    give_sigsegv:

       if (sig == TARGET_SIGSEGV) {

            ka->_sa_handler = TARGET_SIG_DFL;

        }

        force_sig(TARGET_SIGSEGV);

    }

    env->ir[IR_RA] = r26;

    env->ir[IR_PV] = env->pc = ka->_sa_handler;

    env->ir[IR_A0] = sig;

    env->ir[IR_A1] = frame_addr + offsetof(struct target_rt_sigframe, info);

    env->ir[IR_A2] = frame_addr + offsetof(struct target_rt_sigframe, uc);

    env->ir[IR_SP] = frame_addr;

}


static void imx_gpt_reset(DeviceState *dev)

{

    IMXGPTState *s = IMX_GPT(dev);

    /* stop timer */

    ptimer_stop(s->timer);

    /*

     * Soft reset doesn't touch some bits; hard reset clears them

     */

    s->cr &= ~(GPT_CR_EN|GPT_CR_ENMOD|GPT_CR_STOPEN|GPT_CR_DOZEN|

               GPT_CR_WAITEN|GPT_CR_DBGEN);

    s->sr = 0;

    s->pr = 0;

    s->ir = 0;

    s->cnt = 0;

    s->ocr1 = TIMER_MAX;

    s->ocr2 = TIMER_MAX;

    s->ocr3 = TIMER_MAX;

    s->icr1 = 0;

    s->icr2 = 0;

    s->next_timeout = TIMER_MAX;

    s->next_int = 0;

    /* compute new freq */

    imx_gpt_set_freq(s);

    /* reset the limit to TIMER_MAX */

    ptimer_set_limit(s->timer, TIMER_MAX, 1);

    /* if the timer is still enabled, restart it */

    if (s->freq && (s->cr & GPT_CR_EN)) {

        ptimer_run(s->timer, 1);

    }

}


static int dynticks_start_timer(struct qemu_alarm_timer *t)

{

    struct sigevent ev;

    timer_t host_timer;

    struct sigaction act;

    sigfillset(&act.sa_mask);

    act.sa_flags = 0;

    act.sa_handler = host_alarm_handler;

    sigaction(SIGALRM, &act, NULL);

    ev.sigev_value.sival_int = 0;

    ev.sigev_notify = SIGEV_SIGNAL;

    ev.sigev_signo = SIGALRM;

    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {

        perror("timer_create");

        /* disable dynticks */

        fprintf(stderr, "Dynamic Ticks disabled\n");

        return -1;

    }

    t->priv = (void *)(long)host_timer;

    return 0;

}


static void s390_pci_generate_event(uint8_t cc, uint16_t pec, uint32_t fh,

                                    uint32_t fid, uint64_t faddr, uint32_t e)

{

    SeiContainer *sei_cont = g_malloc0(sizeof(SeiContainer));

    S390pciState *s = S390_PCI_HOST_BRIDGE(

        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));

    if (!s) {

        return;

    }

    sei_cont->fh = fh;

    sei_cont->fid = fid;

    sei_cont->cc = cc;

    sei_cont->pec = pec;

    sei_cont->faddr = faddr;

    sei_cont->e = e;

    QTAILQ_INSERT_TAIL(&s->pending_sei, sei_cont, link);

    css_generate_css_crws(0);

}


void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask,

                CPSRWriteType write_type)

{

    uint32_t changed_daif;

    if (mask & CPSR_NZCV) {

        env->ZF = (~val) & CPSR_Z;

        env->NF = val;

        env->CF = (val >> 29) & 1;

        env->VF = (val << 3) & 0x80000000;

    }

    if (mask & CPSR_Q)

        env->QF = ((val & CPSR_Q) != 0);

    if (mask & CPSR_T)

        env->thumb = ((val & CPSR_T) != 0);

    if (mask & CPSR_IT_0_1) {

        env->condexec_bits &= ~3;

        env->condexec_bits |= (val >> 25) & 3;

    }

    if (mask & CPSR_IT_2_7) {

        env->condexec_bits &= 3;

        env->condexec_bits |= (val >> 8) & 0xfc;

    }

    if (mask & CPSR_GE) {

        env->GE = (val >> 16) & 0xf;

    }

    /* In a V7 implementation that includes the security extensions but does

     * not include Virtualization Extensions the SCR.FW and SCR.AW bits control

     * whether non-secure software is allowed to change the CPSR_F and CPSR_A

     * bits respectively.

     *

     * In a V8 implementation, it is permitted for privileged software to

     * change the CPSR A/F bits regardless of the SCR.AW/FW bits.

     */

    if (write_type != CPSRWriteRaw && !arm_feature(env, ARM_FEATURE_V8) &&

        arm_feature(env, ARM_FEATURE_EL3) &&

        !arm_feature(env, ARM_FEATURE_EL2) &&

        !arm_is_secure(env)) {

        changed_daif = (env->daif ^ val) & mask;

        if (changed_daif & CPSR_A) {

            /* Check to see if we are allowed to change the masking of async

             * abort exceptions from a non-secure state.

             */

            if (!(env->cp15.scr_el3 & SCR_AW)) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Ignoring attempt to switch CPSR_A flag from "

                              "non-secure world with SCR.AW bit clear\n");

                mask &= ~CPSR_A;

            }

        }

        if (changed_daif & CPSR_F) {

            /* Check to see if we are allowed to change the masking of FIQ

             * exceptions from a non-secure state.

             */

            if (!(env->cp15.scr_el3 & SCR_FW)) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Ignoring attempt to switch CPSR_F flag from "

                              "non-secure world with SCR.FW bit clear\n");

                mask &= ~CPSR_F;

            }

            /* Check whether non-maskable FIQ (NMFI) support is enabled.

             * If this bit is set software is not allowed to mask

             * FIQs, but is allowed to set CPSR_F to 0.

             */

            if ((A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_NMFI) &&

                (val & CPSR_F)) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "Ignoring attempt to enable CPSR_F flag "

                              "(non-maskable FIQ [NMFI] support enabled)\n");

                mask &= ~CPSR_F;

            }

        }

    }

    env->daif &= ~(CPSR_AIF & mask);

    env->daif |= val & CPSR_AIF & mask;

    if (write_type != CPSRWriteRaw &&

        (env->uncached_cpsr & CPSR_M) != CPSR_USER &&

        ((env->uncached_cpsr ^ val) & mask & CPSR_M)) {

        if (bad_mode_switch(env, val & CPSR_M)) {

            /* Attempt to switch to an invalid mode: this is UNPREDICTABLE.

             * We choose to ignore the attempt and leave the CPSR M field

             * untouched.

             */

            mask &= ~CPSR_M;

        } else {

            switch_mode(env, val & CPSR_M);

        }

    }

    mask &= ~CACHED_CPSR_BITS;

    env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);

}


static void vfio_probe_nvidia_bar0_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIOConfigMirrorQuirk *mirror;

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||

        !vfio_is_vga(vdev) || nr != 0) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    mirror = quirk->data = g_malloc0(sizeof(*mirror));

    mirror->mem = quirk->mem = g_malloc0(sizeof(MemoryRegion));

    quirk->nr_mem = 1;

    mirror->vdev = vdev;

    mirror->offset = 0x88000;

    mirror->bar = nr;

    memory_region_init_io(mirror->mem, OBJECT(vdev),

                          &vfio_nvidia_mirror_quirk, mirror,

                          "vfio-nvidia-bar0-88000-mirror-quirk",

                          PCIE_CONFIG_SPACE_SIZE);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        mirror->offset, mirror->mem, 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    /* The 0x1800 offset mirror only seems to get used by legacy VGA */

    if (vdev->has_vga) {

        quirk = g_malloc0(sizeof(*quirk));

        mirror = quirk->data = g_malloc0(sizeof(*mirror));

        mirror->mem = quirk->mem = g_malloc0(sizeof(MemoryRegion));

        quirk->nr_mem = 1;

        mirror->vdev = vdev;

        mirror->offset = 0x1800;

        mirror->bar = nr;

        memory_region_init_io(mirror->mem, OBJECT(vdev),

                              &vfio_nvidia_mirror_quirk, mirror,

                              "vfio-nvidia-bar0-1800-mirror-quirk",

                              PCI_CONFIG_SPACE_SIZE);

        memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                            mirror->offset, mirror->mem, 1);

        QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    }

    trace_vfio_quirk_nvidia_bar0_probe(vdev->vbasedev.name);

}


static inline void gen_op_arith_compute_ov(DisasContext *ctx, TCGv arg0,

                                           TCGv arg1, TCGv arg2, int sub)

{

    TCGv t0 = tcg_temp_new();

    tcg_gen_xor_tl(cpu_ov, arg0, arg1);

    tcg_gen_xor_tl(t0, arg1, arg2);

    if (sub) {

        tcg_gen_and_tl(cpu_ov, cpu_ov, t0);

    } else {

        tcg_gen_andc_tl(cpu_ov, cpu_ov, t0);

    }

    tcg_temp_free(t0);

    if (NARROW_MODE(ctx)) {

        tcg_gen_ext32s_tl(cpu_ov, cpu_ov);

    }

    tcg_gen_shri_tl(cpu_ov, cpu_ov, TARGET_LONG_BITS - 1);

    tcg_gen_or_tl(cpu_so, cpu_so, cpu_ov);

}


static int decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             uint8_t *buf, int buf_size)

{

    H264Context *h = avctx->priv_data;

    MpegEncContext *s = &h->s;

    AVFrame *pict = data;

    int buf_index;

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

   /* no supplementary picture */

    if (buf_size == 0) {

        return 0;

    }

    if(s->flags&CODEC_FLAG_TRUNCATED){

        int next= find_frame_end(h, buf, buf_size);

        if( ff_combine_frame(&s->parse_context, next, &buf, &buf_size) < 0 )

            return buf_size;

//printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);

    }

    if(h->is_avc && !h->got_avcC) {

        int i, cnt, nalsize;

        unsigned char *p = avctx->extradata;

        if(avctx->extradata_size < 7) {

            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");

            return -1;

        }

        if(*p != 1) {

            av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);

            return -1;

        }

        /* sps and pps in the avcC always have length coded with 2 bytes,

           so put a fake nal_length_size = 2 while parsing them */

        h->nal_length_size = 2;

        // Decode sps from avcC

        cnt = *(p+5) & 0x1f; // Number of sps

        p += 6;

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

            nalsize = BE_16(p) + 2;

            if(decode_nal_units(h, p, nalsize) < 0) {

                av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Decode pps from avcC

        cnt = *(p++); // Number of pps

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

            nalsize = BE_16(p) + 2;

            if(decode_nal_units(h, p, nalsize)  != nalsize) {

                av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Now store right nal length size, that will be use to parse all other nals

        h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;

        // Do not reparse avcC

        h->got_avcC = 1;

    }

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

        if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)

            return -1;

    }

    buf_index=decode_nal_units(h, buf, buf_size);

    if(buf_index < 0)

        return -1;

    //FIXME do something with unavailable reference frames

//    if(ret==FRAME_SKIPPED) return get_consumed_bytes(s, buf_index, buf_size);

    if(!s->current_picture_ptr){

        av_log(h->s.avctx, AV_LOG_DEBUG, "error, NO frame\n");

        return -1;

    }

    {

        Picture *out = s->current_picture_ptr;

#if 0 //decode order

        *data_size = sizeof(AVFrame);

#else

        /* Sort B-frames into display order */

        Picture *cur = s->current_picture_ptr;

        Picture *prev = h->delayed_output_pic;

        int out_idx = 0;

        int pics = 0;

        int out_of_order;

        int cross_idr = 0;

        int dropped_frame = 0;

        int i;

        if(h->sps.bitstream_restriction_flag

           && s->avctx->has_b_frames < h->sps.num_reorder_frames){

            s->avctx->has_b_frames = h->sps.num_reorder_frames;

            s->low_delay = 0;

        }

        while(h->delayed_pic[pics]) pics++;

        h->delayed_pic[pics++] = cur;

        if(cur->reference == 0)

            cur->reference = 1;

        for(i=0; h->delayed_pic[i]; i++)

            if(h->delayed_pic[i]->key_frame || h->delayed_pic[i]->poc==0)

                cross_idr = 1;

        out = h->delayed_pic[0];

        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame; i++)

            if(h->delayed_pic[i]->poc < out->poc){

                out = h->delayed_pic[i];

                out_idx = i;

            }

        out_of_order = !cross_idr && prev && out->poc < prev->poc;

        if(prev && pics <= s->avctx->has_b_frames)

            out = prev;

        else if((out_of_order && pics-1 == s->avctx->has_b_frames)

           || (s->low_delay &&

            ((!cross_idr && prev && out->poc > prev->poc + 2)

             || cur->pict_type == B_TYPE)))

        {

            s->low_delay = 0;

            s->avctx->has_b_frames++;

            out = prev;

        }

        else if(out_of_order)

            out = prev;

        if(out_of_order || pics > s->avctx->has_b_frames){

            dropped_frame = (out != h->delayed_pic[out_idx]);

            for(i=out_idx; h->delayed_pic[i]; i++)

                h->delayed_pic[i] = h->delayed_pic[i+1];

        }

        if(prev == out && !dropped_frame)

            *data_size = 0;

        else

            *data_size = sizeof(AVFrame);

        if(prev && prev != out && prev->reference == 1)

            prev->reference = 0;

        h->delayed_output_pic = out;

#endif

        *pict= *(AVFrame*)out;

    }

    assert(pict->data[0]);

    ff_print_debug_info(s, pict);

//printf("out %d\n", (int)pict->data[0]);

#if 0 //?

    /* Return the Picture timestamp as the frame number */

    /* we substract 1 because it is added on utils.c    */

    avctx->frame_number = s->picture_number - 1;

#endif

    return get_consumed_bytes(s, buf_index, buf_size);

}


static void cpu_common_reset(CPUState *cpu)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    if (qemu_loglevel_mask(CPU_LOG_RESET)) {

        qemu_log("CPU Reset (CPU %d)\n", cpu->cpu_index);

        log_cpu_state(cpu, cc->reset_dump_flags);

    }

    cpu->interrupt_request = 0;

    cpu->halted = 0;

    cpu->mem_io_pc = 0;

    cpu->mem_io_vaddr = 0;

    cpu->icount_extra = 0;

    cpu->icount_decr.u32 = 0;

    cpu->can_do_io = 1;

    cpu->exception_index = -1;

    cpu->crash_occurred = false;

    if (tcg_enabled()) {

        cpu_tb_jmp_cache_clear(cpu);

#ifdef CONFIG_SOFTMMU

        tlb_flush(cpu, 0);

#endif

    }

}


int qemu_opts_foreach(QemuOptsList *list, qemu_opts_loopfunc func, void *opaque,

                      int abort_on_failure)

{

    QemuOpts *opts;

    int rc = 0;

    TAILQ_FOREACH(opts, &list->head, next) {

        rc = func(opts, opaque);

        if (abort_on_failure  &&  rc != 0)

            break;

    }

    return rc;

}


static void subpage_write(void *opaque, target_phys_addr_t addr,

                          uint64_t value, unsigned len)

{

    subpage_t *mmio = opaque;

    unsigned int idx = SUBPAGE_IDX(addr);

    MemoryRegionSection *section;

#if defined(DEBUG_SUBPAGE)

    printf("%s: subpage %p len %d addr " TARGET_FMT_plx

           " idx %d value %"PRIx64"\n",

           __func__, mmio, len, addr, idx, value);

#endif

    section = &phys_sections[mmio->sub_section[idx]];

    addr += mmio->base;

    addr -= section->offset_within_address_space;

    addr += section->offset_within_region;

    io_mem_write(section->mr, addr, value, len);

}


static int nvenc_find_free_reg_resource(AVCodecContext *avctx)

{

    NvencContext *ctx = avctx->priv_data;

    NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;

    NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;

    int i;

    if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {

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

            if (!ctx->registered_frames[i].mapped) {

                if (ctx->registered_frames[i].regptr) {

                    p_nvenc->nvEncUnregisterResource(ctx->nvencoder,

                                                ctx->registered_frames[i].regptr);

                    ctx->registered_frames[i].regptr = NULL;

                }

                return i;

            }

        }

    } else {

        return ctx->nb_registered_frames++;

    }

    av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");

    return AVERROR(ENOMEM);

}


void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)

{

    unsigned int i;

    /* Discard jump cache entries for any tb which might potentially

       overlap the flushed page.  */

    i = tb_jmp_cache_hash_page(addr - TARGET_PAGE_SIZE);

    memset(&cpu->tb_jmp_cache[i], 0,

           TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *));

    i = tb_jmp_cache_hash_page(addr);

    memset(&cpu->tb_jmp_cache[i], 0,

           TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *));

}


DeviceState *bdrv_get_attached(BlockDriverState *bs)

{

    return bs->peer;

}


static void qapi_dealloc_push(QapiDeallocVisitor *qov, void *value)

{

    StackEntry *e = g_malloc0(sizeof(*e));

    e->value = value;

    /* see if we're just pushing a list head tracker */

    if (value == NULL) {

        e->is_list_head = true;

    }

    QTAILQ_INSERT_HEAD(&qov->stack, e, node);

}


void *vnc_zlib_zalloc(void *x, unsigned items, unsigned size)

{

    void *p;

    size *= items;

    size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);

    p = qemu_mallocz(size);

    return (p);

}


static int send_png_rect(VncState *vs, int x, int y, int w, int h,

                         VncPalette *palette)

{

    png_byte color_type;

    png_structp png_ptr;

    png_infop info_ptr;

    png_colorp png_palette = NULL;

    pixman_image_t *linebuf;

    int level = tight_png_conf[vs->tight.compression].png_zlib_level;

    int filters = tight_png_conf[vs->tight.compression].png_filters;

    uint8_t *buf;

    int dy;

    png_ptr = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL,

                                        NULL, vnc_png_malloc, vnc_png_free);

    if (png_ptr == NULL)

        return -1;

    info_ptr = png_create_info_struct(png_ptr);

    if (info_ptr == NULL) {

        png_destroy_write_struct(&png_ptr, NULL);

        return -1;

    }

    png_set_write_fn(png_ptr, (void *) vs, png_write_data, png_flush_data);

    png_set_compression_level(png_ptr, level);

    png_set_filter(png_ptr, PNG_FILTER_TYPE_DEFAULT, filters);

    if (palette) {

        color_type = PNG_COLOR_TYPE_PALETTE;

    } else {

        color_type = PNG_COLOR_TYPE_RGB;

    }

    png_set_IHDR(png_ptr, info_ptr, w, h,

                 8, color_type, PNG_INTERLACE_NONE,

                 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);

    if (color_type == PNG_COLOR_TYPE_PALETTE) {

        struct palette_cb_priv priv;

        png_palette = png_malloc(png_ptr, sizeof(*png_palette) *

                                 palette_size(palette));

        priv.vs = vs;

        priv.png_palette = png_palette;

        palette_iter(palette, write_png_palette, &priv);

        png_set_PLTE(png_ptr, info_ptr, png_palette, palette_size(palette));

        if (vs->client_pf.bytes_per_pixel == 4) {

            tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette);

        } else {

            tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette);

        }

    }

    png_write_info(png_ptr, info_ptr);

    buffer_reserve(&vs->tight.png, 2048);

    linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, w);

    buf = (uint8_t *)pixman_image_get_data(linebuf);

    for (dy = 0; dy < h; dy++)

    {

        if (color_type == PNG_COLOR_TYPE_PALETTE) {

            memcpy(buf, vs->tight.tight.buffer + (dy * w), w);

        } else {

            qemu_pixman_linebuf_fill(linebuf, vs->vd->server, w, dy);

        }

        png_write_row(png_ptr, buf);

    }

    qemu_pixman_image_unref(linebuf);

    png_write_end(png_ptr, NULL);

    if (color_type == PNG_COLOR_TYPE_PALETTE) {

        png_free(png_ptr, png_palette);

    }

    png_destroy_write_struct(&png_ptr, &info_ptr);

    vnc_write_u8(vs, VNC_TIGHT_PNG << 4);

    tight_send_compact_size(vs, vs->tight.png.offset);

    vnc_write(vs, vs->tight.png.buffer, vs->tight.png.offset);

    buffer_reset(&vs->tight.png);

    return 1;

}


void nvdimm_init_acpi_state(AcpiNVDIMMState *state, MemoryRegion *io,

                            FWCfgState *fw_cfg, Object *owner)

{

    memory_region_init_io(&state->io_mr, owner, &nvdimm_dsm_ops, state,

                          "nvdimm-acpi-io", NVDIMM_ACPI_IO_LEN);

    memory_region_add_subregion(io, NVDIMM_ACPI_IO_BASE, &state->io_mr);

    state->dsm_mem = g_array_new(false, true /* clear */, 1);

    acpi_data_push(state->dsm_mem, TARGET_PAGE_SIZE);

    fw_cfg_add_file(fw_cfg, NVDIMM_DSM_MEM_FILE, state->dsm_mem->data,

                    state->dsm_mem->len);

}


static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,

                               BdrvCheckMode fix, bool *rebuild,

                               void **refcount_table, int64_t *nb_clusters)

{

    BDRVQcow2State *s = bs->opaque;

    int64_t i;

    QCowSnapshot *sn;

    int ret;

    if (!*refcount_table) {

        int64_t old_size = 0;

        ret = realloc_refcount_array(s, refcount_table,

                                     &old_size, *nb_clusters);

        if (ret < 0) {

            res->check_errors++;

            return ret;

        }

    }

    /* header */

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        0, s->cluster_size);

    if (ret < 0) {

        return ret;

    }

    /* current L1 table */

    ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                             s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);

    if (ret < 0) {

        return ret;

    }

    /* snapshots */

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

        sn = s->snapshots + i;

        ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                                 sn->l1_table_offset, sn->l1_size, 0);

        if (ret < 0) {

            return ret;

        }

    }

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        s->snapshots_offset, s->snapshots_size);

    if (ret < 0) {

        return ret;

    }

    /* refcount data */

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        s->refcount_table_offset,

                        s->refcount_table_size * sizeof(uint64_t));

    if (ret < 0) {

        return ret;

    }

    /* encryption */

    if (s->crypto_header.length) {

        ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                            s->crypto_header.offset,

                            s->crypto_header.length);

        if (ret < 0) {

            return ret;

        }

    }

    return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);

}


static void ehci_trace_qtd(EHCIQueue *q, target_phys_addr_t addr, EHCIqtd *qtd)

{

    trace_usb_ehci_qtd(q, addr, qtd->next, qtd->altnext,

                       get_field(qtd->token, QTD_TOKEN_TBYTES),

                       get_field(qtd->token, QTD_TOKEN_CPAGE),

                       get_field(qtd->token, QTD_TOKEN_CERR),

                       get_field(qtd->token, QTD_TOKEN_PID),

                       (bool)(qtd->token & QTD_TOKEN_IOC),

                       (bool)(qtd->token & QTD_TOKEN_ACTIVE),

                       (bool)(qtd->token & QTD_TOKEN_HALT),

                       (bool)(qtd->token & QTD_TOKEN_BABBLE),

                       (bool)(qtd->token & QTD_TOKEN_XACTERR));

}


static void megasas_scsi_uninit(PCIDevice *d)

{

    MegasasState *s = MEGASAS(d);

    if (megasas_use_msix(s)) {

        msix_uninit(d, &s->mmio_io, &s->mmio_io);

    }

    if (megasas_use_msi(s)) {

        msi_uninit(d);

    }

}


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

                                 int *got_frame, AVPacket *avpkt)

{

    Jpeg2000DecoderContext *s = avctx->priv_data;

    ThreadFrame frame = { .f = data };

    AVFrame *picture = data;

    int tileno, ret;

    s->avctx     = avctx;

    s->buf       = s->buf_start = avpkt->data;

    s->buf_end   = s->buf_start + avpkt->size;

    s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles

    // reduction factor, i.e number of resolution levels to skip

    s->reduction_factor = s->lowres;

    ff_jpeg2000_init_tier1_luts();

    if (s->buf_end - s->buf < 2)

        return AVERROR(EINVAL);

    // check if the image is in jp2 format

    if ((AV_RB32(s->buf) == 12) &&

        (AV_RB32(s->buf + 4) == JP2_SIG_TYPE) &&

        (AV_RB32(s->buf + 8) == JP2_SIG_VALUE)) {

        if (!jp2_find_codestream(s)) {

            av_log(avctx, AV_LOG_ERROR,

                   "couldn't find jpeg2k codestream atom\n");

            return -1;

        }

    }

    if (bytestream_get_be16(&s->buf) != JPEG2000_SOC) {

        av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");

        return -1;

    }

    if (ret = jpeg2000_read_main_headers(s))

        goto end;

    /* get picture buffer */

    if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");

        goto end;

    }

    picture->pict_type = AV_PICTURE_TYPE_I;

    picture->key_frame = 1;

    if (ret = jpeg2000_read_bitstream_packets(s))

        goto end;

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)

        if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))

            goto end;

    *got_frame = 1;

end:

    jpeg2000_dec_cleanup(s);

    return ret ? ret : s->buf - s->buf_start;

}


static void vfio_platform_eoi(VFIODevice *vbasedev)

{

    VFIOINTp *intp;

    VFIOPlatformDevice *vdev =

        container_of(vbasedev, VFIOPlatformDevice, vbasedev);

    qemu_mutex_lock(&vdev->intp_mutex);

    QLIST_FOREACH(intp, &vdev->intp_list, next) {

        if (intp->state == VFIO_IRQ_ACTIVE) {

            trace_vfio_platform_eoi(intp->pin,

                                event_notifier_get_fd(&intp->interrupt));

            intp->state = VFIO_IRQ_INACTIVE;

            /* deassert the virtual IRQ */

            qemu_set_irq(intp->qemuirq, 0);

            if (intp->flags & VFIO_IRQ_INFO_AUTOMASKED) {

                /* unmasks the physical level-sensitive IRQ */

                vfio_unmask_single_irqindex(vbasedev, intp->pin);

            }

            /* a single IRQ can be active at a time */

            break;

        }

    }

    /* in case there are pending IRQs, handle the first one */

    if (!QSIMPLEQ_EMPTY(&vdev->pending_intp_queue)) {

        intp = QSIMPLEQ_FIRST(&vdev->pending_intp_queue);

        vfio_intp_inject_pending_lockheld(intp);

        QSIMPLEQ_REMOVE_HEAD(&vdev->pending_intp_queue, pqnext);

    }

    qemu_mutex_unlock(&vdev->intp_mutex);

}


static void gen_storeq_reg(DisasContext *s, int rlow, int rhigh, TCGv val)

{

    TCGv tmp;

    tmp = new_tmp();

    tcg_gen_trunc_i64_i32(tmp, val);

    store_reg(s, rlow, tmp);

    tmp = new_tmp();

    tcg_gen_shri_i64(val, val, 32);

    tcg_gen_trunc_i64_i32(tmp, val);

    store_reg(s, rhigh, tmp);

}