void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end,

                                     int dirty_flags)

{

    CPUState *env;

    unsigned long length, start1;

    int i;

    start &= TARGET_PAGE_MASK;

    end = TARGET_PAGE_ALIGN(end);

    length = end - start;

    if (length == 0)

        return;

    cpu_physical_memory_mask_dirty_range(start, length, dirty_flags);

    /* we modify the TLB cache so that the dirty bit will be set again

       when accessing the range */

    start1 = (unsigned long)qemu_safe_ram_ptr(start);

    /* Chek that we don't span multiple blocks - this breaks the

       address comparisons below.  */

    if ((unsigned long)qemu_safe_ram_ptr(end - 1) - start1

            != (end - 1) - start) {

        abort();

    }

    for(env = first_cpu; env != NULL; env = env->next_cpu) {

        int mmu_idx;

        for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {

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

                tlb_reset_dirty_range(&env->tlb_table[mmu_idx][i],

                                      start1, length);

        }

    }

}


static void phys_page_set(target_phys_addr_t index, target_phys_addr_t nb,

                          uint16_t leaf)

{

    /* Wildly overreserve - it doesn't matter much. */

    phys_map_node_reserve(3 * P_L2_LEVELS);

    phys_page_set_level(&phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);

}


void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)

{

    char buf[READ_BUF_LEN];

    va_list ap;

    va_start(ap, fmt);

    vsnprintf(buf, sizeof(buf), fmt, ap);

    qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));

    va_end(ap);

}


int hw_device_setup_for_decode(InputStream *ist)

{

    enum AVHWDeviceType type;

    HWDevice *dev;

    int err;

    if (ist->hwaccel_device) {

        dev = hw_device_get_by_name(ist->hwaccel_device);

        if (!dev) {

            char *tmp;

            type = hw_device_match_type_by_hwaccel(ist->hwaccel_id);

            if (type == AV_HWDEVICE_TYPE_NONE) {

                // No match - this isn't necessarily invalid, though,

                // because an explicit device might not be needed or

                // the hwaccel setup could be handled elsewhere.

                return 0;

            }

            tmp = av_asprintf("%s:%s", av_hwdevice_get_type_name(type),

                              ist->hwaccel_device);

            if (!tmp)

                return AVERROR(ENOMEM);

            err = hw_device_init_from_string(tmp, &dev);

            av_free(tmp);

            if (err < 0)

                return err;

        }

    } else {

        if (ist->hwaccel_id != HWACCEL_NONE)

            type = hw_device_match_type_by_hwaccel(ist->hwaccel_id);

        else

            type = hw_device_match_type_in_name(ist->dec->name);

        if (type != AV_HWDEVICE_TYPE_NONE) {

            dev = hw_device_get_by_type(type);

            if (!dev) {

                hw_device_init_from_string(av_hwdevice_get_type_name(type),

                                           &dev);

            }

        } else {

            // No device required.

            return 0;

        }

    }

    if (!dev) {

        av_log(ist->dec_ctx, AV_LOG_WARNING, "No device available "

               "for decoder (device type %s for codec %s).\n",

               av_hwdevice_get_type_name(type), ist->dec->name);

        return 0;

    }

    ist->dec_ctx->hw_device_ctx = av_buffer_ref(dev->device_ref);

    if (!ist->dec_ctx->hw_device_ctx)

        return AVERROR(ENOMEM);

    return 0;

}


static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd)

{

    uint8_t data[4096];

    struct mfi_config_data *info;

    int num_pd_disks = 0, array_offset, ld_offset;

    BusChild *kid;

    if (cmd->iov_size > 4096) {

        return MFI_STAT_INVALID_PARAMETER;

    }

    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {

        num_pd_disks++;

    }

    info = (struct mfi_config_data *)&data;

    /*

     * Array mapping:

     * - One array per SCSI device

     * - One logical drive per SCSI device

     *   spanning the entire device

     */

    info->array_count = num_pd_disks;

    info->array_size = sizeof(struct mfi_array) * num_pd_disks;

    info->log_drv_count = num_pd_disks;

    info->log_drv_size = sizeof(struct mfi_ld_config) * num_pd_disks;

    info->spares_count = 0;

    info->spares_size = sizeof(struct mfi_spare);

    info->size = sizeof(struct mfi_config_data) + info->array_size +

        info->log_drv_size;

    if (info->size > 4096) {

        return MFI_STAT_INVALID_PARAMETER;

    }

    array_offset = sizeof(struct mfi_config_data);

    ld_offset = array_offset + sizeof(struct mfi_array) * num_pd_disks;

    QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {

        SCSIDevice *sdev = DO_UPCAST(SCSIDevice, qdev, kid->child);

        BlockConf *conf = &sdev->conf;

        uint16_t sdev_id = ((sdev->id & 0xFF) >> 8) | (sdev->lun & 0xFF);

        struct mfi_array *array;

        struct mfi_ld_config *ld;

        uint64_t pd_size;

        int i;

        array = (struct mfi_array *)(data + array_offset);

        bdrv_get_geometry(conf->bs, &pd_size);

        array->size = cpu_to_le64(pd_size);

        array->num_drives = 1;

        array->array_ref = cpu_to_le16(sdev_id);

        array->pd[0].ref.v.device_id = cpu_to_le16(sdev_id);

        array->pd[0].ref.v.seq_num = 0;

        array->pd[0].fw_state = MFI_PD_STATE_ONLINE;

        array->pd[0].encl.pd = 0xFF;

        array->pd[0].encl.slot = (sdev->id & 0xFF);

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

            array->pd[i].ref.v.device_id = 0xFFFF;

            array->pd[i].ref.v.seq_num = 0;

            array->pd[i].fw_state = MFI_PD_STATE_UNCONFIGURED_GOOD;

            array->pd[i].encl.pd = 0xFF;

            array->pd[i].encl.slot = 0xFF;

        }

        array_offset += sizeof(struct mfi_array);

        ld = (struct mfi_ld_config *)(data + ld_offset);

        memset(ld, 0, sizeof(struct mfi_ld_config));

        ld->properties.ld.v.target_id = (sdev->id & 0xFF);

        ld->properties.default_cache_policy = MR_LD_CACHE_READ_AHEAD |

            MR_LD_CACHE_READ_ADAPTIVE;

        ld->properties.current_cache_policy = MR_LD_CACHE_READ_AHEAD |

            MR_LD_CACHE_READ_ADAPTIVE;

        ld->params.state = MFI_LD_STATE_OPTIMAL;

        ld->params.stripe_size = 3;

        ld->params.num_drives = 1;

        ld->params.span_depth = 1;

        ld->params.is_consistent = 1;

        ld->span[0].start_block = 0;

        ld->span[0].num_blocks = cpu_to_le64(pd_size);

        ld->span[0].array_ref = cpu_to_le16(sdev_id);

        ld_offset += sizeof(struct mfi_ld_config);

    }

    cmd->iov_size -= dma_buf_read((uint8_t *)data, info->size, &cmd->qsg);

    return MFI_STAT_OK;

}


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

{

    struct etrax_timer *t = opaque;

    uint32_t r = 0;

    switch (addr) {

    case R_TMR0_DATA:

        r = ptimer_get_count(t->ptimer_t0);

        break;

    case R_TMR1_DATA:

        r = ptimer_get_count(t->ptimer_t1);

        break;

    case R_TIME:

        r = qemu_get_clock_ns(vm_clock) / 10;

        break;

    case RW_INTR_MASK:

        r = t->rw_intr_mask;

        break;

    case R_MASKED_INTR:

        r = t->r_intr & t->rw_intr_mask;

        break;

    default:

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

        break;

    }

    return r;

}


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

{

    MachineClass *mc = MACHINE_CLASS(oc);

    mc->desc = "ARM Virtual Machine",

    mc->init = machvirt_init;

    mc->max_cpus = 8;

    mc->has_dynamic_sysbus = true;

    mc->block_default_type = IF_VIRTIO;

    mc->no_cdrom = 1;

}


static GArray *nvdimm_build_device_structure(void)

{

    GSList *device_list = nvdimm_get_plugged_device_list();

    GArray *structures = g_array_new(false, true /* clear */, 1);

    for (; device_list; device_list = device_list->next) {

        DeviceState *dev = device_list->data;

        /* build System Physical Address Range Structure. */

        nvdimm_build_structure_spa(structures, dev);

        /*

         * build Memory Device to System Physical Address Range Mapping

         * Structure.

         */

        nvdimm_build_structure_memdev(structures, dev);

        /* build NVDIMM Control Region Structure. */

        nvdimm_build_structure_dcr(structures, dev);

    }

    g_slist_free(device_list);

    return structures;

}


static void pflash_timer (void *opaque)

{

    pflash_t *pfl = opaque;

    DPRINTF("%s: command %02x done\n", __func__, pfl->cmd);

    /* Reset flash */

    pfl->status ^= 0x80;

    if (pfl->bypass) {

        pfl->wcycle = 2;

    } else {

        memory_region_rom_device_set_readable(&pfl->mem, true);

        pfl->wcycle = 0;

    }

    pfl->cmd = 0;

}


void  helper_evaluate_flags_mcp(void)

{

	uint32_t src;

	uint32_t dst;

	uint32_t res;

	uint32_t flags = 0;

	src = env->cc_src;

	dst = env->cc_dest;

	res = env->cc_result;

	if ((res & 0x80000000L) != 0L)

	{

		flags |= N_FLAG;

		if (((src & 0x80000000L) == 0L)

		    && ((dst & 0x80000000L) == 0L))

		{

			flags |= V_FLAG;

		}

		else if (((src & 0x80000000L) != 0L) &&

			 ((dst & 0x80000000L) != 0L))

		{

			flags |= R_FLAG;

		}

	}

	else

	{

		if (res == 0L)

			flags |= Z_FLAG;

		if (((src & 0x80000000L) != 0L)

		    && ((dst & 0x80000000L) != 0L))

			flags |= V_FLAG;

		if ((dst & 0x80000000L) != 0L

		    || (src & 0x80000000L) != 0L)

			flags |= R_FLAG;

	}

	evaluate_flags_writeback(flags);

}


static void gen_store_exclusive(DisasContext *s, int rd, int rt, int rt2,

                                TCGv_i64 inaddr, int size, int is_pair)

{

    /* if (env->exclusive_addr == addr && env->exclusive_val == [addr]

     *     && (!is_pair || env->exclusive_high == [addr + datasize])) {

     *     [addr] = {Rt};

     *     if (is_pair) {

     *         [addr + datasize] = {Rt2};

     *     }

     *     {Rd} = 0;

     * } else {

     *     {Rd} = 1;

     * }

     * env->exclusive_addr = -1;

     */

    int fail_label = gen_new_label();

    int done_label = gen_new_label();

    TCGv_i64 addr = tcg_temp_local_new_i64();

    TCGv_i64 tmp;

    /* Copy input into a local temp so it is not trashed when the

     * basic block ends at the branch insn.

     */

    tcg_gen_mov_i64(addr, inaddr);

    tcg_gen_brcond_i64(TCG_COND_NE, addr, cpu_exclusive_addr, fail_label);

    tmp = tcg_temp_new_i64();

    tcg_gen_qemu_ld_i64(tmp, addr, get_mem_index(s), MO_TE + size);

    tcg_gen_brcond_i64(TCG_COND_NE, tmp, cpu_exclusive_val, fail_label);

    tcg_temp_free_i64(tmp);

    if (is_pair) {

        TCGv_i64 addrhi = tcg_temp_new_i64();

        TCGv_i64 tmphi = tcg_temp_new_i64();

        tcg_gen_addi_i64(addrhi, addr, 1 << size);

        tcg_gen_qemu_ld_i64(tmphi, addrhi, get_mem_index(s), MO_TE + size);

        tcg_gen_brcond_i64(TCG_COND_NE, tmphi, cpu_exclusive_high, fail_label);

        tcg_temp_free_i64(tmphi);

        tcg_temp_free_i64(addrhi);

    }

    /* We seem to still have the exclusive monitor, so do the store */

    tcg_gen_qemu_st_i64(cpu_reg(s, rt), addr, get_mem_index(s), MO_TE + size);

    if (is_pair) {

        TCGv_i64 addrhi = tcg_temp_new_i64();

        tcg_gen_addi_i64(addrhi, addr, 1 << size);

        tcg_gen_qemu_st_i64(cpu_reg(s, rt2), addrhi,

                            get_mem_index(s), MO_TE + size);

        tcg_temp_free_i64(addrhi);

    }

    tcg_temp_free_i64(addr);

    tcg_gen_movi_i64(cpu_reg(s, rd), 0);

    tcg_gen_br(done_label);

    gen_set_label(fail_label);

    tcg_gen_movi_i64(cpu_reg(s, rd), 1);

    gen_set_label(done_label);

    tcg_gen_movi_i64(cpu_exclusive_addr, -1);

}


QError *qerror_new(void)

{

    QError *qerr;

    qerr = g_malloc0(sizeof(*qerr));

    QOBJECT_INIT(qerr, &qerror_type);

    return qerr;

}


static void tgq_decode_mb(TgqContext *s, int mb_y, int mb_x, const uint8_t **bs, const uint8_t *buf_end){

    int mode;

    int i;

    int8_t dc[6];

    mode = bytestream_get_byte(bs);

    if (mode>buf_end-*bs) {

        av_log(s->avctx, AV_LOG_ERROR, "truncated macroblock\n");

        return;

    }

    if (mode>12) {

        GetBitContext gb;

        init_get_bits(&gb, *bs, mode*8);

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

            tgq_decode_block(s, s->block[i], &gb);

        tgq_idct_put_mb(s, s->block, mb_x, mb_y);

    }else{

        if (mode==3) {

            memset(dc, (*bs)[0], 4);

            dc[4] = (*bs)[1];

            dc[5] = (*bs)[2];

        }else if (mode==6) {

            memcpy(dc, *bs, 6);

        }else if (mode==12) {

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

                dc[i] = (*bs)[i*2];

        }else{

            av_log(s->avctx, AV_LOG_ERROR, "unsupported mb mode %i\n", mode);

        }

        tgq_idct_put_mb_dconly(s, mb_x, mb_y, dc);

    }

    *bs += mode;

}


void ff_prores_idct(DCTELEM *block, const int16_t *qmat)

{

    int i;

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

        block[i] *= qmat[i];

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

        idctRowCondDC_10(block + i*8);

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

        block[i] >>= 2;

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

        idctSparseCol_10(block + i);

}


int bdrv_write(BlockDriverState *bs, int64_t sector_num,
               const uint8_t *buf, int nb_sectors)
{
    BlockDriver *drv = bs->drv;
    if (!bs->drv)
        return -ENOMEDIUM;
    if (bs->read_only)
        return -EACCES;
    if (drv->bdrv_pwrite) {
        int ret, len, count = 0;
        len = nb_sectors * 512;
        do {
            ret = drv->bdrv_pwrite(bs, sector_num * 512, buf, len - count);
            if (ret < 0) {
                printf("bdrv_write ret=%d\n", ret);
                return ret;
            }
            count += ret;
            buf += ret;
        } while (count != len);
        bs->wr_bytes += (unsigned) len;
        bs->wr_ops ++;
        return 0;
    }
    return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
}


static void pnv_chip_power8nvl_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PnvChipClass *k = PNV_CHIP_CLASS(klass);

    k->cpu_model = "POWER8NVL";

    k->chip_type = PNV_CHIP_POWER8NVL;

    k->chip_cfam_id = 0x120d304980000000ull;  /* P8 Naples DD1.0 */

    k->cores_mask = POWER8_CORE_MASK;

    k->core_pir = pnv_chip_core_pir_p8;

    dc->desc = "PowerNV Chip POWER8NVL";

}


static inline void idct_col (int16_t * col, int offset)

{

#define T1 13036

#define T2 27146

#define T3 43790

#define C4 23170

    static const short _T1[] ATTR_ALIGN(8) = {T1,T1,T1,T1};

    static const short _T2[] ATTR_ALIGN(8) = {T2,T2,T2,T2};

    static const short _T3[] ATTR_ALIGN(8) = {T3,T3,T3,T3};

    static const short _C4[] ATTR_ALIGN(8) = {C4,C4,C4,C4};

    /* column code adapted from Peter Gubanov */

    /* http://www.elecard.com/peter/idct.shtml */

    movq_m2r (*_T1, mm0);               // mm0 = T1

    movq_m2r (*(col+offset+1*8), mm1);  // mm1 = x1

    movq_r2r (mm0, mm2);                // mm2 = T1

    movq_m2r (*(col+offset+7*8), mm4);  // mm4 = x7

    pmulhw_r2r (mm1, mm0);              // mm0 = T1*x1

    movq_m2r (*_T3, mm5);               // mm5 = T3

    pmulhw_r2r (mm4, mm2);              // mm2 = T1*x7

    movq_m2r (*(col+offset+5*8), mm6);  // mm6 = x5

    movq_r2r (mm5, mm7);                // mm7 = T3-1

    movq_m2r (*(col+offset+3*8), mm3);  // mm3 = x3

    psubsw_r2r (mm4, mm0);              // mm0 = v17

    movq_m2r (*_T2, mm4);               // mm4 = T2

    pmulhw_r2r (mm3, mm5);              // mm5 = (T3-1)*x3

    paddsw_r2r (mm2, mm1);              // mm1 = u17

    pmulhw_r2r (mm6, mm7);              // mm7 = (T3-1)*x5

    /* slot */

    movq_r2r (mm4, mm2);                // mm2 = T2

    paddsw_r2r (mm3, mm5);              // mm5 = T3*x3

    pmulhw_m2r (*(col+offset+2*8), mm4);// mm4 = T2*x2

    paddsw_r2r (mm6, mm7);              // mm7 = T3*x5

    psubsw_r2r (mm6, mm5);              // mm5 = v35

    paddsw_r2r (mm3, mm7);              // mm7 = u35

    movq_m2r (*(col+offset+6*8), mm3);  // mm3 = x6

    movq_r2r (mm0, mm6);                // mm6 = v17

    pmulhw_r2r (mm3, mm2);              // mm2 = T2*x6

    psubsw_r2r (mm5, mm0);              // mm0 = b3

    psubsw_r2r (mm3, mm4);              // mm4 = v26

    paddsw_r2r (mm6, mm5);              // mm5 = v12

    movq_r2m (mm0, *(col+offset+3*8));  // save b3 in scratch0

    movq_r2r (mm1, mm6);                // mm6 = u17

    paddsw_m2r (*(col+offset+2*8), mm2);// mm2 = u26

    paddsw_r2r (mm7, mm6);              // mm6 = b0

    psubsw_r2r (mm7, mm1);              // mm1 = u12

    movq_r2r (mm1, mm7);                // mm7 = u12

    movq_m2r (*(col+offset+0*8), mm3);  // mm3 = x0

    paddsw_r2r (mm5, mm1);              // mm1 = u12+v12

    movq_m2r (*_C4, mm0);               // mm0 = C4/2

    psubsw_r2r (mm5, mm7);              // mm7 = u12-v12

    movq_r2m (mm6, *(col+offset+5*8));  // save b0 in scratch1

    pmulhw_r2r (mm0, mm1);              // mm1 = b1/2

    movq_r2r (mm4, mm6);                // mm6 = v26

    pmulhw_r2r (mm0, mm7);              // mm7 = b2/2

    movq_m2r (*(col+offset+4*8), mm5);  // mm5 = x4

    movq_r2r (mm3, mm0);                // mm0 = x0

    psubsw_r2r (mm5, mm3);              // mm3 = v04

    paddsw_r2r (mm5, mm0);              // mm0 = u04

    paddsw_r2r (mm3, mm4);              // mm4 = a1

    movq_r2r (mm0, mm5);                // mm5 = u04

    psubsw_r2r (mm6, mm3);              // mm3 = a2

    paddsw_r2r (mm2, mm5);              // mm5 = a0

    paddsw_r2r (mm1, mm1);              // mm1 = b1

    psubsw_r2r (mm2, mm0);              // mm0 = a3

    paddsw_r2r (mm7, mm7);              // mm7 = b2

    movq_r2r (mm3, mm2);                // mm2 = a2

    movq_r2r (mm4, mm6);                // mm6 = a1

    paddsw_r2r (mm7, mm3);              // mm3 = a2+b2

    psraw_i2r (COL_SHIFT, mm3);         // mm3 = y2

    paddsw_r2r (mm1, mm4);              // mm4 = a1+b1

    psraw_i2r (COL_SHIFT, mm4);         // mm4 = y1

    psubsw_r2r (mm1, mm6);              // mm6 = a1-b1

    movq_m2r (*(col+offset+5*8), mm1);  // mm1 = b0

    psubsw_r2r (mm7, mm2);              // mm2 = a2-b2

    psraw_i2r (COL_SHIFT, mm6);         // mm6 = y6

    movq_r2r (mm5, mm7);                // mm7 = a0

    movq_r2m (mm4, *(col+offset+1*8));  // save y1

    psraw_i2r (COL_SHIFT, mm2);         // mm2 = y5

    movq_r2m (mm3, *(col+offset+2*8));  // save y2

    paddsw_r2r (mm1, mm5);              // mm5 = a0+b0

    movq_m2r (*(col+offset+3*8), mm4);  // mm4 = b3

    psubsw_r2r (mm1, mm7);              // mm7 = a0-b0

    psraw_i2r (COL_SHIFT, mm5);         // mm5 = y0

    movq_r2r (mm0, mm3);                // mm3 = a3

    movq_r2m (mm2, *(col+offset+5*8));  // save y5

    psubsw_r2r (mm4, mm3);              // mm3 = a3-b3

    psraw_i2r (COL_SHIFT, mm7);         // mm7 = y7

    paddsw_r2r (mm0, mm4);              // mm4 = a3+b3

    movq_r2m (mm5, *(col+offset+0*8));  // save y0

    psraw_i2r (COL_SHIFT, mm3);         // mm3 = y4

    movq_r2m (mm6, *(col+offset+6*8));  // save y6

    psraw_i2r (COL_SHIFT, mm4);         // mm4 = y3

    movq_r2m (mm7, *(col+offset+7*8));  // save y7

    movq_r2m (mm3, *(col+offset+4*8));  // save y4

    movq_r2m (mm4, *(col+offset+3*8));  // save y3

#undef T1

#undef T2

#undef T3

#undef C4

}


static av_always_inline void encode_mb_internal(MpegEncContext *s,

                                                int motion_x, int motion_y,

                                                int mb_block_height,

                                                int mb_block_width,

                                                int mb_block_count)

{

    int16_t weight[12][64];

    int16_t orig[12][64];

    const int mb_x = s->mb_x;

    const int mb_y = s->mb_y;

    int i;

    int skip_dct[12];

    int dct_offset = s->linesize * 8; // default for progressive frames

    int uv_dct_offset = s->uvlinesize * 8;

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    int wrap_y, wrap_c;

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

        skip_dct[i] = s->skipdct;

    if (s->adaptive_quant) {

        const int last_qp = s->qscale;

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

        s->lambda = s->lambda_table[mb_xy];

        update_qscale(s);

        if (!(s->mpv_flags & FF_MPV_FLAG_QP_RD)) {

            s->qscale = s->current_picture_ptr->qscale_table[mb_xy];

            s->dquant = s->qscale - last_qp;

            if (s->out_format == FMT_H263) {

                s->dquant = av_clip(s->dquant, -2, 2);

                if (s->codec_id == AV_CODEC_ID_MPEG4) {

                    if (!s->mb_intra) {

                        if (s->pict_type == AV_PICTURE_TYPE_B) {

                            if (s->dquant & 1 || s->mv_dir & MV_DIRECT)

                                s->dquant = 0;

                        }

                        if (s->mv_type == MV_TYPE_8X8)

                            s->dquant = 0;

                    }

                }

            }

        }

        ff_set_qscale(s, last_qp + s->dquant);

    } else if (s->mpv_flags & FF_MPV_FLAG_QP_RD)

        ff_set_qscale(s, s->qscale + s->dquant);

    wrap_y = s->linesize;

    wrap_c = s->uvlinesize;

    ptr_y  = s->new_picture.f.data[0] +

             (mb_y * 16 * wrap_y)              + mb_x * 16;

    ptr_cb = s->new_picture.f.data[1] +

             (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;

    ptr_cr = s->new_picture.f.data[2] +

             (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;

    if((mb_x*16+16 > s->width || mb_y*16+16 > s->height) && s->codec_id != AV_CODEC_ID_AMV){

        uint8_t *ebuf = s->edge_emu_buffer + 32;

        int cw = (s->width  + s->chroma_x_shift) >> s->chroma_x_shift;

        int ch = (s->height + s->chroma_y_shift) >> s->chroma_y_shift;

        s->vdsp.emulated_edge_mc(ebuf, ptr_y, wrap_y, 16, 16, mb_x * 16,

                                 mb_y * 16, s->width, s->height);

        ptr_y = ebuf;

        s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb, wrap_c, mb_block_width,

                                 mb_block_height, mb_x * mb_block_width, mb_y * mb_block_height,

                                 cw, ch);

        ptr_cb = ebuf + 18 * wrap_y;

        s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y + 16, ptr_cr, wrap_c, mb_block_width,

                                 mb_block_height, mb_x * mb_block_width, mb_y * mb_block_height,

                                 cw, ch);

        ptr_cr = ebuf + 18 * wrap_y + 16;

    }

    if (s->mb_intra) {

        if (s->flags & CODEC_FLAG_INTERLACED_DCT) {

            int progressive_score, interlaced_score;

            s->interlaced_dct = 0;

            progressive_score = s->dsp.ildct_cmp[4](s, ptr_y,

                                                    NULL, wrap_y, 8) +

                                s->dsp.ildct_cmp[4](s, ptr_y + wrap_y * 8,

                                                    NULL, wrap_y, 8) - 400;

            if (progressive_score > 0) {

                interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y,

                                                       NULL, wrap_y * 2, 8) +

                                   s->dsp.ildct_cmp[4](s, ptr_y + wrap_y,

                                                       NULL, wrap_y * 2, 8);

                if (progressive_score > interlaced_score) {

                    s->interlaced_dct = 1;

                    dct_offset = wrap_y;

                    uv_dct_offset = wrap_c;

                    wrap_y <<= 1;

                    if (s->chroma_format == CHROMA_422 ||

                        s->chroma_format == CHROMA_444)

                        wrap_c <<= 1;

                }

            }

        }

        s->dsp.get_pixels(s->block[0], ptr_y                  , wrap_y);

        s->dsp.get_pixels(s->block[1], ptr_y              + 8 , wrap_y);

        s->dsp.get_pixels(s->block[2], ptr_y + dct_offset     , wrap_y);

        s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8 , wrap_y);

        if (s->flags & CODEC_FLAG_GRAY) {

            skip_dct[4] = 1;

            skip_dct[5] = 1;

        } else {

            s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);

            s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);

            if (!s->chroma_y_shift && s->chroma_x_shift) { /* 422 */

                s->dsp.get_pixels(s->block[6], ptr_cb + uv_dct_offset, wrap_c);

                s->dsp.get_pixels(s->block[7], ptr_cr + uv_dct_offset, wrap_c);

            } else if (!s->chroma_y_shift && !s->chroma_x_shift) { /* 444 */

                s->dsp.get_pixels(s->block[6], ptr_cb + 8, wrap_c);

                s->dsp.get_pixels(s->block[7], ptr_cr + 8, wrap_c);

                s->dsp.get_pixels(s->block[8], ptr_cb + uv_dct_offset, wrap_c);

                s->dsp.get_pixels(s->block[9], ptr_cr + uv_dct_offset, wrap_c);

                s->dsp.get_pixels(s->block[10], ptr_cb + uv_dct_offset + 8, wrap_c);

                s->dsp.get_pixels(s->block[11], ptr_cr + uv_dct_offset + 8, wrap_c);

            }

        }

    } else {

        op_pixels_func (*op_pix)[4];

        qpel_mc_func (*op_qpix)[16];

        uint8_t *dest_y, *dest_cb, *dest_cr;

        dest_y  = s->dest[0];

        dest_cb = s->dest[1];

        dest_cr = s->dest[2];

        if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {

            op_pix  = s->hdsp.put_pixels_tab;

            op_qpix = s->dsp.put_qpel_pixels_tab;

        } else {

            op_pix  = s->hdsp.put_no_rnd_pixels_tab;

            op_qpix = s->dsp.put_no_rnd_qpel_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_FORWARD) {

            ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 0,

                          s->last_picture.f.data,

                          op_pix, op_qpix);

            op_pix  = s->hdsp.avg_pixels_tab;

            op_qpix = s->dsp.avg_qpel_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_BACKWARD) {

            ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 1,

                          s->next_picture.f.data,

                          op_pix, op_qpix);

        }

        if (s->flags & CODEC_FLAG_INTERLACED_DCT) {

            int progressive_score, interlaced_score;

            s->interlaced_dct = 0;

            progressive_score = s->dsp.ildct_cmp[0](s, dest_y,

                                                    ptr_y,              wrap_y,

                                                    8) +

                                s->dsp.ildct_cmp[0](s, dest_y + wrap_y * 8,

                                                    ptr_y + wrap_y * 8, wrap_y,

                                                    8) - 400;

            if (s->avctx->ildct_cmp == FF_CMP_VSSE)

                progressive_score -= 400;

            if (progressive_score > 0) {

                interlaced_score = s->dsp.ildct_cmp[0](s, dest_y,

                                                       ptr_y,

                                                       wrap_y * 2, 8) +

                                   s->dsp.ildct_cmp[0](s, dest_y + wrap_y,

                                                       ptr_y + wrap_y,

                                                       wrap_y * 2, 8);

                if (progressive_score > interlaced_score) {

                    s->interlaced_dct = 1;

                    dct_offset = wrap_y;

                    uv_dct_offset = wrap_c;

                    wrap_y <<= 1;

                    if (s->chroma_format == CHROMA_422)

                        wrap_c <<= 1;

                }

            }

        }

        s->dsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);

        s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);

        s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset,

                           dest_y + dct_offset, wrap_y);

        s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,

                           dest_y + dct_offset + 8, wrap_y);

        if (s->flags & CODEC_FLAG_GRAY) {

            skip_dct[4] = 1;

            skip_dct[5] = 1;

        } else {

            s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);

            s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);

            if (!s->chroma_y_shift) { /* 422 */

                s->dsp.diff_pixels(s->block[6], ptr_cb + uv_dct_offset,

                                   dest_cb + uv_dct_offset, wrap_c);

                s->dsp.diff_pixels(s->block[7], ptr_cr + uv_dct_offset,

                                   dest_cr + uv_dct_offset, wrap_c);

            }

        }

        /* pre quantization */

        if (s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] <

                2 * s->qscale * s->qscale) {

            // FIXME optimize

            if (s->dsp.sad[1](NULL, ptr_y , dest_y,

                              wrap_y, 8) < 20 * s->qscale)

                skip_dct[0] = 1;

            if (s->dsp.sad[1](NULL, ptr_y + 8,

                              dest_y + 8, wrap_y, 8) < 20 * s->qscale)

                skip_dct[1] = 1;

            if (s->dsp.sad[1](NULL, ptr_y + dct_offset,

                              dest_y + dct_offset, wrap_y, 8) < 20 * s->qscale)

                skip_dct[2] = 1;

            if (s->dsp.sad[1](NULL, ptr_y + dct_offset + 8,

                              dest_y + dct_offset + 8,

                              wrap_y, 8) < 20 * s->qscale)

                skip_dct[3] = 1;

            if (s->dsp.sad[1](NULL, ptr_cb, dest_cb,

                              wrap_c, 8) < 20 * s->qscale)

                skip_dct[4] = 1;

            if (s->dsp.sad[1](NULL, ptr_cr, dest_cr,

                              wrap_c, 8) < 20 * s->qscale)

                skip_dct[5] = 1;

            if (!s->chroma_y_shift) { /* 422 */

                if (s->dsp.sad[1](NULL, ptr_cb + uv_dct_offset,

                                  dest_cb + uv_dct_offset,

                                  wrap_c, 8) < 20 * s->qscale)

                    skip_dct[6] = 1;

                if (s->dsp.sad[1](NULL, ptr_cr + uv_dct_offset,

                                  dest_cr + uv_dct_offset,

                                  wrap_c, 8) < 20 * s->qscale)

                    skip_dct[7] = 1;

            }

        }

    }

    if (s->quantizer_noise_shaping) {

        if (!skip_dct[0])

            get_visual_weight(weight[0], ptr_y                 , wrap_y);

        if (!skip_dct[1])

            get_visual_weight(weight[1], ptr_y              + 8, wrap_y);

        if (!skip_dct[2])

            get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);

        if (!skip_dct[3])

            get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);

        if (!skip_dct[4])

            get_visual_weight(weight[4], ptr_cb                , wrap_c);

        if (!skip_dct[5])

            get_visual_weight(weight[5], ptr_cr                , wrap_c);

        if (!s->chroma_y_shift) { /* 422 */

            if (!skip_dct[6])

                get_visual_weight(weight[6], ptr_cb + uv_dct_offset,

                                  wrap_c);

            if (!skip_dct[7])

                get_visual_weight(weight[7], ptr_cr + uv_dct_offset,

                                  wrap_c);

        }

        memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);

    }

    /* DCT & quantize */

    av_assert2(s->out_format != FMT_MJPEG || s->qscale == 8);

    {

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

            if (!skip_dct[i]) {

                int overflow;

                s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);

                // FIXME we could decide to change to quantizer instead of

                // clipping

                // JS: I don't think that would be a good idea it could lower

                //     quality instead of improve it. Just INTRADC clipping

                //     deserves changes in quantizer

                if (overflow)

                    clip_coeffs(s, s->block[i], s->block_last_index[i]);

            } else

                s->block_last_index[i] = -1;

        }

        if (s->quantizer_noise_shaping) {

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

                if (!skip_dct[i]) {

                    s->block_last_index[i] =

                        dct_quantize_refine(s, s->block[i], weight[i],

                                            orig[i], i, s->qscale);

                }

            }

        }

        if (s->luma_elim_threshold && !s->mb_intra)

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

                dct_single_coeff_elimination(s, i, s->luma_elim_threshold);

        if (s->chroma_elim_threshold && !s->mb_intra)

            for (i = 4; i < mb_block_count; i++)

                dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);

        if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {

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

                if (s->block_last_index[i] == -1)

                    s->coded_score[i] = INT_MAX / 256;

            }

        }

    }

    if ((s->flags & CODEC_FLAG_GRAY) && s->mb_intra) {

        s->block_last_index[4] =

        s->block_last_index[5] = 0;

        s->block[4][0] =

        s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;

        if (!s->chroma_y_shift) { /* 422 / 444 */

            for (i=6; i<12; i++) {

                s->block_last_index[i] = 0;

                s->block[i][0] = s->block[4][0];

            }

        }

    }

    // non c quantize code returns incorrect block_last_index FIXME

    if (s->alternate_scan && s->dct_quantize != ff_dct_quantize_c) {

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

            int j;

            if (s->block_last_index[i] > 0) {

                for (j = 63; j > 0; j--) {

                    if (s->block[i][s->intra_scantable.permutated[j]])

                        break;

                }

                s->block_last_index[i] = j;

            }

        }

    }

    /* huffman encode */

    switch(s->codec_id){ //FIXME funct ptr could be slightly faster

    case AV_CODEC_ID_MPEG1VIDEO:

    case AV_CODEC_ID_MPEG2VIDEO:

        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

            ff_mpeg1_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_MPEG4:

        if (CONFIG_MPEG4_ENCODER)

            ff_mpeg4_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_MSMPEG4V2:

    case AV_CODEC_ID_MSMPEG4V3:

    case AV_CODEC_ID_WMV1:

        if (CONFIG_MSMPEG4_ENCODER)

            ff_msmpeg4_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_WMV2:

        if (CONFIG_WMV2_ENCODER)

            ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_H261:

        if (CONFIG_H261_ENCODER)

            ff_h261_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_H263:

    case AV_CODEC_ID_H263P:

    case AV_CODEC_ID_FLV1:

    case AV_CODEC_ID_RV10:

    case AV_CODEC_ID_RV20:

        if (CONFIG_H263_ENCODER)

            ff_h263_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_MJPEG:

    case AV_CODEC_ID_AMV:

        if (CONFIG_MJPEG_ENCODER)

            ff_mjpeg_encode_mb(s, s->block);

        break;

    default:

        av_assert1(0);

    }

}


static void gd_menu_switch_vc(GtkMenuItem *item, void *opaque)
{
    GtkDisplayState *s = opaque;
    VirtualConsole *vc = gd_vc_find_by_menu(s);
    GtkNotebook *nb = GTK_NOTEBOOK(s->notebook);
    gint page;
    gtk_release_modifiers(s);
    if (vc) {
        page = gtk_notebook_page_num(nb, vc->tab_item);
        gtk_notebook_set_current_page(nb, page);
        gtk_widget_grab_focus(vc->focus);
    }
}


void blockdev_mark_auto_del(BlockDriverState *bs)

{

    BlockBackend *blk = bs->blk;

    DriveInfo *dinfo = blk_legacy_dinfo(blk);

    if (dinfo && !dinfo->enable_auto_del) {

        return;

    }

    if (bs->job) {

        block_job_cancel(bs->job);

    }

    if (dinfo) {

        dinfo->auto_del = 1;

    }

}


static void create_gic(VirtBoardInfo *vbi, qemu_irq *pic, bool secure)

{

    /* We create a standalone GIC v2 */

    DeviceState *gicdev;

    SysBusDevice *gicbusdev;

    const char *gictype;

    int i;

    gictype = gic_class_name();

    gicdev = qdev_create(NULL, gictype);

    qdev_prop_set_uint32(gicdev, "revision", 2);

    qdev_prop_set_uint32(gicdev, "num-cpu", smp_cpus);

    /* Note that the num-irq property counts both internal and external

     * interrupts; there are always 32 of the former (mandated by GIC spec).

     */

    qdev_prop_set_uint32(gicdev, "num-irq", NUM_IRQS + 32);

    if (!kvm_irqchip_in_kernel()) {

        qdev_prop_set_bit(gicdev, "has-security-extensions", secure);

    }

    qdev_init_nofail(gicdev);

    gicbusdev = SYS_BUS_DEVICE(gicdev);

    sysbus_mmio_map(gicbusdev, 0, vbi->memmap[VIRT_GIC_DIST].base);

    sysbus_mmio_map(gicbusdev, 1, vbi->memmap[VIRT_GIC_CPU].base);

    /* Wire the outputs from each CPU's generic timer to the

     * appropriate GIC PPI inputs, and the GIC's IRQ output to

     * the CPU's IRQ input.

     */

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

        DeviceState *cpudev = DEVICE(qemu_get_cpu(i));

        int ppibase = NUM_IRQS + i * GIC_INTERNAL + GIC_NR_SGIS;

        int irq;

        /* Mapping from the output timer irq lines from the CPU to the

         * GIC PPI inputs we use for the virt board.

         */

        const int timer_irq[] = {

            [GTIMER_PHYS] = ARCH_TIMER_NS_EL1_IRQ,

            [GTIMER_VIRT] = ARCH_TIMER_VIRT_IRQ,

            [GTIMER_HYP]  = ARCH_TIMER_NS_EL2_IRQ,

            [GTIMER_SEC]  = ARCH_TIMER_S_EL1_IRQ,

        };

        for (irq = 0; irq < ARRAY_SIZE(timer_irq); irq++) {

            qdev_connect_gpio_out(cpudev, irq,

                                  qdev_get_gpio_in(gicdev,

                                                   ppibase + timer_irq[irq]));

        }

        sysbus_connect_irq(gicbusdev, i, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ));

        sysbus_connect_irq(gicbusdev, i + smp_cpus,

                           qdev_get_gpio_in(cpudev, ARM_CPU_FIQ));

    }

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

        pic[i] = qdev_get_gpio_in(gicdev, i);

    }

    fdt_add_gic_node(vbi);

    create_v2m(vbi, pic);

}


static int disas_neon_ls_insn(DisasContext *s, uint32_t insn)

{

    int rd, rn, rm;

    int op;

    int nregs;

    int interleave;

    int spacing;

    int stride;

    int size;

    int reg;

    int pass;

    int load;

    int shift;

    int n;

    TCGv_i32 addr;

    TCGv_i32 tmp;

    TCGv_i32 tmp2;

    TCGv_i64 tmp64;

    /* FIXME: this access check should not take precedence over UNDEF

     * for invalid encodings; we will generate incorrect syndrome information

     * for attempts to execute invalid vfp/neon encodings with FP disabled.

     */

    if (!s->cpacr_fpen) {

        gen_exception_insn(s, 4, EXCP_UDEF,

                           syn_fp_access_trap(1, 0xe, s->thumb),

                           default_exception_el(s));

        return 0;

    }

    if (!s->vfp_enabled)

      return 1;

    VFP_DREG_D(rd, insn);

    rn = (insn >> 16) & 0xf;

    rm = insn & 0xf;

    load = (insn & (1 << 21)) != 0;

    if ((insn & (1 << 23)) == 0) {

        /* Load store all elements.  */

        op = (insn >> 8) & 0xf;

        size = (insn >> 6) & 3;

        if (op > 10)

            return 1;

        /* Catch UNDEF cases for bad values of align field */

        switch (op & 0xc) {

        case 4:

            if (((insn >> 5) & 1) == 1) {

                return 1;

            }

            break;

        case 8:

            if (((insn >> 4) & 3) == 3) {

                return 1;

            }

            break;

        default:

            break;

        }

        nregs = neon_ls_element_type[op].nregs;

        interleave = neon_ls_element_type[op].interleave;

        spacing = neon_ls_element_type[op].spacing;

        if (size == 3 && (interleave | spacing) != 1)

            return 1;

        addr = tcg_temp_new_i32();

        load_reg_var(s, addr, rn);

        stride = (1 << size) * interleave;

        for (reg = 0; reg < nregs; reg++) {

            if (interleave > 2 || (interleave == 2 && nregs == 2)) {

                load_reg_var(s, addr, rn);

                tcg_gen_addi_i32(addr, addr, (1 << size) * reg);

            } else if (interleave == 2 && nregs == 4 && reg == 2) {

                load_reg_var(s, addr, rn);

                tcg_gen_addi_i32(addr, addr, 1 << size);

            }

            if (size == 3) {

                tmp64 = tcg_temp_new_i64();

                if (load) {

                    gen_aa32_ld64(tmp64, addr, get_mem_index(s));

                    neon_store_reg64(tmp64, rd);

                } else {

                    neon_load_reg64(tmp64, rd);

                    gen_aa32_st64(tmp64, addr, get_mem_index(s));

                }

                tcg_temp_free_i64(tmp64);

                tcg_gen_addi_i32(addr, addr, stride);

            } else {

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

                    if (size == 2) {

                        if (load) {

                            tmp = tcg_temp_new_i32();

                            gen_aa32_ld32u(tmp, addr, get_mem_index(s));

                            neon_store_reg(rd, pass, tmp);

                        } else {

                            tmp = neon_load_reg(rd, pass);

                            gen_aa32_st32(tmp, addr, get_mem_index(s));

                            tcg_temp_free_i32(tmp);

                        }

                        tcg_gen_addi_i32(addr, addr, stride);

                    } else if (size == 1) {

                        if (load) {

                            tmp = tcg_temp_new_i32();

                            gen_aa32_ld16u(tmp, addr, get_mem_index(s));

                            tcg_gen_addi_i32(addr, addr, stride);

                            tmp2 = tcg_temp_new_i32();

                            gen_aa32_ld16u(tmp2, addr, get_mem_index(s));

                            tcg_gen_addi_i32(addr, addr, stride);

                            tcg_gen_shli_i32(tmp2, tmp2, 16);

                            tcg_gen_or_i32(tmp, tmp, tmp2);

                            tcg_temp_free_i32(tmp2);

                            neon_store_reg(rd, pass, tmp);

                        } else {

                            tmp = neon_load_reg(rd, pass);

                            tmp2 = tcg_temp_new_i32();

                            tcg_gen_shri_i32(tmp2, tmp, 16);

                            gen_aa32_st16(tmp, addr, get_mem_index(s));

                            tcg_temp_free_i32(tmp);

                            tcg_gen_addi_i32(addr, addr, stride);

                            gen_aa32_st16(tmp2, addr, get_mem_index(s));

                            tcg_temp_free_i32(tmp2);

                            tcg_gen_addi_i32(addr, addr, stride);

                        }

                    } else /* size == 0 */ {

                        if (load) {

                            TCGV_UNUSED_I32(tmp2);

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

                                tmp = tcg_temp_new_i32();

                                gen_aa32_ld8u(tmp, addr, get_mem_index(s));

                                tcg_gen_addi_i32(addr, addr, stride);

                                if (n == 0) {

                                    tmp2 = tmp;

                                } else {

                                    tcg_gen_shli_i32(tmp, tmp, n * 8);

                                    tcg_gen_or_i32(tmp2, tmp2, tmp);

                                    tcg_temp_free_i32(tmp);

                                }

                            }

                            neon_store_reg(rd, pass, tmp2);

                        } else {

                            tmp2 = neon_load_reg(rd, pass);

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

                                tmp = tcg_temp_new_i32();

                                if (n == 0) {

                                    tcg_gen_mov_i32(tmp, tmp2);

                                } else {

                                    tcg_gen_shri_i32(tmp, tmp2, n * 8);

                                }

                                gen_aa32_st8(tmp, addr, get_mem_index(s));

                                tcg_temp_free_i32(tmp);

                                tcg_gen_addi_i32(addr, addr, stride);

                            }

                            tcg_temp_free_i32(tmp2);

                        }

                    }

                }

            }

            rd += spacing;

        }

        tcg_temp_free_i32(addr);

        stride = nregs * 8;

    } else {

        size = (insn >> 10) & 3;

        if (size == 3) {

            /* Load single element to all lanes.  */

            int a = (insn >> 4) & 1;

            if (!load) {

                return 1;

            }

            size = (insn >> 6) & 3;

            nregs = ((insn >> 8) & 3) + 1;

            if (size == 3) {

                if (nregs != 4 || a == 0) {

                    return 1;

                }

                /* For VLD4 size==3 a == 1 means 32 bits at 16 byte alignment */

                size = 2;

            }

            if (nregs == 1 && a == 1 && size == 0) {

                return 1;

            }

            if (nregs == 3 && a == 1) {

                return 1;

            }

            addr = tcg_temp_new_i32();

            load_reg_var(s, addr, rn);

            if (nregs == 1) {

                /* VLD1 to all lanes: bit 5 indicates how many Dregs to write */

                tmp = gen_load_and_replicate(s, addr, size);

                tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 0));

                tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 1));

                if (insn & (1 << 5)) {

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd + 1, 0));

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd + 1, 1));

                }

                tcg_temp_free_i32(tmp);

            } else {

                /* VLD2/3/4 to all lanes: bit 5 indicates register stride */

                stride = (insn & (1 << 5)) ? 2 : 1;

                for (reg = 0; reg < nregs; reg++) {

                    tmp = gen_load_and_replicate(s, addr, size);

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 0));

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 1));

                    tcg_temp_free_i32(tmp);

                    tcg_gen_addi_i32(addr, addr, 1 << size);

                    rd += stride;

                }

            }

            tcg_temp_free_i32(addr);

            stride = (1 << size) * nregs;

        } else {

            /* Single element.  */

            int idx = (insn >> 4) & 0xf;

            pass = (insn >> 7) & 1;

            switch (size) {

            case 0:

                shift = ((insn >> 5) & 3) * 8;

                stride = 1;

                break;

            case 1:

                shift = ((insn >> 6) & 1) * 16;

                stride = (insn & (1 << 5)) ? 2 : 1;

                break;

            case 2:

                shift = 0;

                stride = (insn & (1 << 6)) ? 2 : 1;

                break;

            default:

                abort();

            }

            nregs = ((insn >> 8) & 3) + 1;

            /* Catch the UNDEF cases. This is unavoidably a bit messy. */

            switch (nregs) {

            case 1:

                if (((idx & (1 << size)) != 0) ||

                    (size == 2 && ((idx & 3) == 1 || (idx & 3) == 2))) {

                    return 1;

                }

                break;

            case 3:

                if ((idx & 1) != 0) {

                    return 1;

                }

                /* fall through */

            case 2:

                if (size == 2 && (idx & 2) != 0) {

                    return 1;

                }

                break;

            case 4:

                if ((size == 2) && ((idx & 3) == 3)) {

                    return 1;

                }

                break;

            default:

                abort();

            }

            if ((rd + stride * (nregs - 1)) > 31) {

                /* Attempts to write off the end of the register file

                 * are UNPREDICTABLE; we choose to UNDEF because otherwise

                 * the neon_load_reg() would write off the end of the array.

                 */

                return 1;

            }

            addr = tcg_temp_new_i32();

            load_reg_var(s, addr, rn);

            for (reg = 0; reg < nregs; reg++) {

                if (load) {

                    tmp = tcg_temp_new_i32();

                    switch (size) {

                    case 0:

                        gen_aa32_ld8u(tmp, addr, get_mem_index(s));

                        break;

                    case 1:

                        gen_aa32_ld16u(tmp, addr, get_mem_index(s));

                        break;

                    case 2:

                        gen_aa32_ld32u(tmp, addr, get_mem_index(s));

                        break;

                    default: /* Avoid compiler warnings.  */

                        abort();

                    }

                    if (size != 2) {

                        tmp2 = neon_load_reg(rd, pass);

                        tcg_gen_deposit_i32(tmp, tmp2, tmp,

                                            shift, size ? 16 : 8);

                        tcg_temp_free_i32(tmp2);

                    }

                    neon_store_reg(rd, pass, tmp);

                } else { /* Store */

                    tmp = neon_load_reg(rd, pass);

                    if (shift)

                        tcg_gen_shri_i32(tmp, tmp, shift);

                    switch (size) {

                    case 0:

                        gen_aa32_st8(tmp, addr, get_mem_index(s));

                        break;

                    case 1:

                        gen_aa32_st16(tmp, addr, get_mem_index(s));

                        break;

                    case 2:

                        gen_aa32_st32(tmp, addr, get_mem_index(s));

                        break;

                    }

                    tcg_temp_free_i32(tmp);

                }

                rd += stride;

                tcg_gen_addi_i32(addr, addr, 1 << size);

            }

            tcg_temp_free_i32(addr);

            stride = nregs * (1 << size);

        }

    }

    if (rm != 15) {

        TCGv_i32 base;

        base = load_reg(s, rn);

        if (rm == 13) {

            tcg_gen_addi_i32(base, base, stride);

        } else {

            TCGv_i32 index;

            index = load_reg(s, rm);

            tcg_gen_add_i32(base, base, index);

            tcg_temp_free_i32(index);

        }

        store_reg(s, rn, base);

    }

    return 0;

}


e1000_can_receive(NetClientState *nc)

{

    E1000State *s = qemu_get_nic_opaque(nc);

    return (s->mac_reg[RCTL] & E1000_RCTL_EN) && e1000_has_rxbufs(s, 1);

}


static void rtce_init(VIOsPAPRDevice *dev)

{

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

        * sizeof(VIOsPAPR_RTCE);

    if (size) {

        dev->rtce_table = kvmppc_create_spapr_tce(dev->reg,

                                                  dev->rtce_window_size,

                                                  &dev->kvmtce_fd);

        if (!dev->rtce_table) {

            dev->rtce_table = g_malloc0(size);

        }

    }

}


static void vnc_desktop_resize(VncState *vs)

{

    DisplaySurface *ds = vs->vd->ds;

    if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {

        return;

    }

    if (vs->client_width == surface_width(ds) &&

        vs->client_height == surface_height(ds)) {

        return;

    }

    vs->client_width = surface_width(ds);

    vs->client_height = surface_height(ds);

    vnc_lock_output(vs);

    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);

    vnc_write_u8(vs, 0);

    vnc_write_u16(vs, 1); /* number of rects */

    vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,

                           VNC_ENCODING_DESKTOPRESIZE);

    vnc_unlock_output(vs);

    vnc_flush(vs);

}


static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time, int bye)

{

    RTPMuxContext *s = s1->priv_data;

    uint32_t rtp_ts;

    av_log(s1, AV_LOG_TRACE, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);

    s->last_rtcp_ntp_time = ntp_time;

    rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, (AVRational){1, 1000000},

                          s1->streams[0]->time_base) + s->base_timestamp;

    avio_w8(s1->pb, RTP_VERSION << 6);

    avio_w8(s1->pb, RTCP_SR);

    avio_wb16(s1->pb, 6); /* length in words - 1 */

    avio_wb32(s1->pb, s->ssrc);

    avio_wb64(s1->pb, NTP_TO_RTP_FORMAT(ntp_time));

    avio_wb32(s1->pb, rtp_ts);

    avio_wb32(s1->pb, s->packet_count);

    avio_wb32(s1->pb, s->octet_count);

    if (s->cname) {

        int len = FFMIN(strlen(s->cname), 255);

        avio_w8(s1->pb, (RTP_VERSION << 6) + 1);

        avio_w8(s1->pb, RTCP_SDES);

        avio_wb16(s1->pb, (7 + len + 3) / 4); /* length in words - 1 */

        avio_wb32(s1->pb, s->ssrc);

        avio_w8(s1->pb, 0x01); /* CNAME */

        avio_w8(s1->pb, len);

        avio_write(s1->pb, s->cname, len);

        avio_w8(s1->pb, 0); /* END */

        for (len = (7 + len) % 4; len % 4; len++)

            avio_w8(s1->pb, 0);

    }

    if (bye) {

        avio_w8(s1->pb, (RTP_VERSION << 6) | 1);

        avio_w8(s1->pb, RTCP_BYE);

        avio_wb16(s1->pb, 1); /* length in words - 1 */

        avio_wb32(s1->pb, s->ssrc);

    }

    avio_flush(s1->pb);

}


void stl_be_phys(target_phys_addr_t addr, uint32_t val)

{

    stl_phys_internal(addr, val, DEVICE_BIG_ENDIAN);

}


static uint8_t *l2cap_bframe_out(struct bt_l2cap_conn_params_s *parm, int len)

{

    struct l2cap_chan_s *chan = (struct l2cap_chan_s *) parm;

    if (len > chan->params.remote_mtu) {

        fprintf(stderr, "%s: B-Frame for CID %04x longer than %i octets.\n",

                        __func__,

                        chan->remote_cid, chan->params.remote_mtu);

        exit(-1);

    }

    return l2cap_pdu_out(chan->l2cap, chan->remote_cid, len);

}


static int do_open_tray(const char *device, bool force, Error **errp)

{

    BlockBackend *blk;

    bool locked;

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

                  "Device '%s' not found", device);

        return -ENODEV;

    }

    if (!blk_dev_has_removable_media(blk)) {

        error_setg(errp, "Device '%s' is not removable", device);

        return -ENOTSUP;

    }

    if (!blk_dev_has_tray(blk)) {

        /* Ignore this command on tray-less devices */

        return ENOSYS;

    }

    if (blk_dev_is_tray_open(blk)) {

        return 0;

    }

    locked = blk_dev_is_medium_locked(blk);

    if (locked) {

        blk_dev_eject_request(blk, force);

    }

    if (!locked || force) {

        blk_dev_change_media_cb(blk, false);

    }

    if (locked && !force) {

        return EINPROGRESS;

    }

    return 0;

}


static int read_config(BDRVBlkdebugState *s, const char *filename,

                       QDict *options, Error **errp)

{

    FILE *f = NULL;

    int ret;

    struct add_rule_data d;

    Error *local_err = NULL;

    if (filename) {

        f = fopen(filename, "r");

        if (f == NULL) {

            error_setg_errno(errp, errno, "Could not read blkdebug config file");

            return -errno;

        }

        ret = qemu_config_parse(f, config_groups, filename);

        if (ret < 0) {

            error_setg(errp, "Could not parse blkdebug config file");

            ret = -EINVAL;

            goto fail;

        }

    }

    qemu_config_parse_qdict(options, config_groups, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    d.s = s;

    d.action = ACTION_INJECT_ERROR;

    qemu_opts_foreach(&inject_error_opts, add_rule, &d, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    d.action = ACTION_SET_STATE;

    qemu_opts_foreach(&set_state_opts, add_rule, &d, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    ret = 0;

fail:

    qemu_opts_reset(&inject_error_opts);

    qemu_opts_reset(&set_state_opts);

    if (f) {

        fclose(f);

    }

    return ret;

}


static void kvm_log_start(MemoryListener *listener,

                          MemoryRegionSection *section)

{

    int r;

    r = kvm_dirty_pages_log_change(section->offset_within_address_space,

                                   int128_get64(section->size), true);

    if (r < 0) {

        abort();

    }

}


int tcp_socket_outgoing_spec(const char *address_and_port)

{

    return inet_connect(address_and_port, true, NULL);

}


static int blk_get_request(struct XenBlkDev *blkdev, struct ioreq *ioreq, RING_IDX rc)

{

    switch (blkdev->protocol) {

    case BLKIF_PROTOCOL_NATIVE:

        memcpy(&ioreq->req, RING_GET_REQUEST(&blkdev->rings.native, rc),

               sizeof(ioreq->req));

        break;

    case BLKIF_PROTOCOL_X86_32:

        blkif_get_x86_32_req(&ioreq->req,

                             RING_GET_REQUEST(&blkdev->rings.x86_32_part, rc));

        break;

    case BLKIF_PROTOCOL_X86_64:

        blkif_get_x86_64_req(&ioreq->req,

                             RING_GET_REQUEST(&blkdev->rings.x86_64_part, rc));

        break;

    }

    return 0;

}


static int msrle_decode_pal4(AVCodecContext *avctx, AVPicture *pic,

                             GetByteContext *gb)

{

    unsigned char rle_code;

    unsigned char extra_byte, odd_pixel;

    unsigned char stream_byte;

    unsigned int pixel_ptr = 0;

    int row_dec = pic->linesize[0];

    int row_ptr = (avctx->height - 1) * row_dec;

    int frame_size = row_dec * avctx->height;

    int i;

    while (row_ptr >= 0) {

        if (bytestream2_get_bytes_left(gb) <= 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "MS RLE: bytestream overrun, %d rows left\n",

                   row_ptr);

            return AVERROR_INVALIDDATA;

        }

        rle_code = stream_byte = bytestream2_get_byteu(gb);

        if (rle_code == 0) {

            /* fetch the next byte to see how to handle escape code */

            stream_byte = bytestream2_get_byte(gb);

            if (stream_byte == 0) {

                /* line is done, goto the next one */

                row_ptr -= row_dec;

                pixel_ptr = 0;

            } else if (stream_byte == 1) {

                /* decode is done */

                return 0;

            } else if (stream_byte == 2) {

                /* reposition frame decode coordinates */

                stream_byte = bytestream2_get_byte(gb);

                pixel_ptr += stream_byte;

                stream_byte = bytestream2_get_byte(gb);

                row_ptr -= stream_byte * row_dec;

            } else {

                // copy pixels from encoded stream

                odd_pixel =  stream_byte & 1;

                rle_code = (stream_byte + 1) / 2;

                extra_byte = rle_code & 0x01;

                if (row_ptr + pixel_ptr + stream_byte > frame_size ||

                    bytestream2_get_bytes_left(gb) < rle_code) {

                    av_log(avctx, AV_LOG_ERROR,

                           "MS RLE: frame/stream ptr just went out of bounds (copy)\n");

                    return AVERROR_INVALIDDATA;

                }

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

                    if (pixel_ptr >= avctx->width)

                        break;

                    stream_byte = bytestream2_get_byteu(gb);

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;

                    pixel_ptr++;

                    if (i + 1 == rle_code && odd_pixel)

                        break;

                    if (pixel_ptr >= avctx->width)

                        break;

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;

                    pixel_ptr++;

                }

                // if the RLE code is odd, skip a byte in the stream

                if (extra_byte)

                    bytestream2_skip(gb, 1);

            }

        } else {

            // decode a run of data

            if (row_ptr + pixel_ptr + stream_byte > frame_size) {

                av_log(avctx, AV_LOG_ERROR,

                       "MS RLE: frame ptr just went out of bounds (run)\n");

                return AVERROR_INVALIDDATA;

            }

            stream_byte = bytestream2_get_byte(gb);

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

                if (pixel_ptr >= avctx->width)

                    break;

                if ((i & 1) == 0)

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;

                else

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;

                pixel_ptr++;

            }

        }

    }

    /* one last sanity check on the way out */

    if (bytestream2_get_bytes_left(gb)) {

        av_log(avctx, AV_LOG_ERROR,

               "MS RLE: ended frame decode with %d bytes left over\n",

               bytestream2_get_bytes_left(gb));

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


void blk_remove_bs(BlockBackend *blk)

{

    assert(blk->root->bs->blk == blk);

    notifier_list_notify(&blk->remove_bs_notifiers, blk);

    if (blk->public.throttle_state) {

        throttle_timers_detach_aio_context(&blk->public.throttle_timers);

    }

    blk_update_root_state(blk);

    blk->root->bs->blk = NULL;

    bdrv_root_unref_child(blk->root);

    blk->root = NULL;

}


static int vnc_display_get_addresses(QemuOpts *opts,

                                     bool reverse,

                                     SocketAddressLegacy ***retsaddr,

                                     size_t *retnsaddr,

                                     SocketAddressLegacy ***retwsaddr,

                                     size_t *retnwsaddr,

                                     Error **errp)

{

    SocketAddressLegacy *saddr = NULL;

    SocketAddressLegacy *wsaddr = NULL;

    QemuOptsIter addriter;

    const char *addr;

    int to = qemu_opt_get_number(opts, "to", 0);

    bool has_ipv4 = qemu_opt_get(opts, "ipv4");

    bool has_ipv6 = qemu_opt_get(opts, "ipv6");

    bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);

    bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);

    size_t i;

    int displaynum = -1;

    int ret = -1;

    *retsaddr = NULL;

    *retnsaddr = 0;

    *retwsaddr = NULL;

    *retnwsaddr = 0;

    addr = qemu_opt_get(opts, "vnc");

    if (addr == NULL || g_str_equal(addr, "none")) {

        ret = 0;

        goto cleanup;

    }

    if (qemu_opt_get(opts, "websocket") &&

        !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {

        error_setg(errp,

                   "SHA1 hash support is required for websockets");

        goto cleanup;

    }

    qemu_opt_iter_init(&addriter, opts, "vnc");

    while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {

        int rv;

        rv = vnc_display_get_address(addr, false, reverse, 0, to,

                                     has_ipv4, has_ipv6,

                                     ipv4, ipv6,

                                     &saddr, errp);

        if (rv < 0) {

            goto cleanup;

        }

        /* Historical compat - first listen address can be used

         * to set the default websocket port

         */

        if (displaynum == -1) {

            displaynum = rv;

        }

        *retsaddr = g_renew(SocketAddressLegacy *, *retsaddr, *retnsaddr + 1);

        (*retsaddr)[(*retnsaddr)++] = saddr;

    }

    /* If we had multiple primary displays, we don't do defaults

     * for websocket, and require explicit config instead. */

    if (*retnsaddr > 1) {

        displaynum = -1;

    }

    qemu_opt_iter_init(&addriter, opts, "websocket");

    while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {

        if (vnc_display_get_address(addr, true, reverse, displaynum, to,

                                    has_ipv4, has_ipv6,

                                    ipv4, ipv6,

                                    &wsaddr, errp) < 0) {

            goto cleanup;

        }

        /* Historical compat - if only a single listen address was

         * provided, then this is used to set the default listen

         * address for websocket too

         */

        if (*retnsaddr == 1 &&

            (*retsaddr)[0]->type == SOCKET_ADDRESS_LEGACY_KIND_INET &&

            wsaddr->type == SOCKET_ADDRESS_LEGACY_KIND_INET &&

            g_str_equal(wsaddr->u.inet.data->host, "") &&

            !g_str_equal((*retsaddr)[0]->u.inet.data->host, "")) {

            g_free(wsaddr->u.inet.data->host);

            wsaddr->u.inet.data->host =

                g_strdup((*retsaddr)[0]->u.inet.data->host);

        }

        *retwsaddr = g_renew(SocketAddressLegacy *, *retwsaddr, *retnwsaddr + 1);

        (*retwsaddr)[(*retnwsaddr)++] = wsaddr;

    }

    ret = 0;

 cleanup:

    if (ret < 0) {

        for (i = 0; i < *retnsaddr; i++) {

            qapi_free_SocketAddressLegacy((*retsaddr)[i]);

        }

        g_free(*retsaddr);

        for (i = 0; i < *retnwsaddr; i++) {

            qapi_free_SocketAddressLegacy((*retwsaddr)[i]);

        }

        g_free(*retwsaddr);

        *retsaddr = *retwsaddr = NULL;

        *retnsaddr = *retnwsaddr = 0;

    }

    return ret;

}


static void gen_logicq_cc(TCGv val)

{

    TCGv tmp = new_tmp();

    gen_helper_logicq_cc(tmp, val);

    gen_logic_CC(tmp);

    dead_tmp(tmp);

}


static int64_t nfs_client_open(NFSClient *client, QDict *options,

                               int flags, int open_flags, Error **errp)

{

    int ret = -EINVAL;

    QemuOpts *opts = NULL;

    Error *local_err = NULL;

    struct stat st;

    char *file = NULL, *strp = NULL;

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    client->path = g_strdup(qemu_opt_get(opts, "path"));

    if (!client->path) {

        ret = -EINVAL;

        error_setg(errp, "No path was specified");

        goto fail;

    }

    strp = strrchr(client->path, '/');

    if (strp == NULL) {

        error_setg(errp, "Invalid URL specified");

        goto fail;

    }

    file = g_strdup(strp);

    *strp = 0;

    /* Pop the config into our state object, Exit if invalid */

    client->server = nfs_config(options, errp);

    if (!client->server) {

        ret = -EINVAL;

        goto fail;

    }

    client->context = nfs_init_context();

    if (client->context == NULL) {

        error_setg(errp, "Failed to init NFS context");

        goto fail;

    }

    if (qemu_opt_get(opts, "user")) {

        client->uid = qemu_opt_get_number(opts, "user", 0);

        nfs_set_uid(client->context, client->uid);

    }

    if (qemu_opt_get(opts, "group")) {

        client->gid = qemu_opt_get_number(opts, "group", 0);

        nfs_set_gid(client->context, client->gid);

    }

    if (qemu_opt_get(opts, "tcp-syn-count")) {

        client->tcp_syncnt = qemu_opt_get_number(opts, "tcp-syn-count", 0);

        nfs_set_tcp_syncnt(client->context, client->tcp_syncnt);

    }

#ifdef LIBNFS_FEATURE_READAHEAD

    if (qemu_opt_get(opts, "readahead-size")) {

        if (open_flags & BDRV_O_NOCACHE) {

            error_setg(errp, "Cannot enable NFS readahead "

                             "if cache.direct = on");

            goto fail;

        }

        client->readahead = qemu_opt_get_number(opts, "readahead-size", 0);

        if (client->readahead > QEMU_NFS_MAX_READAHEAD_SIZE) {

            error_report("NFS Warning: Truncating NFS readahead "

                         "size to %d", QEMU_NFS_MAX_READAHEAD_SIZE);

            client->readahead = QEMU_NFS_MAX_READAHEAD_SIZE;

        }

        nfs_set_readahead(client->context, client->readahead);

#ifdef LIBNFS_FEATURE_PAGECACHE

        nfs_set_pagecache_ttl(client->context, 0);

#endif

        client->cache_used = true;

    }

#endif

#ifdef LIBNFS_FEATURE_PAGECACHE

    if (qemu_opt_get(opts, "page-cache-size")) {

        if (open_flags & BDRV_O_NOCACHE) {

            error_setg(errp, "Cannot enable NFS pagecache "

                             "if cache.direct = on");

            goto fail;

        }

        client->pagecache = qemu_opt_get_number(opts, "page-cache-size", 0);

        if (client->pagecache > QEMU_NFS_MAX_PAGECACHE_SIZE) {

            error_report("NFS Warning: Truncating NFS pagecache "

                         "size to %d pages", QEMU_NFS_MAX_PAGECACHE_SIZE);

            client->pagecache = QEMU_NFS_MAX_PAGECACHE_SIZE;

        }

        nfs_set_pagecache(client->context, client->pagecache);

        nfs_set_pagecache_ttl(client->context, 0);

        client->cache_used = true;

    }

#endif

#ifdef LIBNFS_FEATURE_DEBUG

    if (qemu_opt_get(opts, "debug")) {

        client->debug = qemu_opt_get_number(opts, "debug", 0);

        /* limit the maximum debug level to avoid potential flooding

         * of our log files. */

        if (client->debug > QEMU_NFS_MAX_DEBUG_LEVEL) {

            error_report("NFS Warning: Limiting NFS debug level "

                         "to %d", QEMU_NFS_MAX_DEBUG_LEVEL);

            client->debug = QEMU_NFS_MAX_DEBUG_LEVEL;

        }

        nfs_set_debug(client->context, client->debug);

    }

#endif

    ret = nfs_mount(client->context, client->server->host, client->path);

    if (ret < 0) {

        error_setg(errp, "Failed to mount nfs share: %s",

                   nfs_get_error(client->context));

        goto fail;

    }

    if (flags & O_CREAT) {

        ret = nfs_creat(client->context, file, 0600, &client->fh);

        if (ret < 0) {

            error_setg(errp, "Failed to create file: %s",

                       nfs_get_error(client->context));

            goto fail;

        }

    } else {

        ret = nfs_open(client->context, file, flags, &client->fh);

        if (ret < 0) {

            error_setg(errp, "Failed to open file : %s",

                       nfs_get_error(client->context));

            goto fail;

        }

    }

    ret = nfs_fstat(client->context, client->fh, &st);

    if (ret < 0) {

        error_setg(errp, "Failed to fstat file: %s",

                   nfs_get_error(client->context));

        goto fail;

    }

    ret = DIV_ROUND_UP(st.st_size, BDRV_SECTOR_SIZE);

    client->st_blocks = st.st_blocks;

    client->has_zero_init = S_ISREG(st.st_mode);

    *strp = '/';

    goto out;

fail:

    nfs_client_close(client);

out:

    qemu_opts_del(opts);

    g_free(file);

    return ret;

}


static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)

{

    AVStream *st = av_new_stream(pes->stream, pes->pid);

    if (!st)

        return NULL;

    av_set_pts_info(st, 33, 1, 90000);

    st->priv_data = pes;

    st->codec->codec_type = CODEC_TYPE_DATA;

    st->codec->codec_id   = CODEC_ID_NONE;

    st->need_parsing = AVSTREAM_PARSE_FULL;

    pes->st = st;

    dprintf(pes->stream, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",

            pes->stream_type, pes->pid, (char*)&prog_reg_desc);

    st->codec->codec_tag = pes->stream_type;

    mpegts_find_stream_type(st, pes->stream_type, ISO_types);

    if (prog_reg_desc == AV_RL32("HDMV") &&

        st->codec->codec_id == CODEC_ID_NONE) {

        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);

        if (pes->stream_type == 0x83) {

            // HDMV TrueHD streams also contain an AC3 coded version of the

            // audio track - add a second stream for this

            AVStream *sub_st;

            // priv_data cannot be shared between streams

            PESContext *sub_pes = av_malloc(sizeof(*sub_pes));

            if (!sub_pes)

                return NULL;

            memcpy(sub_pes, pes, sizeof(*sub_pes));

            sub_st = av_new_stream(pes->stream, pes->pid);

            if (!sub_st) {

                av_free(sub_pes);

                return NULL;

            }

            av_set_pts_info(sub_st, 33, 1, 90000);

            sub_st->priv_data = sub_pes;

            sub_st->codec->codec_type = CODEC_TYPE_AUDIO;

            sub_st->codec->codec_id   = CODEC_ID_AC3;

            sub_st->need_parsing = AVSTREAM_PARSE_FULL;

            sub_pes->sub_st = pes->sub_st = sub_st;

        }

    }

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

        mpegts_find_stream_type(st, pes->stream_type, MISC_types);

    /* stream was not present in PMT, guess based on PES start code */

    if (st->codec->codec_id == CODEC_ID_NONE) {

        if (code >= 0x1c0 && code <= 0x1df) {

            st->codec->codec_type = CODEC_TYPE_AUDIO;

            st->codec->codec_id = CODEC_ID_MP2;

        } else if (code == 0x1bd) {

            st->codec->codec_type = CODEC_TYPE_AUDIO;

            st->codec->codec_id = CODEC_ID_AC3;

        }

    }

    return st;

}


BlockAIOCB *dma_bdrv_io(

    BlockDriverState *bs, QEMUSGList *sg, uint64_t sector_num,

    DMAIOFunc *io_func, BlockCompletionFunc *cb,

    void *opaque, DMADirection dir)

{

    DMAAIOCB *dbs = qemu_aio_get(&dma_aiocb_info, bs, cb, opaque);

    trace_dma_bdrv_io(dbs, bs, sector_num, (dir == DMA_DIRECTION_TO_DEVICE));

    dbs->acb = NULL;

    dbs->bs = bs;

    dbs->sg = sg;

    dbs->sector_num = sector_num;

    dbs->sg_cur_index = 0;

    dbs->sg_cur_byte = 0;

    dbs->dir = dir;

    dbs->io_func = io_func;

    dbs->bh = NULL;

    qemu_iovec_init(&dbs->iov, sg->nsg);

    dma_bdrv_cb(dbs, 0);

    return &dbs->common;

}


void helper_ldl_l_raw(uint64_t t0, uint64_t t1)

{

    env->lock = t1;

    ldl_raw(t1, t0);

}


static void assign_storage(SCLPDevice *sclp, SCCB *sccb)

{

    MemoryRegion *mr = NULL;

    uint64_t this_subregion_size;

    AssignStorage *assign_info = (AssignStorage *) sccb;

    sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();

    assert(mhd);

    ram_addr_t assign_addr = (assign_info->rn - 1) * mhd->rzm;

    MemoryRegion *sysmem = get_system_memory();

    if ((assign_addr % MEM_SECTION_SIZE == 0) &&

        (assign_addr >= mhd->padded_ram_size)) {

        /* Re-use existing memory region if found */

        mr = memory_region_find(sysmem, assign_addr, 1).mr;

        memory_region_unref(mr);

        if (!mr) {

            MemoryRegion *standby_ram = g_new(MemoryRegion, 1);

            /* offset to align to standby_subregion_size for allocation */

            ram_addr_t offset = assign_addr -

                                (assign_addr - mhd->padded_ram_size)

                                % mhd->standby_subregion_size;

            /* strlen("standby.ram") + 4 (Max of KVM_MEMORY_SLOTS) +  NULL */

            char id[16];

            snprintf(id, 16, "standby.ram%d",

                     (int)((offset - mhd->padded_ram_size) /

                     mhd->standby_subregion_size) + 1);

            /* Allocate a subregion of the calculated standby_subregion_size */

            if (offset + mhd->standby_subregion_size >

                mhd->padded_ram_size + mhd->standby_mem_size) {

                this_subregion_size = mhd->padded_ram_size +

                  mhd->standby_mem_size - offset;

            } else {

                this_subregion_size = mhd->standby_subregion_size;

            }

            memory_region_init_ram(standby_ram, NULL, id, this_subregion_size, &error_abort);

            /* This is a hack to make memory hotunplug work again. Once we have

             * subdevices, we have to unparent them when unassigning memory,

             * instead of doing it via the ref count of the MemoryRegion. */

            object_ref(OBJECT(standby_ram));

            object_unparent(OBJECT(standby_ram));

            vmstate_register_ram_global(standby_ram);

            memory_region_add_subregion(sysmem, offset, standby_ram);

        }

        /* The specified subregion is no longer in standby */

        mhd->standby_state_map[(assign_addr - mhd->padded_ram_size)

                               / MEM_SECTION_SIZE] = 1;

    }

    sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION);

}


static void dump_aml_files(test_data *data)

{

    AcpiSdtTable *sdt;

    GError *error = NULL;

    gint fd;

    ssize_t ret;

    int i;

    for (i = 0; i < data->ssdt_tables->len; ++i) {

        sdt = &g_array_index(data->ssdt_tables, AcpiSdtTable, i);

        g_assert(sdt->aml);

        fd = g_file_open_tmp("aml-XXXXXX", &sdt->aml_file, &error);

        g_assert_no_error(error);

        ret = qemu_write_full(fd, sdt, sizeof(AcpiTableHeader));

        g_assert(ret == sizeof(AcpiTableHeader));

        ret = qemu_write_full(fd, sdt->aml, sdt->aml_len);

        g_assert(ret == sdt->aml_len);

        close(fd);

    }

}


void ff_er_frame_end(MpegEncContext *s){

    int i, mb_x, mb_y, error, error_type, dc_error, mv_error, ac_error;

    int distance;

    int threshold_part[4]= {100,100,100};

    int threshold= 50;

    int is_intra_likely;

    int size = s->b8_stride * 2 * s->mb_height;

    Picture *pic= s->current_picture_ptr;

    if(!s->error_recognition || s->error_count==0 || s->avctx->lowres ||

       s->avctx->hwaccel ||

       s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU ||

       s->error_count==3*s->mb_width*(s->avctx->skip_top + s->avctx->skip_bottom)) return;

    if(s->current_picture.motion_val[0] == NULL){

        av_log(s->avctx, AV_LOG_ERROR, "Warning MVs not available\n");

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

            pic->ref_index[i]= av_mallocz(size * sizeof(uint8_t));

            pic->motion_val_base[i]= av_mallocz((size+4) * 2 * sizeof(uint16_t));

            pic->motion_val[i]= pic->motion_val_base[i]+4;

        }

        pic->motion_subsample_log2= 3;

        s->current_picture= *s->current_picture_ptr;

    }

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

        if(pic->ref_index[i])

            memset(pic->ref_index[i], 0, size * sizeof(uint8_t));

    }

    if(s->avctx->debug&FF_DEBUG_ER){

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

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

                int status= s->error_status_table[mb_x + mb_y*s->mb_stride];

                av_log(s->avctx, AV_LOG_DEBUG, "%2X ", status);

            }

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

        }

    }

#if 1

    /* handle overlapping slices */

    for(error_type=1; error_type<=3; error_type++){

        int end_ok=0;

        for(i=s->mb_num-1; i>=0; i--){

            const int mb_xy= s->mb_index2xy[i];

            int error= s->error_status_table[mb_xy];

            if(error&(1<<error_type))

                end_ok=1;

            if(error&(8<<error_type))

                end_ok=1;

            if(!end_ok)

                s->error_status_table[mb_xy]|= 1<<error_type;

            if(error&VP_START)

                end_ok=0;

        }

    }

#endif

#if 1

    /* handle slices with partitions of different length */

    if(s->partitioned_frame){

        int end_ok=0;

        for(i=s->mb_num-1; i>=0; i--){

            const int mb_xy= s->mb_index2xy[i];

            int error= s->error_status_table[mb_xy];

            if(error&AC_END)

                end_ok=0;

            if((error&MV_END) || (error&DC_END) || (error&AC_ERROR))

                end_ok=1;

            if(!end_ok)

                s->error_status_table[mb_xy]|= AC_ERROR;

            if(error&VP_START)

                end_ok=0;

        }

    }

#endif

    /* handle missing slices */

    if(s->error_recognition>=4){

        int end_ok=1;

        for(i=s->mb_num-2; i>=s->mb_width+100; i--){ //FIXME +100 hack

            const int mb_xy= s->mb_index2xy[i];

            int error1= s->error_status_table[mb_xy  ];

            int error2= s->error_status_table[s->mb_index2xy[i+1]];

            if(error1&VP_START)

                end_ok=1;

            if(   error2==(VP_START|DC_ERROR|AC_ERROR|MV_ERROR|AC_END|DC_END|MV_END)

               && error1!=(VP_START|DC_ERROR|AC_ERROR|MV_ERROR|AC_END|DC_END|MV_END)

               && ((error1&AC_END) || (error1&DC_END) || (error1&MV_END))){ //end & uninit

                end_ok=0;

            }

            if(!end_ok)

                s->error_status_table[mb_xy]|= DC_ERROR|AC_ERROR|MV_ERROR;

        }

    }

#if 1

    /* backward mark errors */

    distance=9999999;

    for(error_type=1; error_type<=3; error_type++){

        for(i=s->mb_num-1; i>=0; i--){

            const int mb_xy= s->mb_index2xy[i];

            int error= s->error_status_table[mb_xy];

            if(!s->mbskip_table[mb_xy]) //FIXME partition specific

                distance++;

            if(error&(1<<error_type))

                distance= 0;

            if(s->partitioned_frame){

                if(distance < threshold_part[error_type-1])

                    s->error_status_table[mb_xy]|= 1<<error_type;

            }else{

                if(distance < threshold)

                    s->error_status_table[mb_xy]|= 1<<error_type;

            }

            if(error&VP_START)

                distance= 9999999;

        }

    }

#endif

    /* forward mark errors */

    error=0;

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

        const int mb_xy= s->mb_index2xy[i];

        int old_error= s->error_status_table[mb_xy];

        if(old_error&VP_START)

            error= old_error& (DC_ERROR|AC_ERROR|MV_ERROR);

        else{

            error|= old_error& (DC_ERROR|AC_ERROR|MV_ERROR);

            s->error_status_table[mb_xy]|= error;

        }

    }

#if 1

    /* handle not partitioned case */

    if(!s->partitioned_frame){

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

            const int mb_xy= s->mb_index2xy[i];

            error= s->error_status_table[mb_xy];

            if(error&(AC_ERROR|DC_ERROR|MV_ERROR))

                error|= AC_ERROR|DC_ERROR|MV_ERROR;

            s->error_status_table[mb_xy]= error;

        }

    }

#endif

    dc_error= ac_error= mv_error=0;

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

        const int mb_xy= s->mb_index2xy[i];

        error= s->error_status_table[mb_xy];

        if(error&DC_ERROR) dc_error ++;

        if(error&AC_ERROR) ac_error ++;

        if(error&MV_ERROR) mv_error ++;

    }

    av_log(s->avctx, AV_LOG_INFO, "concealing %d DC, %d AC, %d MV errors\n", dc_error, ac_error, mv_error);

    is_intra_likely= is_intra_more_likely(s);

    /* set unknown mb-type to most likely */

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

        const int mb_xy= s->mb_index2xy[i];

        error= s->error_status_table[mb_xy];

        if(!((error&DC_ERROR) && (error&MV_ERROR)))

            continue;

        if(is_intra_likely)

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

        else

            s->current_picture.mb_type[mb_xy]= MB_TYPE_16x16 | MB_TYPE_L0;

    }

    // change inter to intra blocks if no reference frames are available

    if (!s->last_picture.data[0] && !s->next_picture.data[0])

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

            const int mb_xy= s->mb_index2xy[i];

            if(!IS_INTRA(s->current_picture.mb_type[mb_xy]))

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

        }

    /* handle inter blocks with damaged AC */

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

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

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

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

            int dir = !s->last_picture.data[0];

            error= s->error_status_table[mb_xy];

            if(IS_INTRA(mb_type)) continue; //intra

            if(error&MV_ERROR) continue;              //inter with damaged MV

            if(!(error&AC_ERROR)) continue;           //undamaged inter

            s->mv_dir = dir ? MV_DIR_BACKWARD : MV_DIR_FORWARD;

            s->mb_intra=0;

            s->mb_skipped=0;

            if(IS_8X8(mb_type)){

                int mb_index= mb_x*2 + mb_y*2*s->b8_stride;

                int j;

                s->mv_type = MV_TYPE_8X8;

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

                    s->mv[0][j][0] = s->current_picture.motion_val[dir][ mb_index + (j&1) + (j>>1)*s->b8_stride ][0];

                    s->mv[0][j][1] = s->current_picture.motion_val[dir][ mb_index + (j&1) + (j>>1)*s->b8_stride ][1];

                }

            }else{

                s->mv_type = MV_TYPE_16X16;

                s->mv[0][0][0] = s->current_picture.motion_val[dir][ mb_x*2 + mb_y*2*s->b8_stride ][0];

                s->mv[0][0][1] = s->current_picture.motion_val[dir][ mb_x*2 + mb_y*2*s->b8_stride ][1];

            }

            s->dsp.clear_blocks(s->block[0]);

            s->mb_x= mb_x;

            s->mb_y= mb_y;

            decode_mb(s);

        }

    }

    /* guess MVs */

    if(s->pict_type==FF_B_TYPE){

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

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

                int xy= mb_x*2 + mb_y*2*s->b8_stride;

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

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

                error= s->error_status_table[mb_xy];

                if(IS_INTRA(mb_type)) continue;

                if(!(error&MV_ERROR)) continue;           //inter with undamaged MV

                if(!(error&AC_ERROR)) continue;           //undamaged inter

                s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD;

                if(!s->last_picture.data[0]) s->mv_dir &= ~MV_DIR_FORWARD;

                if(!s->next_picture.data[0]) s->mv_dir &= ~MV_DIR_BACKWARD;

                s->mb_intra=0;

                s->mv_type = MV_TYPE_16X16;

                s->mb_skipped=0;

                if(s->pp_time){

                    int time_pp= s->pp_time;

                    int time_pb= s->pb_time;

                    s->mv[0][0][0] = s->next_picture.motion_val[0][xy][0]*time_pb/time_pp;

                    s->mv[0][0][1] = s->next_picture.motion_val[0][xy][1]*time_pb/time_pp;

                    s->mv[1][0][0] = s->next_picture.motion_val[0][xy][0]*(time_pb - time_pp)/time_pp;

                    s->mv[1][0][1] = s->next_picture.motion_val[0][xy][1]*(time_pb - time_pp)/time_pp;

                }else{

                    s->mv[0][0][0]= 0;

                    s->mv[0][0][1]= 0;

                    s->mv[1][0][0]= 0;

                    s->mv[1][0][1]= 0;

                }

                s->dsp.clear_blocks(s->block[0]);

                s->mb_x= mb_x;

                s->mb_y= mb_y;

                decode_mb(s);

            }

        }

    }else

        guess_mv(s);

    /* the filters below are not XvMC compatible, skip them */

    if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)

        goto ec_clean;

    /* fill DC for inter blocks */

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

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

            int dc, dcu, dcv, y, n;

            int16_t *dc_ptr;

            uint8_t *dest_y, *dest_cb, *dest_cr;

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

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

            error= s->error_status_table[mb_xy];

            if(IS_INTRA(mb_type) && s->partitioned_frame) continue;

//            if(error&MV_ERROR) continue; //inter data damaged FIXME is this good?

            dest_y = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize;

            dest_cb= s->current_picture.data[1] + mb_x*8  + mb_y*8 *s->uvlinesize;

            dest_cr= s->current_picture.data[2] + mb_x*8  + mb_y*8 *s->uvlinesize;

            dc_ptr= &s->dc_val[0][mb_x*2 + mb_y*2*s->b8_stride];

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

                dc=0;

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

                    int x;

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

                       dc+= dest_y[x + (n&1)*8 + (y + (n>>1)*8)*s->linesize];

                    }

                }

                dc_ptr[(n&1) + (n>>1)*s->b8_stride]= (dc+4)>>3;

            }

            dcu=dcv=0;

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

                int x;

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

                    dcu+=dest_cb[x + y*(s->uvlinesize)];

                    dcv+=dest_cr[x + y*(s->uvlinesize)];

                }

            }

            s->dc_val[1][mb_x + mb_y*s->mb_stride]= (dcu+4)>>3;

            s->dc_val[2][mb_x + mb_y*s->mb_stride]= (dcv+4)>>3;

        }

    }

#if 1

    /* guess DC for damaged blocks */

    guess_dc(s, s->dc_val[0], s->mb_width*2, s->mb_height*2, s->b8_stride, 1);

    guess_dc(s, s->dc_val[1], s->mb_width  , s->mb_height  , s->mb_stride, 0);

    guess_dc(s, s->dc_val[2], s->mb_width  , s->mb_height  , s->mb_stride, 0);

#endif

    /* filter luma DC */

    filter181(s->dc_val[0], s->mb_width*2, s->mb_height*2, s->b8_stride);

#if 1

    /* render DC only intra */

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

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

            uint8_t *dest_y, *dest_cb, *dest_cr;

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

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

            error= s->error_status_table[mb_xy];

            if(IS_INTER(mb_type)) continue;

            if(!(error&AC_ERROR)) continue;              //undamaged

            dest_y = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize;

            dest_cb= s->current_picture.data[1] + mb_x*8  + mb_y*8 *s->uvlinesize;

            dest_cr= s->current_picture.data[2] + mb_x*8  + mb_y*8 *s->uvlinesize;

            put_dc(s, dest_y, dest_cb, dest_cr, mb_x, mb_y);

        }

    }

#endif

    if(s->avctx->error_concealment&FF_EC_DEBLOCK){

        /* filter horizontal block boundaries */

        h_block_filter(s, s->current_picture.data[0], s->mb_width*2, s->mb_height*2, s->linesize  , 1);

        h_block_filter(s, s->current_picture.data[1], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

        h_block_filter(s, s->current_picture.data[2], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

        /* filter vertical block boundaries */

        v_block_filter(s, s->current_picture.data[0], s->mb_width*2, s->mb_height*2, s->linesize  , 1);

        v_block_filter(s, s->current_picture.data[1], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

        v_block_filter(s, s->current_picture.data[2], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

    }

ec_clean:

    /* clean a few tables */

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

        const int mb_xy= s->mb_index2xy[i];

        int error= s->error_status_table[mb_xy];

        if(s->pict_type!=FF_B_TYPE && (error&(DC_ERROR|MV_ERROR|AC_ERROR))){

            s->mbskip_table[mb_xy]=0;

        }

        s->mbintra_table[mb_xy]=1;

    }

}


static int matroska_deliver_packet(MatroskaDemuxContext *matroska,

                                   AVPacket *pkt)

{

    if (matroska->num_packets > 0) {

        memcpy(pkt, matroska->packets[0], sizeof(AVPacket));

        av_free(matroska->packets[0]);

        if (matroska->num_packets > 1) {

            memmove(&matroska->packets[0], &matroska->packets[1],

                    (matroska->num_packets - 1) * sizeof(AVPacket *));

            matroska->packets =

                av_realloc(matroska->packets, (matroska->num_packets - 1) *

                           sizeof(AVPacket *));

        } else {

            av_freep(&matroska->packets);

        }

        matroska->num_packets--;

        return 0;

    }

    return -1;

}


static int vc1_parse_init(AVCodecParserContext *s)

{

    VC1ParseContext *vpc = s->priv_data;

    vpc->v.s.slice_context_count = 1;

    return 0;

}