static int spapr_populate_pci_child_dt(PCIDevice *dev, void *fdt, int offset,

                                       sPAPRPHBState *sphb)

{

    ResourceProps rp;

    bool is_bridge = false;

    int pci_status, err;

    char *buf = NULL;

    uint32_t drc_index = spapr_phb_get_pci_drc_index(sphb, dev);

    uint32_t ccode = pci_default_read_config(dev, PCI_CLASS_PROG, 3);

    uint32_t max_msi, max_msix;

    if (pci_default_read_config(dev, PCI_HEADER_TYPE, 1) ==

        PCI_HEADER_TYPE_BRIDGE) {

        is_bridge = true;

    }

    /* in accordance with PAPR+ v2.7 13.6.3, Table 181 */

    _FDT(fdt_setprop_cell(fdt, offset, "vendor-id",

                          pci_default_read_config(dev, PCI_VENDOR_ID, 2)));

    _FDT(fdt_setprop_cell(fdt, offset, "device-id",

                          pci_default_read_config(dev, PCI_DEVICE_ID, 2)));

    _FDT(fdt_setprop_cell(fdt, offset, "revision-id",

                          pci_default_read_config(dev, PCI_REVISION_ID, 1)));

    _FDT(fdt_setprop_cell(fdt, offset, "class-code", ccode));

    if (pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)) {

        _FDT(fdt_setprop_cell(fdt, offset, "interrupts",

                 pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)));

    }

    if (!is_bridge) {

        _FDT(fdt_setprop_cell(fdt, offset, "min-grant",

            pci_default_read_config(dev, PCI_MIN_GNT, 1)));

        _FDT(fdt_setprop_cell(fdt, offset, "max-latency",

            pci_default_read_config(dev, PCI_MAX_LAT, 1)));

    }

    if (pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)) {

        _FDT(fdt_setprop_cell(fdt, offset, "subsystem-id",

                 pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)));

    }

    if (pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)) {

        _FDT(fdt_setprop_cell(fdt, offset, "subsystem-vendor-id",

                 pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)));

    }

    _FDT(fdt_setprop_cell(fdt, offset, "cache-line-size",

        pci_default_read_config(dev, PCI_CACHE_LINE_SIZE, 1)));

    /* the following fdt cells are masked off the pci status register */

    pci_status = pci_default_read_config(dev, PCI_STATUS, 2);

    _FDT(fdt_setprop_cell(fdt, offset, "devsel-speed",

                          PCI_STATUS_DEVSEL_MASK & pci_status));

    if (pci_status & PCI_STATUS_FAST_BACK) {

        _FDT(fdt_setprop(fdt, offset, "fast-back-to-back", NULL, 0));

    }

    if (pci_status & PCI_STATUS_66MHZ) {

        _FDT(fdt_setprop(fdt, offset, "66mhz-capable", NULL, 0));

    }

    if (pci_status & PCI_STATUS_UDF) {

        _FDT(fdt_setprop(fdt, offset, "udf-supported", NULL, 0));

    }

    _FDT(fdt_setprop_string(fdt, offset, "name",

                            pci_find_device_name((ccode >> 16) & 0xff,

                                                 (ccode >> 8) & 0xff,

                                                 ccode & 0xff)));

    buf = spapr_phb_get_loc_code(sphb, dev);

    if (!buf) {

        error_report("Failed setting the ibm,loc-code");

        return -1;

    }

    err = fdt_setprop_string(fdt, offset, "ibm,loc-code", buf);

    g_free(buf);

    if (err < 0) {

        return err;

    }

    if (drc_index) {

        _FDT(fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index));

    }

    _FDT(fdt_setprop_cell(fdt, offset, "#address-cells",

                          RESOURCE_CELLS_ADDRESS));

    _FDT(fdt_setprop_cell(fdt, offset, "#size-cells",

                          RESOURCE_CELLS_SIZE));

    max_msi = msi_nr_vectors_allocated(dev);

    if (max_msi) {

        _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi", max_msi));

    }

    max_msix = dev->msix_entries_nr;

    if (max_msix) {

        _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi-x", max_msix));

    }

    populate_resource_props(dev, &rp);

    _FDT(fdt_setprop(fdt, offset, "reg", (uint8_t *)rp.reg, rp.reg_len));

    _FDT(fdt_setprop(fdt, offset, "assigned-addresses",

                     (uint8_t *)rp.assigned, rp.assigned_len));

    if (pci_is_express(dev)) {

        _FDT(fdt_setprop_cell(fdt, offset, "ibm,pci-config-space-type", 0x1));

    }

    return 0;

}


static int v9fs_xattr_write(V9fsState *s, V9fsPDU *pdu, V9fsFidState *fidp,

                            uint64_t off, uint32_t count,

                            struct iovec *sg, int cnt)

{

    int i, to_copy;

    ssize_t err = 0;

    int write_count;

    int64_t xattr_len;

    size_t offset = 7;

    xattr_len = fidp->fs.xattr.len;

    write_count = xattr_len - off;

    if (write_count > count) {

        write_count = count;

    } else if (write_count < 0) {

        /*

         * write beyond XATTR value len specified in

         * xattrcreate

         */

        err = -ENOSPC;

        goto out;

    }

    offset += pdu_marshal(pdu, offset, "d", write_count);

    err = offset;

    fidp->fs.xattr.copied_len += write_count;

    /*

     * Now copy the content from sg list

     */

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

        if (write_count > sg[i].iov_len) {

            to_copy = sg[i].iov_len;

        } else {

            to_copy = write_count;

        }

        memcpy((char *)fidp->fs.xattr.value + off, sg[i].iov_base, to_copy);

        /* updating vs->off since we are not using below */

        off += to_copy;

        write_count -= to_copy;

    }

out:

    return err;

}


static int x86_cpu_filter_features(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    FeatureWord w;

    int rv = 0;

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

        uint32_t host_feat =

            x86_cpu_get_supported_feature_word(w, false);

        uint32_t requested_features = env->features[w];

        env->features[w] &= host_feat;

        cpu->filtered_features[w] = requested_features & ~env->features[w];

        if (cpu->filtered_features[w]) {

            rv = 1;

        }

    }

    return rv;

}


static int decode_mb(H264Context *h){

    MpegEncContext * const s = &h->s;

    const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;

    int mb_type, partition_count, cbp;

    s->dsp.clear_blocks(h->mb); //FIXME avoid if allready clear (move after skip handlong?

    tprintf("pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);

    cbp = 0; /* avoid warning. FIXME: find a solution without slowing

                down the code */

    if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){

        if(s->mb_skip_run==-1)

            s->mb_skip_run= get_ue_golomb(&s->gb);

        if (s->mb_skip_run--) {

            int mx, my;

            /* skip mb */

//FIXME b frame

            mb_type= MB_TYPE_16x16|MB_TYPE_P0L0|MB_TYPE_P1L0;

            memset(h->non_zero_count[mb_xy], 0, 16+4+4);

            memset(h->non_zero_count_cache + 8, 0, 8*5); //FIXME ugly, remove pfui

            if(h->sps.mb_aff && s->mb_skip_run==0 && (s->mb_y&1)==0){

                h->mb_field_decoding_flag= get_bits1(&s->gb);

            }

            if(h->mb_field_decoding_flag)

                mb_type|= MB_TYPE_INTERLACED;

            fill_caches(h, mb_type); //FIXME check what is needed and what not ...

            pred_pskip_motion(h, &mx, &my);

            fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, 0, 1);

            fill_rectangle(  h->mv_cache[0][scan8[0]], 4, 4, 8, pack16to32(mx,my), 4);

            write_back_motion(h, mb_type);

            s->current_picture.mb_type[mb_xy]= mb_type; //FIXME SKIP type

            s->current_picture.qscale_table[mb_xy]= s->qscale;

            h->slice_table[ mb_xy ]= h->slice_num;

            h->prev_mb_skiped= 1;

            return 0;

        }

    }

    if(h->sps.mb_aff /* && !field pic FIXME needed? */){

        if((s->mb_y&1)==0)

            h->mb_field_decoding_flag = get_bits1(&s->gb);

    }else

        h->mb_field_decoding_flag=0; //FIXME som ed note ?!

    h->prev_mb_skiped= 0;

    mb_type= get_ue_golomb(&s->gb);

    if(h->slice_type == B_TYPE){

        if(mb_type < 23){

            partition_count= b_mb_type_info[mb_type].partition_count;

            mb_type=         b_mb_type_info[mb_type].type;

        }else{

            mb_type -= 23;

            goto decode_intra_mb;

        }

    }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){

        if(mb_type < 5){

            partition_count= p_mb_type_info[mb_type].partition_count;

            mb_type=         p_mb_type_info[mb_type].type;

        }else{

            mb_type -= 5;

            goto decode_intra_mb;

        }

    }else{

       assert(h->slice_type == I_TYPE);

decode_intra_mb:

        if(mb_type > 25){

            av_log(h->s.avctx, AV_LOG_ERROR, "mb_type %d in %c slice to large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);

            return -1;

        }

        partition_count=0;

        cbp= i_mb_type_info[mb_type].cbp;

        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;

        mb_type= i_mb_type_info[mb_type].type;

    }

    if(h->mb_field_decoding_flag)

        mb_type |= MB_TYPE_INTERLACED;

    s->current_picture.mb_type[mb_xy]= mb_type;

    h->slice_table[ mb_xy ]= h->slice_num;

    if(IS_INTRA_PCM(mb_type)){

        const uint8_t *ptr;

        int x, y;

        // we assume these blocks are very rare so we dont optimize it

        align_get_bits(&s->gb);

        ptr= s->gb.buffer + get_bits_count(&s->gb);

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

            const int index= 4*(y&3) + 64*(y>>2);

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

                h->mb[index + (x&3) + 16*(x>>2)]= *(ptr++);

            }

        }

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

            const int index= 256 + 4*(y&3) + 32*(y>>2);

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

                h->mb[index + (x&3) + 16*(x>>2)]= *(ptr++);

            }

        }

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

            const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);

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

                h->mb[index + (x&3) + 16*(x>>2)]= *(ptr++);

            }

        }

        skip_bits(&s->gb, 384); //FIXME check /fix the bitstream readers

        memset(h->non_zero_count[mb_xy], 16, 16+4+4);

        s->current_picture.qscale_table[mb_xy]= s->qscale;

        return 0;

    }

    fill_caches(h, mb_type);

    //mb_pred

    if(IS_INTRA(mb_type)){

//            init_top_left_availability(h);

            if(IS_INTRA4x4(mb_type)){

                int i;

//                fill_intra4x4_pred_table(h);

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

                    const int mode_coded= !get_bits1(&s->gb);

                    const int predicted_mode=  pred_intra_mode(h, i);

                    int mode;

                    if(mode_coded){

                        const int rem_mode= get_bits(&s->gb, 3);

                        if(rem_mode<predicted_mode)

                            mode= rem_mode;

                        else

                            mode= rem_mode + 1;

                    }else{

                        mode= predicted_mode;

                    }

                    h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;

                }

                write_back_intra_pred_mode(h);

                if( check_intra4x4_pred_mode(h) < 0)

                    return -1;

            }else{

                h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);

                if(h->intra16x16_pred_mode < 0)

                    return -1;

            }

            h->chroma_pred_mode= get_ue_golomb(&s->gb);

            h->chroma_pred_mode= check_intra_pred_mode(h, h->chroma_pred_mode);

            if(h->chroma_pred_mode < 0)

                return -1;

    }else if(partition_count==4){

        int i, j, sub_partition_count[4], list, ref[2][4];

        if(h->slice_type == B_TYPE){

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

                h->sub_mb_type[i]= get_ue_golomb(&s->gb);

                if(h->sub_mb_type[i] >=13){

                    av_log(h->s.avctx, AV_LOG_ERROR, "B sub_mb_type %d out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);

                    return -1;

                }

                sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;

                h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;

            }

        }else{

            assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?

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

                h->sub_mb_type[i]= get_ue_golomb(&s->gb);

                if(h->sub_mb_type[i] >=4){

                    av_log(h->s.avctx, AV_LOG_ERROR, "P sub_mb_type %d out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);

                    return -1;

                }

                sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;

                h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;

            }

        }

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

            const int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];

            if(ref_count == 0) continue;

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

                if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){

                    ref[list][i] = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?

                }else{

                 //FIXME

                    ref[list][i] = -1;

                }

            }

        }

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

            const int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];

            if(ref_count == 0) continue;

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

                h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ]=

                h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];

                if(IS_DIR(h->sub_mb_type[i], 0, list) && !IS_DIRECT(h->sub_mb_type[i])){

                    const int sub_mb_type= h->sub_mb_type[i];

                    const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;

                    for(j=0; j<sub_partition_count[i]; j++){

                        int mx, my;

                        const int index= 4*i + block_width*j;

                        int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];

                        pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);

                        mx += get_se_golomb(&s->gb);

                        my += get_se_golomb(&s->gb);

                        tprintf("final mv:%d %d\n", mx, my);

                        if(IS_SUB_8X8(sub_mb_type)){

                            mv_cache[ 0 ][0]= mv_cache[ 1 ][0]=

                            mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;

                            mv_cache[ 0 ][1]= mv_cache[ 1 ][1]=

                            mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;

                        }else if(IS_SUB_8X4(sub_mb_type)){

                            mv_cache[ 0 ][0]= mv_cache[ 1 ][0]= mx;

                            mv_cache[ 0 ][1]= mv_cache[ 1 ][1]= my;

                        }else if(IS_SUB_4X8(sub_mb_type)){

                            mv_cache[ 0 ][0]= mv_cache[ 8 ][0]= mx;

                            mv_cache[ 0 ][1]= mv_cache[ 8 ][1]= my;

                        }else{

                            assert(IS_SUB_4X4(sub_mb_type));

                            mv_cache[ 0 ][0]= mx;

                            mv_cache[ 0 ][1]= my;

                        }

                    }

                }else{

                    uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];

                    p[0] = p[1]=

                    p[8] = p[9]= 0;

                }

            }

        }

    }else if(!IS_DIRECT(mb_type)){

        int list, mx, my, i;

         //FIXME we should set ref_idx_l? to 0 if we use that later ...

        if(IS_16X16(mb_type)){

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

                if(h->ref_count[0]>0){

                    if(IS_DIR(mb_type, 0, list)){

                        const int val= get_te0_golomb(&s->gb, h->ref_count[list]);

                        fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);

                    }

                }

            }

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

                if(IS_DIR(mb_type, 0, list)){

                    pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);

                    mx += get_se_golomb(&s->gb);

                    my += get_se_golomb(&s->gb);

                    tprintf("final mv:%d %d\n", mx, my);

                    fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);

                }

            }

        }

        else if(IS_16X8(mb_type)){

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

                if(h->ref_count[list]>0){

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

                        if(IS_DIR(mb_type, i, list)){

                            const int val= get_te0_golomb(&s->gb, h->ref_count[list]);

                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);

                        }

                    }

                }

            }

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

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

                    if(IS_DIR(mb_type, i, list)){

                        pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);

                        mx += get_se_golomb(&s->gb);

                        my += get_se_golomb(&s->gb);

                        tprintf("final mv:%d %d\n", mx, my);

                        fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);

                    }

                }

            }

        }else{

            assert(IS_8X16(mb_type));

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

                if(h->ref_count[list]>0){

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

                        if(IS_DIR(mb_type, i, list)){ //FIXME optimize

                            const int val= get_te0_golomb(&s->gb, h->ref_count[list]);

                            fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);

                        }

                    }

                }

            }

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

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

                    if(IS_DIR(mb_type, i, list)){

                        pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);

                        mx += get_se_golomb(&s->gb);

                        my += get_se_golomb(&s->gb);

                        tprintf("final mv:%d %d\n", mx, my);

                        fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);

                    }

                }

            }

        }

    }

    if(IS_INTER(mb_type))

        write_back_motion(h, mb_type);

    if(!IS_INTRA16x16(mb_type)){

        cbp= get_ue_golomb(&s->gb);

        if(cbp > 47){

            av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%d) at %d %d\n", cbp, s->mb_x, s->mb_y);

            return -1;

        }

        if(IS_INTRA4x4(mb_type))

            cbp= golomb_to_intra4x4_cbp[cbp];

        else

            cbp= golomb_to_inter_cbp[cbp];

    }

    if(cbp || IS_INTRA16x16(mb_type)){

        int i8x8, i4x4, chroma_idx;

        int chroma_qp, dquant;

        GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;

        const uint8_t *scan, *dc_scan;

//        fill_non_zero_count_cache(h);

        if(IS_INTERLACED(mb_type)){

            scan= field_scan;

            dc_scan= luma_dc_field_scan;

        }else{

            scan= zigzag_scan;

            dc_scan= luma_dc_zigzag_scan;

        }

        dquant= get_se_golomb(&s->gb);

        if( dquant > 25 || dquant < -26 ){

            av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);

            return -1;

        }

        s->qscale += dquant;

        if(((unsigned)s->qscale) > 51){

            if(s->qscale<0) s->qscale+= 52;

            else            s->qscale-= 52;

        }

        h->chroma_qp= chroma_qp= get_chroma_qp(h, s->qscale);

        if(IS_INTRA16x16(mb_type)){

            if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, s->qscale, 16) < 0){

                return -1; //FIXME continue if partotioned and other retirn -1 too

            }

            assert((cbp&15) == 0 || (cbp&15) == 15);

            if(cbp&15){

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

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

                        const int index= i4x4 + 4*i8x8;

                        if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, s->qscale, 15) < 0 ){

                            return -1;

                        }

                    }

                }

            }else{

                fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);

            }

        }else{

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

                if(cbp & (1<<i8x8)){

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

                        const int index= i4x4 + 4*i8x8;

                        if( decode_residual(h, gb, h->mb + 16*index, index, scan, s->qscale, 16) <0 ){

                            return -1;

                        }

                    }

                }else{

                    uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];

                    nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;

                }

            }

        }

        if(cbp&0x30){

            for(chroma_idx=0; chroma_idx<2; chroma_idx++)

                if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, chroma_qp, 4) < 0){

                    return -1;

                }

        }

        if(cbp&0x20){

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

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

                    const int index= 16 + 4*chroma_idx + i4x4;

                    if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, chroma_qp, 15) < 0){

                        return -1;

                    }

                }

            }

        }else{

            uint8_t * const nnz= &h->non_zero_count_cache[0];

            nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =

            nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;

        }

    }else{

        memset(&h->non_zero_count_cache[8], 0, 8*5);

    }

    s->current_picture.qscale_table[mb_xy]= s->qscale;

    write_back_non_zero_count(h);

    return 0;

}


static void decode_vui(GetBitContext *gb, AVCodecContext *avctx,

                       int apply_defdispwin, HEVCSPS *sps)

{

    VUI *vui          = &sps->vui;

    int sar_present;

    av_log(avctx, AV_LOG_DEBUG, "Decoding VUI\n");

    sar_present = get_bits1(gb);

    if (sar_present) {

        uint8_t sar_idx = get_bits(gb, 8);

        if (sar_idx < FF_ARRAY_ELEMS(vui_sar))

            vui->sar = vui_sar[sar_idx];

        else if (sar_idx == 255) {

            vui->sar.num = get_bits(gb, 16);

            vui->sar.den = get_bits(gb, 16);

        } else

            av_log(avctx, AV_LOG_WARNING,

                   "Unknown SAR index: %u.\n", sar_idx);

    }

    vui->overscan_info_present_flag = get_bits1(gb);

    if (vui->overscan_info_present_flag)

        vui->overscan_appropriate_flag = get_bits1(gb);

    vui->video_signal_type_present_flag = get_bits1(gb);

    if (vui->video_signal_type_present_flag) {

        vui->video_format                    = get_bits(gb, 3);

        vui->video_full_range_flag           = get_bits1(gb);

        vui->colour_description_present_flag = get_bits1(gb);

        if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P)

            sps->pix_fmt = AV_PIX_FMT_YUVJ420P;

        if (vui->colour_description_present_flag) {

            vui->colour_primaries        = get_bits(gb, 8);

            vui->transfer_characteristic = get_bits(gb, 8);

            vui->matrix_coeffs           = get_bits(gb, 8);

            // Set invalid values to "unspecified"

            if (vui->colour_primaries >= AVCOL_PRI_NB)

                vui->colour_primaries = AVCOL_PRI_UNSPECIFIED;

            if (vui->transfer_characteristic >= AVCOL_TRC_NB)

                vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED;

            if (vui->matrix_coeffs >= AVCOL_SPC_NB)

                vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED;

        }

    }

    vui->chroma_loc_info_present_flag = get_bits1(gb);

    if (vui->chroma_loc_info_present_flag) {

        vui->chroma_sample_loc_type_top_field    = get_ue_golomb_long(gb);

        vui->chroma_sample_loc_type_bottom_field = get_ue_golomb_long(gb);

    }

    vui->neutra_chroma_indication_flag = get_bits1(gb);

    vui->field_seq_flag                = get_bits1(gb);

    vui->frame_field_info_present_flag = get_bits1(gb);

    vui->default_display_window_flag = get_bits1(gb);

    if (vui->default_display_window_flag) {

        //TODO: * 2 is only valid for 420

        vui->def_disp_win.left_offset   = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.right_offset  = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.top_offset    = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.bottom_offset = get_ue_golomb_long(gb) * 2;

        if (apply_defdispwin &&

            avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {

            av_log(avctx, AV_LOG_DEBUG,

                   "discarding vui default display window, "

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

                   vui->def_disp_win.left_offset,

                   vui->def_disp_win.right_offset,

                   vui->def_disp_win.top_offset,

                   vui->def_disp_win.bottom_offset);

            vui->def_disp_win.left_offset   =

            vui->def_disp_win.right_offset  =

            vui->def_disp_win.top_offset    =

            vui->def_disp_win.bottom_offset = 0;

        }

    }

    vui->vui_timing_info_present_flag = get_bits1(gb);

    if (vui->vui_timing_info_present_flag) {

        vui->vui_num_units_in_tick               = get_bits_long(gb, 32);

        vui->vui_time_scale                      = get_bits_long(gb, 32);

        vui->vui_poc_proportional_to_timing_flag = get_bits1(gb);

        if (vui->vui_poc_proportional_to_timing_flag)

            vui->vui_num_ticks_poc_diff_one_minus1 = get_ue_golomb_long(gb);

        vui->vui_hrd_parameters_present_flag = get_bits1(gb);

        if (vui->vui_hrd_parameters_present_flag)

            decode_hrd(gb, 1, sps->max_sub_layers);

    }

    vui->bitstream_restriction_flag = get_bits1(gb);

    if (vui->bitstream_restriction_flag) {

        vui->tiles_fixed_structure_flag              = get_bits1(gb);

        vui->motion_vectors_over_pic_boundaries_flag = get_bits1(gb);

        vui->restricted_ref_pic_lists_flag           = get_bits1(gb);

        vui->min_spatial_segmentation_idc            = get_ue_golomb_long(gb);

        vui->max_bytes_per_pic_denom                 = get_ue_golomb_long(gb);

        vui->max_bits_per_min_cu_denom               = get_ue_golomb_long(gb);

        vui->log2_max_mv_length_horizontal           = get_ue_golomb_long(gb);

        vui->log2_max_mv_length_vertical             = get_ue_golomb_long(gb);

    }

}


static int ivf_write_trailer(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    if (pb->seekable) {

        IVFEncContext *ctx = s->priv_data;

        size_t end = avio_tell(pb);

        avio_seek(pb, 24, SEEK_SET);

        avio_wl64(pb, ctx->frame_cnt * ctx->sum_delta_pts / (ctx->frame_cnt - 1));

        avio_seek(pb, end, SEEK_SET);

    }

    return 0;

}


static int main_loop(void)

{

    int ret, timeout;

#ifdef CONFIG_PROFILER

    int64_t ti;

#endif

    CPUState *env;

    cur_cpu = first_cpu;

    next_cpu = cur_cpu->next_cpu ?: first_cpu;

    for(;;) {

        if (vm_running) {

            for(;;) {

                /* get next cpu */

                env = next_cpu;

#ifdef CONFIG_PROFILER

                ti = profile_getclock();

#endif

                if (use_icount) {

                    int64_t count;

                    int decr;

                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);

                    env->icount_decr.u16.low = 0;

                    env->icount_extra = 0;

                    count = qemu_next_deadline();

                    count = (count + (1 << icount_time_shift) - 1)

                            >> icount_time_shift;

                    qemu_icount += count;

                    decr = (count > 0xffff) ? 0xffff : count;

                    count -= decr;

                    env->icount_decr.u16.low = decr;

                    env->icount_extra = count;

                }

                ret = cpu_exec(env);

#ifdef CONFIG_PROFILER

                qemu_time += profile_getclock() - ti;

#endif

                if (use_icount) {

                    /* Fold pending instructions back into the

                       instruction counter, and clear the interrupt flag.  */

                    qemu_icount -= (env->icount_decr.u16.low

                                    + env->icount_extra);

                    env->icount_decr.u32 = 0;

                    env->icount_extra = 0;

                }

                next_cpu = env->next_cpu ?: first_cpu;

                if (event_pending && likely(ret != EXCP_DEBUG)) {

                    ret = EXCP_INTERRUPT;

                    event_pending = 0;

                    break;

                }

                if (ret == EXCP_HLT) {

                    /* Give the next CPU a chance to run.  */

                    cur_cpu = env;

                    continue;

                }

                if (ret != EXCP_HALTED)

                    break;

                /* all CPUs are halted ? */

                if (env == cur_cpu)

                    break;

            }

            cur_cpu = env;

            if (shutdown_requested) {

                ret = EXCP_INTERRUPT;

                if (no_shutdown) {

                    vm_stop(0);

                    no_shutdown = 0;

                }

                else

                    break;

            }

            if (reset_requested) {

                reset_requested = 0;

                qemu_system_reset();

                ret = EXCP_INTERRUPT;

            }

            if (powerdown_requested) {

                powerdown_requested = 0;

		qemu_system_powerdown();

                ret = EXCP_INTERRUPT;

            }

            if (unlikely(ret == EXCP_DEBUG)) {

                vm_stop(EXCP_DEBUG);

            }

            /* If all cpus are halted then wait until the next IRQ */

            /* XXX: use timeout computed from timers */

            if (ret == EXCP_HALTED) {

                if (use_icount) {

                    int64_t add;

                    int64_t delta;

                    /* Advance virtual time to the next event.  */

                    if (use_icount == 1) {

                        /* When not using an adaptive execution frequency

                           we tend to get badly out of sync with real time,

                           so just delay for a reasonable amount of time.  */

                        delta = 0;

                    } else {

                        delta = cpu_get_icount() - cpu_get_clock();

                    }

                    if (delta > 0) {

                        /* If virtual time is ahead of real time then just

                           wait for IO.  */

                        timeout = (delta / 1000000) + 1;

                    } else {

                        /* Wait for either IO to occur or the next

                           timer event.  */

                        add = qemu_next_deadline();

                        /* We advance the timer before checking for IO.

                           Limit the amount we advance so that early IO

                           activity won't get the guest too far ahead.  */

                        if (add > 10000000)

                            add = 10000000;

                        delta += add;

                        add = (add + (1 << icount_time_shift) - 1)

                              >> icount_time_shift;

                        qemu_icount += add;

                        timeout = delta / 1000000;

                        if (timeout < 0)

                            timeout = 0;

                    }

                } else {

                    timeout = 10;

                }

            } else {

                timeout = 0;

            }

        } else {

            if (shutdown_requested)

                break;

            timeout = 10;

        }

#ifdef CONFIG_PROFILER

        ti = profile_getclock();

#endif

        main_loop_wait(timeout);

#ifdef CONFIG_PROFILER

        dev_time += profile_getclock() - ti;

#endif

    }

    cpu_disable_ticks();

    return ret;

}


int acpi_table_add(const QemuOpts *opts)

{

    AcpiTableOptions *hdrs = NULL;

    Error *err = NULL;

    char **pathnames = NULL;

    char **cur;

    size_t len, start, allen;

    bool has_header;

    int changed;

    int r;

    struct acpi_table_header hdr;

    char unsigned *table_start;

    {

        OptsVisitor *ov;

        ov = opts_visitor_new(opts);

        visit_type_AcpiTableOptions(opts_get_visitor(ov), &hdrs, NULL, &err);

        opts_visitor_cleanup(ov);

    }

    if (err) {

        goto out;

    }

    if (hdrs->has_file == hdrs->has_data) {

        error_setg(&err, "'-acpitable' requires one of 'data' or 'file'");

        goto out;

    }

    has_header = hdrs->has_file;

    pathnames = g_strsplit(hdrs->has_file ? hdrs->file : hdrs->data, ":", 0);

    if (pathnames == NULL || pathnames[0] == NULL) {

        error_setg(&err, "'-acpitable' requires at least one pathname");

        goto out;

    }

    if (!acpi_tables) {

        allen = sizeof(uint16_t);

        acpi_tables = g_malloc0(allen);

    } else {

        allen = acpi_tables_len;

    }

    start = allen;

    acpi_tables = g_realloc(acpi_tables, start + ACPI_TABLE_HDR_SIZE);

    allen += has_header ? ACPI_TABLE_PFX_SIZE : ACPI_TABLE_HDR_SIZE;

    /* now read in the data files, reallocating buffer as needed */

    for (cur = pathnames; *cur; ++cur) {

        int fd = open(*cur, O_RDONLY | O_BINARY);

        if (fd < 0) {

            error_setg(&err, "can't open file %s: %s", *cur, strerror(errno));

            goto out;

        }

        for (;;) {

            char unsigned data[8192];

            r = read(fd, data, sizeof(data));

            if (r == 0) {

                break;

            } else if (r > 0) {

                acpi_tables = g_realloc(acpi_tables, allen + r);

                memcpy(acpi_tables + allen, data, r);

                allen += r;

            } else if (errno != EINTR) {

                error_setg(&err, "can't read file %s: %s",

                           *cur, strerror(errno));

                close(fd);

                goto out;

            }

        }

        close(fd);

    }

    /* now fill in the header fields */

    table_start = acpi_tables + start;   /* start of the table */

    changed = 0;

    /* copy the header to temp place to align the fields */

    memcpy(&hdr, has_header ? table_start : dfl_hdr, ACPI_TABLE_HDR_SIZE);

    /* length of the table minus our prefix */

    len = allen - start - ACPI_TABLE_PFX_SIZE;

    hdr._length = cpu_to_le16(len);

    if (hdrs->has_sig) {

        /* strncpy is justified: the field need not be NUL-terminated. */

        strncpy(hdr.sig, hdrs->sig, sizeof(hdr.sig));

        ++changed;

    }

    /* length of the table including header, in bytes */

    if (has_header) {

        unsigned long val;

        /* check if actual length is correct */

        val = le32_to_cpu(hdr.length);

        if (val != len) {

            fprintf(stderr,

                "warning: acpitable has wrong length,"

                " header says %lu, actual size %zu bytes\n",

                val, len);

            ++changed;

        }

    }

    /* we may avoid putting length here if has_header is true */

    hdr.length = cpu_to_le32(len);

    if (hdrs->has_rev) {

        hdr.revision = hdrs->rev;

        ++changed;

    }

    if (hdrs->has_oem_id) {

        /* strncpy is justified: the field need not be NUL-terminated. */

        strncpy(hdr.oem_id, hdrs->oem_id, sizeof(hdr.oem_id));

        ++changed;

    }

    if (hdrs->has_oem_table_id) {

        /* strncpy is justified: the field need not be NUL-terminated. */

        strncpy(hdr.oem_table_id, hdrs->oem_table_id,

                sizeof(hdr.oem_table_id));

        ++changed;

    }

    if (hdrs->has_oem_rev) {

        hdr.oem_revision = cpu_to_le32(hdrs->oem_rev);

        ++changed;

    }

    if (hdrs->has_asl_compiler_id) {

        /* strncpy is justified: the field need not be NUL-terminated. */

        strncpy(hdr.asl_compiler_id, hdrs->asl_compiler_id,

                sizeof(hdr.asl_compiler_id));

        ++changed;

    }

    if (hdrs->has_asl_compiler_rev) {

        hdr.asl_compiler_revision = cpu_to_le32(hdrs->asl_compiler_rev);

        ++changed;

    }

    if (!has_header && !changed) {

        fprintf(stderr, "warning: acpitable: no table headers are specified\n");

    }

    /* now calculate checksum of the table, complete with the header */

    /* we may as well leave checksum intact if has_header is true */

    /* alternatively there may be a way to set cksum to a given value */

    hdr.checksum = 0;    /* for checksum calculation */

    /* put header back */

    memcpy(table_start, &hdr, sizeof(hdr));

    if (changed || !has_header || 1) {

        ((struct acpi_table_header *)table_start)->checksum =

            acpi_checksum((uint8_t *)table_start + ACPI_TABLE_PFX_SIZE, len);

    }

    /* increase number of tables */

    (*(uint16_t *)acpi_tables) =

        cpu_to_le32(le32_to_cpu(*(uint16_t *)acpi_tables) + 1);

    acpi_tables_len = allen;

out:

    g_strfreev(pathnames);

    if (hdrs != NULL) {

        QapiDeallocVisitor *dv;

        dv = qapi_dealloc_visitor_new();

        visit_type_AcpiTableOptions(qapi_dealloc_get_visitor(dv), &hdrs, NULL,

                                    NULL);

        qapi_dealloc_visitor_cleanup(dv);

    }

    if (err) {

        fprintf(stderr, "%s\n", error_get_pretty(err));

        error_free(err);

        return -1;

    }

    return 0;

}


static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;

    int entries, i;

    print_atom("stsz", atom);

    get_byte(pb); /* version */

    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */

    sc->sample_size = get_be32(pb);

    entries = get_be32(pb);

    sc->sample_count = entries;

#ifdef DEBUG

    av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);

#endif

    if(sc->sample_size)

        return 0; /* there isn't any table following */

    sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));

    if (!sc->sample_sizes)

        return -1;

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

        sc->sample_sizes[i] = get_be32(pb);

#ifdef DEBUG

/*        av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]); */

#endif

    }

    return 0;

}


CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,

                                    void (*init)(struct CharDriverState *s))

{

    CharDriverState *chr;

    int i;

    int ret;

    if (qemu_opts_id(opts) == NULL) {

        fprintf(stderr, "chardev: no id specified\n");

        return NULL;

    }

    if (qemu_opt_get(opts, "backend") == NULL) {

        fprintf(stderr, "chardev: \"%s\" missing backend\n",

                qemu_opts_id(opts));

        return NULL;

    }

    for (i = 0; i < ARRAY_SIZE(backend_table); i++) {

        if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)

            break;

    }

    if (i == ARRAY_SIZE(backend_table)) {

        fprintf(stderr, "chardev: backend \"%s\" not found\n",

                qemu_opt_get(opts, "backend"));

        return NULL;

    }

    ret = backend_table[i].open(opts, &chr);

    if (ret < 0) {

        fprintf(stderr, "chardev: opening backend \"%s\" failed: %s\n",

                qemu_opt_get(opts, "backend"), strerror(-ret));

        return NULL;

    }

    if (!chr->filename)

        chr->filename = g_strdup(qemu_opt_get(opts, "backend"));

    chr->init = init;

    QTAILQ_INSERT_TAIL(&chardevs, chr, next);

    if (qemu_opt_get_bool(opts, "mux", 0)) {

        CharDriverState *base = chr;

        int len = strlen(qemu_opts_id(opts)) + 6;

        base->label = g_malloc(len);

        snprintf(base->label, len, "%s-base", qemu_opts_id(opts));

        chr = qemu_chr_open_mux(base);

        chr->filename = base->filename;

        chr->avail_connections = MAX_MUX;

        QTAILQ_INSERT_TAIL(&chardevs, chr, next);

    } else {

        chr->avail_connections = 1;

    }

    chr->label = g_strdup(qemu_opts_id(opts));

    return chr;

}


static void bastardized_rice_decompress(ALACContext *alac,

                                 int32_t *output_buffer,

                                 int output_size,

                                 int readsamplesize, /* arg_10 */

                                 int rice_initialhistory, /* arg424->b */

                                 int rice_kmodifier, /* arg424->d */

                                 int rice_historymult, /* arg424->c */

                                 int rice_kmodifier_mask /* arg424->e */

        )

{

    int output_count;

    unsigned int history = rice_initialhistory;

    int sign_modifier = 0;

    for (output_count = 0; output_count < output_size; output_count++) {

        int32_t x;

        int32_t x_modified;

        int32_t final_val;

        /* standard rice encoding */

        int k; /* size of extra bits */

        /* read k, that is bits as is */

        k = av_log2((history >> 9) + 3);

        x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);

        x_modified = sign_modifier + x;

        final_val = (x_modified + 1) / 2;

        if (x_modified & 1) final_val *= -1;

        output_buffer[output_count] = final_val;

        sign_modifier = 0;

        /* now update the history */

        history += x_modified * rice_historymult

                   - ((history * rice_historymult) >> 9);

        if (x_modified > 0xffff)

            history = 0xffff;

        /* special case: there may be compressed blocks of 0 */

        if ((history < 128) && (output_count+1 < output_size)) {

            int k;

            unsigned int block_size;

            sign_modifier = 1;

            k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);

            block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);

            if (block_size > 0) {

                if(block_size >= output_size - output_count){

                    av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);

                    block_size= output_size - output_count - 1;

                }

                memset(&output_buffer[output_count+1], 0, block_size * 4);

                output_count += block_size;

            }

            if (block_size > 0xffff)

                sign_modifier = 0;

            history = 0;

        }

    }

}


static int vdadec_decode(AVCodecContext *avctx,
        void *data, int *got_frame, AVPacket *avpkt)
{
    VDADecoderContext *ctx = avctx->priv_data;
    AVFrame *pic = data;
    int ret;
    ret = ff_h264_decoder.decode(avctx, data, got_frame, avpkt);
    if (*got_frame) {
        AVBufferRef *buffer = pic->buf[0];
        VDABufferContext *context = av_buffer_get_opaque(buffer);
        CVPixelBufferRef cv_buffer = (CVPixelBufferRef)pic->data[3];
        CVPixelBufferLockBaseAddress(cv_buffer, 0);
        context->cv_buffer = cv_buffer;
        pic->format = ctx->pix_fmt;
        if (CVPixelBufferIsPlanar(cv_buffer)) {
            int i, count = CVPixelBufferGetPlaneCount(cv_buffer);
            av_assert0(count < 4);
            for (i = 0; i < count; i++) {
                pic->data[i] = CVPixelBufferGetBaseAddressOfPlane(cv_buffer, i);
                pic->linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(cv_buffer, i);
            }
        } else {
            pic->data[0] = CVPixelBufferGetBaseAddress(cv_buffer);
            pic->linesize[0] = CVPixelBufferGetBytesPerRow(cv_buffer);
        }
    }
    avctx->pix_fmt = ctx->pix_fmt;
    return ret;
}


static int target_pread(int fd, abi_ulong ptr, abi_ulong len,

                        abi_ulong offset)

{

    void *buf;

    int ret;

    buf = lock_user(VERIFY_WRITE, ptr, len, 0);

    ret = pread(fd, buf, len, offset);

    unlock_user(buf, ptr, len);

    return ret;


void helper_lret_protected(int shift, int addend)

{

    helper_ret_protected(shift, 0, addend);

#ifdef CONFIG_KQEMU

    if (kqemu_is_ok(env)) {

        env->exception_index = -1;

        cpu_loop_exit();

    }

#endif

}


uint32_t gic_acknowledge_irq(GICState *s, int cpu)

{

    int ret, irq, src;

    int cm = 1 << cpu;

    irq = s->current_pending[cpu];

    if (irq == 1023

            || GIC_GET_PRIORITY(irq, cpu) >= s->running_priority[cpu]) {

        DPRINTF("ACK no pending IRQ\n");

        return 1023;

    }

    s->last_active[irq][cpu] = s->running_irq[cpu];

    if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

        /* Clear pending flags for both level and edge triggered interrupts.

         * Level triggered IRQs will be reasserted once they become inactive.

         */

        GIC_CLEAR_PENDING(irq, GIC_TEST_MODEL(irq) ? ALL_CPU_MASK : cm);

        ret = irq;

    } else {

        if (irq < GIC_NR_SGIS) {

            /* Lookup the source CPU for the SGI and clear this in the

             * sgi_pending map.  Return the src and clear the overall pending

             * state on this CPU if the SGI is not pending from any CPUs.

             */

            assert(s->sgi_pending[irq][cpu] != 0);

            src = ctz32(s->sgi_pending[irq][cpu]);

            s->sgi_pending[irq][cpu] &= ~(1 << src);

            if (s->sgi_pending[irq][cpu] == 0) {

                GIC_CLEAR_PENDING(irq, GIC_TEST_MODEL(irq) ? ALL_CPU_MASK : cm);

            }

            ret = irq | ((src & 0x7) << 10);

        } else {

            /* Clear pending state for both level and edge triggered

             * interrupts. (level triggered interrupts with an active line

             * remain pending, see gic_test_pending)

             */

            GIC_CLEAR_PENDING(irq, GIC_TEST_MODEL(irq) ? ALL_CPU_MASK : cm);

            ret = irq;

        }

    }

    gic_set_running_irq(s, cpu, irq);

    DPRINTF("ACK %d\n", irq);

    return ret;

}


av_cold void ff_dsputil_init_ppc(DSPContext *c, AVCodecContext *avctx)

{

    const int high_bit_depth = avctx->bits_per_raw_sample > 8;

    // Common optimizations whether AltiVec is available or not

    if (!high_bit_depth) {

    switch (check_dcbzl_effect()) {

        case 32:

            c->clear_blocks = clear_blocks_dcbz32_ppc;

            break;

        case 128:

            c->clear_blocks = clear_blocks_dcbz128_ppc;

            break;

        default:

            break;

    }

    }

#if HAVE_ALTIVEC

    if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {

        ff_dsputil_init_altivec(c, avctx);

        ff_int_init_altivec(c, avctx);

        c->gmc1 = ff_gmc1_altivec;

#if CONFIG_ENCODERS

        if (avctx->bits_per_raw_sample <= 8 &&

            (avctx->dct_algo == FF_DCT_AUTO ||

             avctx->dct_algo == FF_DCT_ALTIVEC)) {

            c->fdct = ff_fdct_altivec;

        }

#endif //CONFIG_ENCODERS

        if (avctx->bits_per_raw_sample <= 8) {

            if ((avctx->idct_algo == FF_IDCT_AUTO) ||

                (avctx->idct_algo == FF_IDCT_ALTIVEC)) {

                c->idct_put = ff_idct_put_altivec;

                c->idct_add = ff_idct_add_altivec;

                c->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

            }

        }

    }

#endif /* HAVE_ALTIVEC */

}


static IOMMUTLBEntry pbm_translate_iommu(MemoryRegion *iommu, hwaddr addr,

                                         bool is_write)

{

    IOMMUState *is = container_of(iommu, IOMMUState, iommu);

    hwaddr baseaddr, offset;

    uint64_t tte;

    uint32_t tsbsize;

    IOMMUTLBEntry ret = {

        .target_as = &address_space_memory,

        .iova = 0,

        .translated_addr = 0,

        .addr_mask = ~(hwaddr)0,

        .perm = IOMMU_NONE,

    };

    if (!(is->regs[IOMMU_CTRL >> 3] & IOMMU_CTRL_MMU_EN)) {

        /* IOMMU disabled, passthrough using standard 8K page */

        ret.iova = addr & IOMMU_PAGE_MASK_8K;

        ret.translated_addr = addr;

        ret.addr_mask = IOMMU_PAGE_MASK_8K;

        ret.perm = IOMMU_RW;

        return ret;

    }

    baseaddr = is->regs[IOMMU_BASE >> 3];

    tsbsize = (is->regs[IOMMU_CTRL >> 3] >> IOMMU_CTRL_TSB_SHIFT) & 0x7;

    if (is->regs[IOMMU_CTRL >> 3] & IOMMU_CTRL_TBW_SIZE) {

        /* 64K */

        switch (tsbsize) {

        case 0:

            offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_64M) >> 13;

            break;

        case 1:

            offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_128M) >> 13;

            break;

        case 2:

            offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_256M) >> 13;

            break;

        case 3:

            offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_512M) >> 13;

            break;

        case 4:

            offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_1G) >> 13;

            break;

        case 5:

            offset = (addr & IOMMU_TSB_64K_OFFSET_MASK_2G) >> 13;

            break;

        default:

            /* Not implemented, error */

            return ret;

        }

    } else {

        /* 8K */

        switch (tsbsize) {

        case 0:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_8M) >> 10;

            break;

        case 1:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_16M) >> 10;

            break;

        case 2:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_32M) >> 10;

            break;

        case 3:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_64M) >> 10;

            break;

        case 4:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_128M) >> 10;

            break;

        case 5:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_256M) >> 10;

            break;

        case 6:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_512M) >> 10;

            break;

        case 7:

            offset = (addr & IOMMU_TSB_8K_OFFSET_MASK_1G) >> 10;

            break;

        }

    }

    tte = address_space_ldq_be(&address_space_memory, baseaddr + offset,

                               MEMTXATTRS_UNSPECIFIED, NULL);

    if (!(tte & IOMMU_TTE_DATA_V)) {

        /* Invalid mapping */

        return ret;

    }

    if (tte & IOMMU_TTE_DATA_W) {

        /* Writeable */

        ret.perm = IOMMU_RW;

    } else {

        ret.perm = IOMMU_RO;

    }

    /* Extract phys */

    if (tte & IOMMU_TTE_DATA_SIZE) {

        /* 64K */

        ret.iova = addr & IOMMU_PAGE_MASK_64K;

        ret.translated_addr = tte & IOMMU_TTE_PHYS_MASK_64K;

        ret.addr_mask = (IOMMU_PAGE_SIZE_64K - 1);

    } else {

        /* 8K */

        ret.iova = addr & IOMMU_PAGE_MASK_8K;

        ret.translated_addr = tte & IOMMU_TTE_PHYS_MASK_8K;

        ret.addr_mask = (IOMMU_PAGE_SIZE_8K - 1);

    }

    return ret;

}


static void coroutine_fn mirror_iteration(MirrorBlockJob *s)

{

    BlockDriverState *source = s->common.bs;

    int nb_sectors, sectors_per_chunk, nb_chunks;

    int64_t end, sector_num, next_chunk, next_sector, hbitmap_next_sector;

    MirrorOp *op;

    s->sector_num = hbitmap_iter_next(&s->hbi);

    if (s->sector_num < 0) {

        bdrv_dirty_iter_init(source, s->dirty_bitmap, &s->hbi);

        s->sector_num = hbitmap_iter_next(&s->hbi);

        trace_mirror_restart_iter(s,

                                  bdrv_get_dirty_count(source, s->dirty_bitmap));

        assert(s->sector_num >= 0);

    }

    hbitmap_next_sector = s->sector_num;

    sector_num = s->sector_num;

    sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;

    end = s->common.len >> BDRV_SECTOR_BITS;

    /* Extend the QEMUIOVector to include all adjacent blocks that will

     * be copied in this operation.

     *

     * We have to do this if we have no backing file yet in the destination,

     * and the cluster size is very large.  Then we need to do COW ourselves.

     * The first time a cluster is copied, copy it entirely.  Note that,

     * because both the granularity and the cluster size are powers of two,

     * the number of sectors to copy cannot exceed one cluster.

     *

     * We also want to extend the QEMUIOVector to include more adjacent

     * dirty blocks if possible, to limit the number of I/O operations and

     * run efficiently even with a small granularity.

     */

    nb_chunks = 0;

    nb_sectors = 0;

    next_sector = sector_num;

    next_chunk = sector_num / sectors_per_chunk;

    /* Wait for I/O to this cluster (from a previous iteration) to be done.  */

    while (test_bit(next_chunk, s->in_flight_bitmap)) {

        trace_mirror_yield_in_flight(s, sector_num, s->in_flight);

        qemu_coroutine_yield();

    }

    do {

        int added_sectors, added_chunks;

        if (!bdrv_get_dirty(source, s->dirty_bitmap, next_sector) ||

            test_bit(next_chunk, s->in_flight_bitmap)) {

            assert(nb_sectors > 0);

            break;

        }

        added_sectors = sectors_per_chunk;

        if (s->cow_bitmap && !test_bit(next_chunk, s->cow_bitmap)) {

            bdrv_round_to_clusters(s->target,

                                   next_sector, added_sectors,

                                   &next_sector, &added_sectors);

            /* On the first iteration, the rounding may make us copy

             * sectors before the first dirty one.

             */

            if (next_sector < sector_num) {

                assert(nb_sectors == 0);

                sector_num = next_sector;

                next_chunk = next_sector / sectors_per_chunk;

            }

        }

        added_sectors = MIN(added_sectors, end - (sector_num + nb_sectors));

        added_chunks = (added_sectors + sectors_per_chunk - 1) / sectors_per_chunk;

        /* When doing COW, it may happen that there is not enough space for

         * a full cluster.  Wait if that is the case.

         */

        while (nb_chunks == 0 && s->buf_free_count < added_chunks) {

            trace_mirror_yield_buf_busy(s, nb_chunks, s->in_flight);

            qemu_coroutine_yield();

        }

        if (s->buf_free_count < nb_chunks + added_chunks) {

            trace_mirror_break_buf_busy(s, nb_chunks, s->in_flight);

            break;

        }

        /* We have enough free space to copy these sectors.  */

        bitmap_set(s->in_flight_bitmap, next_chunk, added_chunks);

        nb_sectors += added_sectors;

        nb_chunks += added_chunks;

        next_sector += added_sectors;

        next_chunk += added_chunks;

    } while (next_sector < end);

    /* Allocate a MirrorOp that is used as an AIO callback.  */

    op = g_slice_new(MirrorOp);

    op->s = s;

    op->sector_num = sector_num;

    op->nb_sectors = nb_sectors;

    /* Now make a QEMUIOVector taking enough granularity-sized chunks

     * from s->buf_free.

     */

    qemu_iovec_init(&op->qiov, nb_chunks);

    next_sector = sector_num;

    while (nb_chunks-- > 0) {

        MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);

        QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);

        s->buf_free_count--;

        qemu_iovec_add(&op->qiov, buf, s->granularity);

        /* Advance the HBitmapIter in parallel, so that we do not examine

         * the same sector twice.

         */

        if (next_sector > hbitmap_next_sector

            && bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {

            hbitmap_next_sector = hbitmap_iter_next(&s->hbi);

        }

        next_sector += sectors_per_chunk;

    }

    bdrv_reset_dirty(source, sector_num, nb_sectors);

    /* Copy the dirty cluster.  */

    s->in_flight++;

    trace_mirror_one_iteration(s, sector_num, nb_sectors);

    bdrv_aio_readv(source, sector_num, &op->qiov, nb_sectors,

                   mirror_read_complete, op);

}


static int s390_cpu_initial_reset(S390CPU *cpu)

{

    CPUState *cs = CPU(cpu);

    CPUS390XState *env = &cpu->env;

    int i;

    s390_del_running_cpu(cpu);

    if (kvm_vcpu_ioctl(cs, KVM_S390_INITIAL_RESET, NULL) < 0) {

        perror("cannot init reset vcpu");

    }

    /* Manually zero out all registers */

    cpu_synchronize_state(cs);

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

        env->regs[i] = 0;

    }

    DPRINTF("DONE: SIGP initial reset: %p\n", env);

    return 0;

}


void virtio_setup_block(struct subchannel_id schid)

{

    struct vq_info_block info;

    struct vq_config_block config = {};

    virtio_reset(schid);

    config.index = 0;

    if (run_ccw(schid, CCW_CMD_READ_VQ_CONF, &config, sizeof(config))) {

        virtio_panic("Could not get block device configuration\n");

    }

    vring_init(&block, config.num, (void*)(100 * 1024 * 1024),

               KVM_S390_VIRTIO_RING_ALIGN);

    info.queue = (100ULL * 1024ULL* 1024ULL);

    info.align = KVM_S390_VIRTIO_RING_ALIGN;

    info.index = 0;

    info.num = config.num;

    block.schid = schid;

    if (!run_ccw(schid, CCW_CMD_SET_VQ, &info, sizeof(info))) {

        virtio_set_status(schid, VIRTIO_CONFIG_S_DRIVER_OK);

    }

}


static int v9fs_do_open2(V9fsState *s, V9fsString *path, int flags, mode_t mode)

{

    return s->ops->open2(&s->ctx, path->data, flags, mode);

}


udp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,

           u_int lport, int flags)

{

	struct sockaddr_in addr;

	struct socket *so;

	socklen_t addrlen = sizeof(struct sockaddr_in);

	so = socreate(slirp);

	if (!so) {

	    return NULL;

	}

	so->s = qemu_socket(AF_INET,SOCK_DGRAM,0);

	so->so_expire = curtime + SO_EXPIRE;

	insque(so, &slirp->udb);

	addr.sin_family = AF_INET;

	addr.sin_addr.s_addr = haddr;

	addr.sin_port = hport;

	if (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {

		udp_detach(so);

		return NULL;

	}

	socket_set_fast_reuse(so->s);

	getsockname(so->s,(struct sockaddr *)&addr,&addrlen);

	so->so_ffamily = AF_INET;

	so->so_fport = addr.sin_port;

	if (addr.sin_addr.s_addr == 0 ||

	    addr.sin_addr.s_addr == loopback_addr.s_addr) {

	   so->so_faddr = slirp->vhost_addr;

	} else {

	   so->so_faddr = addr.sin_addr;

	}

	so->so_lfamily = AF_INET;

	so->so_lport = lport;

	so->so_laddr.s_addr = laddr;

	if (flags != SS_FACCEPTONCE)

	   so->so_expire = 0;

	so->so_state &= SS_PERSISTENT_MASK;

	so->so_state |= SS_ISFCONNECTED | flags;

	return so;

}


blkdebug_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

                    QEMUIOVector *qiov, int flags)

{

    BDRVBlkdebugState *s = bs->opaque;

    BlkdebugRule *rule = NULL;

    /* Sanity check block layer guarantees */

    assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));

    assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));

    if (bs->bl.max_transfer) {

        assert(bytes <= bs->bl.max_transfer);

    }

    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {

        uint64_t inject_offset = rule->options.inject.offset;

        if (inject_offset == -1 ||

            (inject_offset >= offset && inject_offset < offset + bytes))

        {

            break;

        }

    }

    if (rule && rule->options.inject.error) {

        return inject_error(bs, rule);

    }

    return bdrv_co_pwritev(bs->file, offset, bytes, qiov, flags);

}


static void test_visitor_out_struct_errors(TestOutputVisitorData *data,

                                           const void *unused)

{

    EnumOne bad_values[] = { ENUM_ONE_MAX, -1 };

    UserDefZero b;

    UserDefOne u = { .base = &b }, *pu = &u;

    Error *err;

    int i;

    for (i = 0; i < ARRAY_SIZE(bad_values) ; i++) {

        err = NULL;

        u.has_enum1 = true;

        u.enum1 = bad_values[i];

        visit_type_UserDefOne(data->ov, &pu, "unused", &err);

        g_assert(err);

        error_free(err);

    }

}


static HEVCFrame *find_ref_idx(HEVCContext *s, int poc)

{

    int i;

    int LtMask = (1 << s->sps->log2_max_poc_lsb) - 1;

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

        HEVCFrame *ref = &s->DPB[i];

        if (ref->frame->buf[0] && (ref->sequence == s->seq_decode)) {

            if ((ref->poc & LtMask) == poc)

                return ref;

        }

    }

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

        HEVCFrame *ref = &s->DPB[i];

        if (ref->frame->buf[0] && ref->sequence == s->seq_decode) {

            if (ref->poc == poc || (ref->poc & LtMask) == poc)

                return ref;

        }

    }

    av_log(s->avctx, AV_LOG_ERROR,

           "Could not find ref with POC %d\n", poc);

    return NULL;

}


void timer_free(QEMUTimer *ts)

{

    g_free(ts);

}


int do_snapshot_blkdev(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

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

    const char *filename = qdict_get_try_str(qdict, "snapshot-file");

    const char *format = qdict_get_try_str(qdict, "format");

    BlockDriverState *bs;

    BlockDriver *drv, *old_drv, *proto_drv;

    int ret = 0;

    int flags;

    char old_filename[1024];

    if (!filename) {

        qerror_report(QERR_MISSING_PARAMETER, "snapshot-file");

        ret = -1;

        goto out;

    }

    bs = bdrv_find(device);

    if (!bs) {

        qerror_report(QERR_DEVICE_NOT_FOUND, device);

        ret = -1;

        goto out;

    }

    pstrcpy(old_filename, sizeof(old_filename), bs->filename);

    old_drv = bs->drv;

    flags = bs->open_flags;

    if (!format) {

        format = "qcow2";

    }

    drv = bdrv_find_format(format);

    if (!drv) {

        qerror_report(QERR_INVALID_BLOCK_FORMAT, format);

        ret = -1;

        goto out;

    }

    proto_drv = bdrv_find_protocol(filename);

    if (!proto_drv) {

        qerror_report(QERR_INVALID_BLOCK_FORMAT, format);

        ret = -1;

        goto out;

    }

    ret = bdrv_img_create(filename, format, bs->filename,

                          bs->drv->format_name, NULL, -1, flags);

    if (ret) {

        goto out;

    }

    qemu_aio_flush();

    bdrv_flush(bs);

    bdrv_close(bs);

    ret = bdrv_open(bs, filename, flags, drv);

    /*

     * If reopening the image file we just created fails, fall back

     * and try to re-open the original image. If that fails too, we

     * are in serious trouble.

     */

    if (ret != 0) {

        ret = bdrv_open(bs, old_filename, flags, old_drv);

        if (ret != 0) {

            qerror_report(QERR_OPEN_FILE_FAILED, old_filename);

        } else {

            qerror_report(QERR_OPEN_FILE_FAILED, filename);

        }

    }

out:

    if (ret) {

        ret = -1;

    }

    return ret;

}


static void breakpoint_invalidate(CPUState *env, target_ulong pc)

{

    target_ulong phys_addr;

    phys_addr = cpu_get_phys_page_debug(env, pc);

    tb_invalidate_phys_page_range(phys_addr, phys_addr + 1, 0);

}


static void omap_ppm_save(const char *filename, uint8_t *data,

                    int w, int h, int linesize, Error **errp)

{

    FILE *f;

    uint8_t *d, *d1;

    unsigned int v;

    int ret, y, x, bpp;

    f = fopen(filename, "wb");

    if (!f) {

        error_setg(errp, "failed to open file '%s': %s", filename,

                   strerror(errno));

        return;

    }

    ret = fprintf(f, "P6\n%d %d\n%d\n", w, h, 255);

    if (ret < 0) {

        goto write_err;

    }

    d1 = data;

    bpp = linesize / w;

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

        d = d1;

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

            v = *(uint32_t *) d;

            switch (bpp) {

            case 2:

                ret = fputc((v >> 8) & 0xf8, f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc((v >> 3) & 0xfc, f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc((v << 3) & 0xf8, f);

                if (ret == EOF) {

                    goto write_err;

                }

                break;

            case 3:

            case 4:

            default:

                ret = fputc((v >> 16) & 0xff, f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc((v >> 8) & 0xff, f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc((v) & 0xff, f);

                if (ret == EOF) {

                    goto write_err;

                }

                break;

            }

            d += bpp;

        }

        d1 += linesize;

    }

out:

    fclose(f);

    return;

write_err:

    error_setg(errp, "failed to write to file '%s': %s", filename,

               strerror(errno));

    unlink(filename);

    goto out;

}


static uint64_t unassigned_mem_read(void *opaque, hwaddr addr,

                                    unsigned size)

{

#ifdef DEBUG_UNASSIGNED

    printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);

#endif

    if (current_cpu != NULL) {

        cpu_unassigned_access(current_cpu, addr, false, false, 0, size);

    }

    return -1ULL;

}


void qemu_set_cloexec(int fd)

{

    int f;

    f = fcntl(fd, F_GETFD);

    fcntl(fd, F_SETFD, f | FD_CLOEXEC);

}


static int netmap_can_send(void *opaque)

{

    NetmapState *s = opaque;

    return qemu_can_send_packet(&s->nc);

}


static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,

                                         unsigned long *bitmap)

{

    unsigned int i, j;

    unsigned long page_number, c;

    hwaddr addr, addr1;

    unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;

    unsigned long hpratio = getpagesize() / TARGET_PAGE_SIZE;

    /*

     * bitmap-traveling is faster than memory-traveling (for addr...)

     * especially when most of the memory is not dirty.

     */

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

        if (bitmap[i] != 0) {

            c = leul_to_cpu(bitmap[i]);

            do {

                j = ffsl(c) - 1;

                c &= ~(1ul << j);

                page_number = (i * HOST_LONG_BITS + j) * hpratio;

                addr1 = page_number * TARGET_PAGE_SIZE;

                addr = section->offset_within_region + addr1;

                memory_region_set_dirty(section->mr, addr,

                                        TARGET_PAGE_SIZE * hpratio);

            } while (c != 0);

        }

    }

    return 0;

}


static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){

    MpegEncContext * const s = &h->s;

    static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};

    int level[16];

    int zeros_left, coeff_num, coeff_token, total_coeff, i, j, trailing_ones, run_before;

    //FIXME put trailing_onex into the context

    if(n == CHROMA_DC_BLOCK_INDEX){

        coeff_token= get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);

        total_coeff= coeff_token>>2;

    }else{

        if(n == LUMA_DC_BLOCK_INDEX){

            total_coeff= pred_non_zero_count(h, 0);

            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);

            total_coeff= coeff_token>>2;

        }else{

            total_coeff= pred_non_zero_count(h, n);

            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);

            total_coeff= coeff_token>>2;

            h->non_zero_count_cache[ scan8[n] ]= total_coeff;

        }

    }

    //FIXME set last_non_zero?

    if(total_coeff==0)

        return 0;

    if(total_coeff > (unsigned)max_coeff) {

        av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);

        return -1;

    }

    trailing_ones= coeff_token&3;

    tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);

    assert(total_coeff<=16);

    i = show_bits(gb, 3);

    skip_bits(gb, trailing_ones);

    level[0] = 1-((i&4)>>1);

    level[1] = 1-((i&2)   );

    level[2] = 1-((i&1)<<1);

    if(trailing_ones<total_coeff) {

        int mask, prefix;

        int suffix_length = total_coeff > 10 & trailing_ones < 3;

        int bitsi= show_bits(gb, LEVEL_TAB_BITS);

        int level_code= cavlc_level_tab[suffix_length][bitsi][0];

        skip_bits(gb, cavlc_level_tab[suffix_length][bitsi][1]);

        if(level_code >= 100){

            prefix= level_code - 100;

            if(prefix == LEVEL_TAB_BITS)

                prefix += get_level_prefix(gb);

            //first coefficient has suffix_length equal to 0 or 1

            if(prefix<14){ //FIXME try to build a large unified VLC table for all this

                if(suffix_length)

                    level_code= (prefix<<1) + get_bits1(gb); //part

                else

                    level_code= prefix; //part

            }else if(prefix==14){

                if(suffix_length)

                    level_code= (prefix<<1) + get_bits1(gb); //part

                else

                    level_code= prefix + get_bits(gb, 4); //part

            }else{

                level_code= 30 + get_bits(gb, prefix-3); //part

                if(prefix>=16)

                    level_code += (1<<(prefix-3))-4096;

            }

            if(trailing_ones < 3) level_code += 2;

            suffix_length = 2;

            mask= -(level_code&1);

            level[trailing_ones]= (((2+level_code)>>1) ^ mask) - mask;

        }else{

            level_code += ((level_code>>31)|1) & -(trailing_ones < 3);

            suffix_length = 1 + (level_code + 3U > 6U);

            level[trailing_ones]= level_code;

        }

        //remaining coefficients have suffix_length > 0

        for(i=trailing_ones+1;i<total_coeff;i++) {

            static const unsigned int suffix_limit[7] = {0,3,6,12,24,48,INT_MAX };

            int bitsi= show_bits(gb, LEVEL_TAB_BITS);

            level_code= cavlc_level_tab[suffix_length][bitsi][0];

            skip_bits(gb, cavlc_level_tab[suffix_length][bitsi][1]);

            if(level_code >= 100){

                prefix= level_code - 100;

                if(prefix == LEVEL_TAB_BITS){

                    prefix += get_level_prefix(gb);

                }

                if(prefix<15){

                    level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);

                }else{

                    level_code = (15<<suffix_length) + get_bits(gb, prefix-3);

                    if(prefix>=16)

                        level_code += (1<<(prefix-3))-4096;

                }

                mask= -(level_code&1);

                level_code= (((2+level_code)>>1) ^ mask) - mask;

            }

            level[i]= level_code;

            suffix_length+= suffix_limit[suffix_length] + level_code > 2U*suffix_limit[suffix_length];

        }

    }

    if(total_coeff == max_coeff)

        zeros_left=0;

    else{

        if(n == CHROMA_DC_BLOCK_INDEX)

            zeros_left= get_vlc2(gb, (chroma_dc_total_zeros_vlc-1)[ total_coeff ].table, CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);

        else

            zeros_left= get_vlc2(gb, (total_zeros_vlc-1)[ total_coeff ].table, TOTAL_ZEROS_VLC_BITS, 1);

    }

    coeff_num = zeros_left + total_coeff - 1;

    j = scantable[coeff_num];

    if(n > 24){

        block[j] = level[0];

        for(i=1;i<total_coeff;i++) {

            if(zeros_left <= 0)

                run_before = 0;

            else if(zeros_left < 7){

                run_before= get_vlc2(gb, (run_vlc-1)[zeros_left].table, RUN_VLC_BITS, 1);

            }else{

                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);

            }

            zeros_left -= run_before;

            coeff_num -= 1 + run_before;

            j= scantable[ coeff_num ];

            block[j]= level[i];

        }

    }else{

        block[j] = (level[0] * qmul[j] + 32)>>6;

        for(i=1;i<total_coeff;i++) {

            if(zeros_left <= 0)

                run_before = 0;

            else if(zeros_left < 7){

                run_before= get_vlc2(gb, (run_vlc-1)[zeros_left].table, RUN_VLC_BITS, 1);

            }else{

                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2);

            }

            zeros_left -= run_before;

            coeff_num -= 1 + run_before;

            j= scantable[ coeff_num ];

            block[j]= (level[i] * qmul[j] + 32)>>6;

        }

    }

    if(zeros_left<0){

        av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);

        return -1;

    }

    return 0;

}


static void ccw_machine_class_init(ObjectClass *oc, void *data)

{

    MachineClass *mc = MACHINE_CLASS(oc);

    NMIClass *nc = NMI_CLASS(oc);

    mc->name = "s390-ccw-virtio";

    mc->alias = "s390-ccw";

    mc->desc = "VirtIO-ccw based S390 machine";

    mc->init = ccw_init;

    mc->block_default_type = IF_VIRTIO;

    mc->no_cdrom = 1;

    mc->no_floppy = 1;

    mc->no_serial = 1;

    mc->no_parallel = 1;

    mc->no_sdcard = 1;

    mc->use_sclp = 1;

    mc->max_cpus = 255;

    mc->is_default = 1;

    nc->nmi_monitor_handler = s390_nmi;

}


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

{

    uint32_t *p = qdev_get_prop_ptr(dev, prop);

    return snprintf(dest, len, (*p & qdev_get_prop_mask(prop)) ? "on" : "off");

}


static char *pxb_host_ofw_unit_address(const SysBusDevice *dev)

{

    const PCIHostState *pxb_host;

    const PCIBus *pxb_bus;

    const PXBDev *pxb_dev;

    int position;

    const DeviceState *pxb_dev_base;

    const PCIHostState *main_host;

    const SysBusDevice *main_host_sbd;

    pxb_host = PCI_HOST_BRIDGE(dev);

    pxb_bus = pxb_host->bus;

    pxb_dev = PXB_DEV(pxb_bus->parent_dev);

    position = g_list_index(pxb_dev_list, pxb_dev);

    assert(position >= 0);

    pxb_dev_base = DEVICE(pxb_dev);

    main_host = PCI_HOST_BRIDGE(pxb_dev_base->parent_bus->parent);

    main_host_sbd = SYS_BUS_DEVICE(main_host);

    if (main_host_sbd->num_mmio > 0) {

        return g_strdup_printf(TARGET_FMT_plx ",%x",

                               main_host_sbd->mmio[0].addr, position + 1);

    }

    if (main_host_sbd->num_pio > 0) {

        return g_strdup_printf("i%04x,%x",

                               main_host_sbd->pio[0], position + 1);

    }

    return NULL;

}


static int openfile(char *name, int flags, QDict *opts)

{

    Error *local_err = NULL;

    if (qemuio_blk) {

        fprintf(stderr, "file open already, try 'help close'\n");

        QDECREF(opts);

        return 1;

    }

    qemuio_blk = blk_new_open("hda", name, NULL, opts, flags, &local_err);

    if (!qemuio_blk) {

        fprintf(stderr, "%s: can't open%s%s: %s\n", progname,

                name ? " device " : "", name ?: "",

                error_get_pretty(local_err));

        error_free(local_err);

        return 1;

    }

    bs = blk_bs(qemuio_blk);

    if (bdrv_is_encrypted(bs)) {

        char password[256];

        printf("Disk image '%s' is encrypted.\n", name);

        if (qemu_read_password(password, sizeof(password)) < 0) {

            error_report("No password given");

            goto error;

        }

        if (bdrv_set_key(bs, password) < 0) {

            error_report("invalid password");

            goto error;

        }

    }

    return 0;

 error:

    blk_unref(qemuio_blk);

    qemuio_blk = NULL;

    return 1;

}


static void calc_slice_sizes(VC2EncContext *s)

{

    int slice_x, slice_y;

    SliceArgs *enc_args = s->slice_args;

    for (slice_y = 0; slice_y < s->num_y; slice_y++) {

        for (slice_x = 0; slice_x < s->num_x; slice_x++) {

            SliceArgs *args = &enc_args[s->num_x*slice_y + slice_x];

            args->ctx = s;

            args->x = slice_x;

            args->y = slice_y;

            args->bits_ceil = s->slice_max_bytes << 3;

            args->bits_floor = s->slice_min_bytes << 3;

            memset(args->cache, 0, MAX_QUANT_INDEX*sizeof(*args->cache));

        }

    }

    /* Determine quantization indices and bytes per slice */

    s->avctx->execute(s->avctx, rate_control, enc_args, NULL, s->num_x*s->num_y,

                      sizeof(SliceArgs));

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,

                                              int *got_picture_ptr,

                                              const AVPacket *avpkt)

{

    AVCodecInternal *avci = avctx->internal;

    int ret;

    // copy to ensure we do not change avpkt

    AVPacket tmp = *avpkt;

    if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");

    }

    *got_picture_ptr = 0;

    if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))

    avcodec_get_frame_defaults(picture);

    if (!avctx->refcounted_frames)

        av_frame_unref(&avci->to_free);

    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {

        int did_split = av_packet_split_side_data(&tmp);

        apply_param_change(avctx, &tmp);

        avctx->pkt = &tmp;

        if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)

            ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,

                                         &tmp);

        else {

            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,

                                       &tmp);

            picture->pkt_dts = avpkt->dts;

            if(!avctx->has_b_frames){

                av_frame_set_pkt_pos(picture, avpkt->pos);

            }

            //FIXME these should be under if(!avctx->has_b_frames)

            /* get_buffer is supposed to set frame parameters */

            if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {

                if (!picture->sample_aspect_ratio.num)    picture->sample_aspect_ratio = avctx->sample_aspect_ratio;

                if (!picture->width)                      picture->width               = avctx->width;

                if (!picture->height)                     picture->height              = avctx->height;

                if (picture->format == AV_PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;

            }

        }

        add_metadata_from_side_data(avctx, picture);

        emms_c(); //needed to avoid an emms_c() call before every return;

        avctx->pkt = NULL;

        if (did_split) {

            ff_packet_free_side_data(&tmp);

            if(ret == tmp.size)

                ret = avpkt->size;

        }

        if (ret < 0 && picture->data[0])

            av_frame_unref(picture);

        if (*got_picture_ptr) {

            if (!avctx->refcounted_frames) {

                avci->to_free = *picture;

                avci->to_free.extended_data = avci->to_free.data;

                memset(picture->buf, 0, sizeof(picture->buf));

            }

            avctx->frame_number++;

            av_frame_set_best_effort_timestamp(picture,

                                               guess_correct_pts(avctx,

                                                                 picture->pkt_pts,

                                                                 picture->pkt_dts));

        }

    } else

        ret = 0;

    /* many decoders assign whole AVFrames, thus overwriting extended_data;

     * make sure it's set correctly */

    picture->extended_data = picture->data;

    return ret;

}


static int rdma_delete_block(RDMAContext *rdma, RDMALocalBlock *block)

{

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    RDMALocalBlock *old = local->block;

    int x;

    if (rdma->blockmap) {

        g_hash_table_remove(rdma->blockmap, (void *)(uintptr_t)block->offset);

    }

    if (block->pmr) {

        int j;

        for (j = 0; j < block->nb_chunks; j++) {

            if (!block->pmr[j]) {

                continue;

            }

            ibv_dereg_mr(block->pmr[j]);

            rdma->total_registrations--;

        }

        g_free(block->pmr);

        block->pmr = NULL;

    }

    if (block->mr) {

        ibv_dereg_mr(block->mr);

        rdma->total_registrations--;

        block->mr = NULL;

    }

    g_free(block->transit_bitmap);

    block->transit_bitmap = NULL;

    g_free(block->unregister_bitmap);

    block->unregister_bitmap = NULL;

    g_free(block->remote_keys);

    block->remote_keys = NULL;

    g_free(block->block_name);

    block->block_name = NULL;

    if (rdma->blockmap) {

        for (x = 0; x < local->nb_blocks; x++) {

            g_hash_table_remove(rdma->blockmap,

                                (void *)(uintptr_t)old[x].offset);

        }

    }

    if (local->nb_blocks > 1) {

        local->block = g_malloc0(sizeof(RDMALocalBlock) *

                                    (local->nb_blocks - 1));

        if (block->index) {

            memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);

        }

        if (block->index < (local->nb_blocks - 1)) {

            memcpy(local->block + block->index, old + (block->index + 1),

                sizeof(RDMALocalBlock) *

                    (local->nb_blocks - (block->index + 1)));

        }

    } else {

        assert(block == local->block);

        local->block = NULL;

    }

    trace_rdma_delete_block(block, (uintptr_t)block->local_host_addr,

                           block->offset, block->length,

                            (uintptr_t)(block->local_host_addr + block->length),

                           BITS_TO_LONGS(block->nb_chunks) *

                               sizeof(unsigned long) * 8, block->nb_chunks);

    g_free(old);

    local->nb_blocks--;

    if (local->nb_blocks && rdma->blockmap) {

        for (x = 0; x < local->nb_blocks; x++) {

            g_hash_table_insert(rdma->blockmap,

                                (void *)(uintptr_t)local->block[x].offset,

                                &local->block[x]);

        }

    }

    return 0;

}


static inline void mpeg4_encode_dc(PutBitContext * s, int level, int n)

{

#if 1

    level+=256;

    if (n < 4) {

        /* luminance */

        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);

    } else {

        /* chrominance */

        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);

    }

#else

    int size, v;

    /* find number of bits */

    size = 0;

    v = abs(level);

    while (v) {

        v >>= 1;

        size++;

    }

    if (n < 4) {

        /* luminance */

        put_bits(&s->pb, DCtab_lum[size][1], DCtab_lum[size][0]);

    } else {

        /* chrominance */

        put_bits(&s->pb, DCtab_chrom[size][1], DCtab_chrom[size][0]);

    }

    /* encode remaining bits */

    if (size > 0) {

        if (level < 0)

            level = (-level) ^ ((1 << size) - 1);

        put_bits(&s->pb, size, level);

        if (size > 8)

            put_bits(&s->pb, 1, 1);

    }

#endif

}


static int pick_formats(AVFilterGraph *graph)

{

    int i, j, ret;

    int change;

    do{

        change = 0;

        for (i = 0; i < graph->filter_count; i++) {

            AVFilterContext *filter = graph->filters[i];

            if (filter->nb_inputs){

                for (j = 0; j < filter->nb_inputs; j++){

                    if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->format_count == 1) {

                        pick_format(filter->inputs[j], NULL);

                        change = 1;

                    }

                }

            }

            if (filter->nb_outputs){

                for (j = 0; j < filter->nb_outputs; j++){

                    if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->format_count == 1) {

                        pick_format(filter->outputs[j], NULL);

                        change = 1;

                    }

                }

            }

            if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {

                for (j = 0; j < filter->nb_outputs; j++) {

                    if(filter->outputs[j]->format<0) {

                        pick_format(filter->outputs[j], filter->inputs[0]);

                        change = 1;

                    }

                }

            }

        }

    }while(change);

    for (i = 0; i < graph->filter_count; i++) {

        AVFilterContext *filter = graph->filters[i];

        for (j = 0; j < filter->nb_inputs; j++)

            if ((ret = pick_format(filter->inputs[j], NULL)) < 0)

                return ret;

        for (j = 0; j < filter->nb_outputs; j++)

            if ((ret = pick_format(filter->outputs[j], NULL)) < 0)

                return ret;

    }

    return 0;

}


ff_yuv2packedX_altivec(SwsContext *c, const int16_t *lumFilter,

                       const int16_t **lumSrc, int lumFilterSize,

                       const int16_t *chrFilter, const int16_t **chrUSrc,

                       const int16_t **chrVSrc, int chrFilterSize,

                       const int16_t **alpSrc, uint8_t *dest,

                       int dstW, int dstY)

{

    int i,j;

    vector signed short X,X0,X1,Y0,U0,V0,Y1,U1,V1,U,V;

    vector signed short R0,G0,B0,R1,G1,B1;

    vector unsigned char R,G,B;

    vector unsigned char *out,*nout;

    vector signed short   RND = vec_splat_s16(1<<3);

    vector unsigned short SCL = vec_splat_u16(4);

    DECLARE_ALIGNED(16, unsigned int, scratch)[16];

    vector signed short *YCoeffs, *CCoeffs;

    YCoeffs = c->vYCoeffsBank+dstY*lumFilterSize;

    CCoeffs = c->vCCoeffsBank+dstY*chrFilterSize;

    out = (vector unsigned char *)dest;

    for (i=0; i<dstW; i+=16) {

        Y0 = RND;

        Y1 = RND;

        /* extract 16 coeffs from lumSrc */

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

            X0 = vec_ld (0,  &lumSrc[j][i]);

            X1 = vec_ld (16, &lumSrc[j][i]);

            Y0 = vec_mradds (X0, YCoeffs[j], Y0);

            Y1 = vec_mradds (X1, YCoeffs[j], Y1);

        }

        U = RND;

        V = RND;

        /* extract 8 coeffs from U,V */

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

            X  = vec_ld (0, &chrUSrc[j][i/2]);

            U  = vec_mradds (X, CCoeffs[j], U);

            X  = vec_ld (0, &chrVSrc[j][i/2]);

            V  = vec_mradds (X, CCoeffs[j], V);

        }

        /* scale and clip signals */

        Y0 = vec_sra (Y0, SCL);

        Y1 = vec_sra (Y1, SCL);

        U  = vec_sra (U,  SCL);

        V  = vec_sra (V,  SCL);

        Y0 = vec_clip_s16 (Y0);

        Y1 = vec_clip_s16 (Y1);

        U  = vec_clip_s16 (U);

        V  = vec_clip_s16 (V);

        /* now we have

          Y0= y0 y1 y2 y3 y4 y5 y6 y7     Y1= y8 y9 y10 y11 y12 y13 y14 y15

          U= u0 u1 u2 u3 u4 u5 u6 u7      V= v0 v1 v2 v3 v4 v5 v6 v7

          Y0= y0 y1 y2 y3 y4 y5 y6 y7    Y1= y8 y9 y10 y11 y12 y13 y14 y15

          U0= u0 u0 u1 u1 u2 u2 u3 u3    U1= u4 u4 u5 u5 u6 u6 u7 u7

          V0= v0 v0 v1 v1 v2 v2 v3 v3    V1= v4 v4 v5 v5 v6 v6 v7 v7

        */

        U0 = vec_mergeh (U,U);

        V0 = vec_mergeh (V,V);

        U1 = vec_mergel (U,U);

        V1 = vec_mergel (V,V);

        cvtyuvtoRGB (c, Y0,U0,V0,&R0,&G0,&B0);

        cvtyuvtoRGB (c, Y1,U1,V1,&R1,&G1,&B1);

        R  = vec_packclp (R0,R1);

        G  = vec_packclp (G0,G1);

        B  = vec_packclp (B0,B1);

        switch(c->dstFormat) {

        case PIX_FMT_ABGR:  out_abgr  (R,G,B,out); break;

        case PIX_FMT_BGRA:  out_bgra  (R,G,B,out); break;

        case PIX_FMT_RGBA:  out_rgba  (R,G,B,out); break;

        case PIX_FMT_ARGB:  out_argb  (R,G,B,out); break;

        case PIX_FMT_RGB24: out_rgb24 (R,G,B,out); break;

        case PIX_FMT_BGR24: out_bgr24 (R,G,B,out); break;

        default:

            {

                /* If this is reached, the caller should have called yuv2packedXinC

                   instead. */

                static int printed_error_message;

                if (!printed_error_message) {

                    av_log(c, AV_LOG_ERROR, "altivec_yuv2packedX doesn't support %s output\n",

                           sws_format_name(c->dstFormat));

                    printed_error_message=1;

                }

                return;

            }

        }

    }

    if (i < dstW) {

        i -= 16;

        Y0 = RND;

        Y1 = RND;

        /* extract 16 coeffs from lumSrc */

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

            X0 = vec_ld (0,  &lumSrc[j][i]);

            X1 = vec_ld (16, &lumSrc[j][i]);

            Y0 = vec_mradds (X0, YCoeffs[j], Y0);

            Y1 = vec_mradds (X1, YCoeffs[j], Y1);

        }

        U = RND;

        V = RND;

        /* extract 8 coeffs from U,V */

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

            X  = vec_ld (0, &chrUSrc[j][i/2]);

            U  = vec_mradds (X, CCoeffs[j], U);

            X  = vec_ld (0, &chrVSrc[j][i/2]);

            V  = vec_mradds (X, CCoeffs[j], V);

        }

        /* scale and clip signals */

        Y0 = vec_sra (Y0, SCL);

        Y1 = vec_sra (Y1, SCL);

        U  = vec_sra (U,  SCL);

        V  = vec_sra (V,  SCL);

        Y0 = vec_clip_s16 (Y0);

        Y1 = vec_clip_s16 (Y1);

        U  = vec_clip_s16 (U);

        V  = vec_clip_s16 (V);

        /* now we have

           Y0= y0 y1 y2 y3 y4 y5 y6 y7     Y1= y8 y9 y10 y11 y12 y13 y14 y15

           U = u0 u1 u2 u3 u4 u5 u6 u7     V = v0 v1 v2 v3 v4 v5 v6 v7

           Y0= y0 y1 y2 y3 y4 y5 y6 y7    Y1= y8 y9 y10 y11 y12 y13 y14 y15

           U0= u0 u0 u1 u1 u2 u2 u3 u3    U1= u4 u4 u5 u5 u6 u6 u7 u7

           V0= v0 v0 v1 v1 v2 v2 v3 v3    V1= v4 v4 v5 v5 v6 v6 v7 v7

        */

        U0 = vec_mergeh (U,U);

        V0 = vec_mergeh (V,V);

        U1 = vec_mergel (U,U);

        V1 = vec_mergel (V,V);

        cvtyuvtoRGB (c, Y0,U0,V0,&R0,&G0,&B0);

        cvtyuvtoRGB (c, Y1,U1,V1,&R1,&G1,&B1);

        R  = vec_packclp (R0,R1);

        G  = vec_packclp (G0,G1);

        B  = vec_packclp (B0,B1);

        nout = (vector unsigned char *)scratch;

        switch(c->dstFormat) {

        case PIX_FMT_ABGR:  out_abgr  (R,G,B,nout); break;

        case PIX_FMT_BGRA:  out_bgra  (R,G,B,nout); break;

        case PIX_FMT_RGBA:  out_rgba  (R,G,B,nout); break;

        case PIX_FMT_ARGB:  out_argb  (R,G,B,nout); break;

        case PIX_FMT_RGB24: out_rgb24 (R,G,B,nout); break;

        case PIX_FMT_BGR24: out_bgr24 (R,G,B,nout); break;

        default:

            /* Unreachable, I think. */

            av_log(c, AV_LOG_ERROR, "altivec_yuv2packedX doesn't support %s output\n",

                   sws_format_name(c->dstFormat));

            return;

        }

        memcpy (&((uint32_t*)dest)[i], scratch, (dstW-i)/4);

    }

}


static void arm_gic_common_realize(DeviceState *dev, Error **errp)
{
    GICState *s = ARM_GIC_COMMON(dev);
    int num_irq = s->num_irq;
    if (s->num_cpu > GIC_NCPU) {
        error_setg(errp, "requested %u CPUs exceeds GIC maximum %d",
                   s->num_cpu, GIC_NCPU);
    s->num_irq += GIC_BASE_IRQ;
    if (s->num_irq > GIC_MAXIRQ) {
        error_setg(errp,
                   "requested %u interrupt lines exceeds GIC maximum %d",
                   num_irq, GIC_MAXIRQ);
    /* ITLinesNumber is represented as (N / 32) - 1 (see
     * gic_dist_readb) so this is an implementation imposed
     * restriction, not an architectural one:
     */
    if (s->num_irq < 32 || (s->num_irq % 32)) {
        error_setg(errp,
                   "%d interrupt lines unsupported: not divisible by 32",
                   num_irq);


static int lance_init(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    SysBusPCNetState *d = SYSBUS_PCNET(dev);

    PCNetState *s = &d->state;

    memory_region_init_io(&s->mmio, OBJECT(d), &lance_mem_ops, d,

                          "lance-mmio", 4);

    qdev_init_gpio_in(dev, parent_lance_reset, 1);

    sysbus_init_mmio(sbd, &s->mmio);

    sysbus_init_irq(sbd, &s->irq);

    s->phys_mem_read = ledma_memory_read;

    s->phys_mem_write = ledma_memory_write;

    return pcnet_common_init(dev, s, &net_lance_info);

}


static int vc9_decode_init(AVCodecContext *avctx)

{

    VC9Context *v = avctx->priv_data;

    MpegEncContext *s = &v->s;

    GetBitContext gb;

    if (!avctx->extradata_size || !avctx->extradata) return -1;

    avctx->pix_fmt = PIX_FMT_YUV420P;

    v->s.avctx = avctx;

    if(ff_h263_decode_init(avctx) < 0)

        return -1;

    if (vc9_init_common(v) < 0) return -1;

    avctx->coded_width = avctx->width;

    avctx->coded_height = avctx->height;

    if (avctx->codec_id == CODEC_ID_WMV3)

    {

        int count = 0;

        // looks like WMV3 has a sequence header stored in the extradata

        // advanced sequence header may be before the first frame

        // the last byte of the extradata is a version number, 1 for the

        // samples we can decode

        init_get_bits(&gb, avctx->extradata, avctx->extradata_size);

        decode_sequence_header(avctx, &gb);

        count = avctx->extradata_size*8 - get_bits_count(&gb);

        if (count>0)

        {

            av_log(avctx, AV_LOG_INFO, "Extra data: %i bits left, value: %X\n",

                   count, get_bits(&gb, count));

        }

        else

        {

            av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count);

        }

    }

    avctx->has_b_frames= !!(avctx->max_b_frames);

    s->mb_width = (avctx->coded_width+15)>>4;

    s->mb_height = (avctx->coded_height+15)>>4;

    /* Allocate mb bitplanes */

    if (alloc_bitplane(&v->mv_type_mb_plane, s->mb_width, s->mb_height) < 0)

        return -1;

    if (alloc_bitplane(&v->mv_type_mb_plane, s->mb_width, s->mb_height) < 0)

        return -1;

    if (alloc_bitplane(&v->skip_mb_plane, s->mb_width, s->mb_height) < 0)

        return -1;

    if (alloc_bitplane(&v->direct_mb_plane, s->mb_width, s->mb_height) < 0)

        return -1;

    /* For predictors */

    v->previous_line_cbpcy = (uint8_t *)av_malloc(s->mb_stride*4);

    if (!v->previous_line_cbpcy) return -1;

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        if (alloc_bitplane(&v->over_flags_plane, s->mb_width, s->mb_height) < 0)

            return -1;

        if (alloc_bitplane(&v->ac_pred_plane, s->mb_width, s->mb_height) < 0)

            return -1;

    }

#endif

    return 0;

    }


yuv2rgb48_2_c_template(SwsContext *c, const int32_t *buf[2],

                       const int32_t *ubuf[2], const int32_t *vbuf[2],

                       const int32_t *abuf[2], uint16_t *dest, int dstW,

                       int yalpha, int uvalpha, int y,

                       enum PixelFormat target)

{

    const int32_t *buf0  = buf[0],  *buf1  = buf[1],

                  *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1];

    int  yalpha1 = 4095 - yalpha;

    int uvalpha1 = 4095 - uvalpha;

    int i;

    for (i = 0; i < ((dstW + 1) >> 1); i++) {

        int Y1 = (buf0[i * 2]     * yalpha1  + buf1[i * 2]     * yalpha) >> 14;

        int Y2 = (buf0[i * 2 + 1] * yalpha1  + buf1[i * 2 + 1] * yalpha) >> 14;

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha + (-128 << 23)) >> 14;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha + (-128 << 23)) >> 14;

        int R, G, B;

        Y1 -= c->yuv2rgb_y_offset;

        Y2 -= c->yuv2rgb_y_offset;

        Y1 *= c->yuv2rgb_y_coeff;

        Y2 *= c->yuv2rgb_y_coeff;

        Y1 += 1 << 13;

        Y2 += 1 << 13;

        R = V * c->yuv2rgb_v2r_coeff;

        G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

        B =                            U * c->yuv2rgb_u2b_coeff;

        output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

        output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

        output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

        output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

        output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

        output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

        dest += 6;

    }

}


void memory_region_init_alias(MemoryRegion *mr,

                              Object *owner,

                              const char *name,

                              MemoryRegion *orig,

                              hwaddr offset,

                              uint64_t size)

{

    memory_region_init(mr, owner, name, size);

    memory_region_ref(orig);

    mr->destructor = memory_region_destructor_alias;

    mr->alias = orig;

    mr->alias_offset = offset;

}


static void monitor_protocol_event_handler(void *opaque)

{

    MonitorEventState *evstate = opaque;

    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    qemu_mutex_lock(&monitor_event_state_lock);

    trace_monitor_protocol_event_handler(evstate->event,

                                         evstate->data,

                                         evstate->last,

                                         now);

    if (evstate->data) {

        monitor_protocol_event_emit(evstate->event, evstate->data);

        qobject_decref(evstate->data);

        evstate->data = NULL;

    }

    evstate->last = now;

    qemu_mutex_unlock(&monitor_event_state_lock);

}