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

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    SysBusDevice *s = SYS_BUS_DEVICE(dev);

    sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);

    PCIHostState *phb = PCI_HOST_BRIDGE(s);

    sPAPRPHBClass *info = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(s);

    char *namebuf;

    int i;

    PCIBus *bus;

    uint64_t msi_window_size = 4096;

    if (sphb->index != (uint32_t)-1) {

        hwaddr windows_base;

        if ((sphb->buid != (uint64_t)-1) || (sphb->dma_liobn != (uint32_t)-1)

            || (sphb->mem_win_addr != (hwaddr)-1)

            || (sphb->io_win_addr != (hwaddr)-1)) {

            error_setg(errp, "Either \"index\" or other parameters must"

                       " be specified for PAPR PHB, not both");

            return;

        }

        if (sphb->index > SPAPR_PCI_MAX_INDEX) {

            error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",

                       SPAPR_PCI_MAX_INDEX);

            return;

        }

        sphb->buid = SPAPR_PCI_BASE_BUID + sphb->index;

        sphb->dma_liobn = SPAPR_PCI_LIOBN(sphb->index, 0);

        windows_base = SPAPR_PCI_WINDOW_BASE

            + sphb->index * SPAPR_PCI_WINDOW_SPACING;

        sphb->mem_win_addr = windows_base + SPAPR_PCI_MMIO_WIN_OFF;

        sphb->io_win_addr = windows_base + SPAPR_PCI_IO_WIN_OFF;

    }

    if (sphb->buid == (uint64_t)-1) {

        error_setg(errp, "BUID not specified for PHB");

        return;

    }

    if (sphb->dma_liobn == (uint32_t)-1) {

        error_setg(errp, "LIOBN not specified for PHB");

        return;

    }

    if (sphb->mem_win_addr == (hwaddr)-1) {

        error_setg(errp, "Memory window address not specified for PHB");

        return;

    }

    if (sphb->io_win_addr == (hwaddr)-1) {

        error_setg(errp, "IO window address not specified for PHB");

        return;

    }

    if (spapr_pci_find_phb(spapr, sphb->buid)) {

        error_setg(errp, "PCI host bridges must have unique BUIDs");

        return;

    }

    sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);

    namebuf = alloca(strlen(sphb->dtbusname) + 32);

    /* Initialize memory regions */

    sprintf(namebuf, "%s.mmio", sphb->dtbusname);

    memory_region_init(&sphb->memspace, OBJECT(sphb), namebuf, UINT64_MAX);

    sprintf(namebuf, "%s.mmio-alias", sphb->dtbusname);

    memory_region_init_alias(&sphb->memwindow, OBJECT(sphb),

                             namebuf, &sphb->memspace,

                             SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);

    memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,

                                &sphb->memwindow);

    /* Initialize IO regions */

    sprintf(namebuf, "%s.io", sphb->dtbusname);

    memory_region_init(&sphb->iospace, OBJECT(sphb),

                       namebuf, SPAPR_PCI_IO_WIN_SIZE);

    sprintf(namebuf, "%s.io-alias", sphb->dtbusname);

    memory_region_init_alias(&sphb->iowindow, OBJECT(sphb), namebuf,

                             &sphb->iospace, 0, SPAPR_PCI_IO_WIN_SIZE);

    memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,

                                &sphb->iowindow);

    bus = pci_register_bus(dev, NULL,

                           pci_spapr_set_irq, pci_spapr_map_irq, sphb,

                           &sphb->memspace, &sphb->iospace,

                           PCI_DEVFN(0, 0), PCI_NUM_PINS, TYPE_PCI_BUS);

    phb->bus = bus;

    qbus_set_hotplug_handler(BUS(phb->bus), DEVICE(sphb), NULL);

    /*

     * Initialize PHB address space.

     * By default there will be at least one subregion for default

     * 32bit DMA window.

     * Later the guest might want to create another DMA window

     * which will become another memory subregion.

     */

    sprintf(namebuf, "%s.iommu-root", sphb->dtbusname);

    memory_region_init(&sphb->iommu_root, OBJECT(sphb),

                       namebuf, UINT64_MAX);

    address_space_init(&sphb->iommu_as, &sphb->iommu_root,

                       sphb->dtbusname);

    /*

     * As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,

     * we need to allocate some memory to catch those writes coming

     * from msi_notify()/msix_notify().

     * As MSIMessage:addr is going to be the same and MSIMessage:data

     * is going to be a VIRQ number, 4 bytes of the MSI MR will only

     * be used.

     *

     * For KVM we want to ensure that this memory is a full page so that

     * our memory slot is of page size granularity.

     */

#ifdef CONFIG_KVM

    if (kvm_enabled()) {

        msi_window_size = getpagesize();

    }

#endif

    memory_region_init_io(&sphb->msiwindow, NULL, &spapr_msi_ops, spapr,

                          "msi", msi_window_size);

    memory_region_add_subregion(&sphb->iommu_root, SPAPR_PCI_MSI_WINDOW,

                                &sphb->msiwindow);

    pci_setup_iommu(bus, spapr_pci_dma_iommu, sphb);

    pci_bus_set_route_irq_fn(bus, spapr_route_intx_pin_to_irq);

    QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);

    /* Initialize the LSI table */

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

        uint32_t irq;

        irq = xics_alloc_block(spapr->icp, 0, 1, true, false);

        if (!irq) {

            error_setg(errp, "spapr_allocate_lsi failed");

            return;

        }

        sphb->lsi_table[i].irq = irq;

    }

    /* allocate connectors for child PCI devices */

    if (sphb->dr_enabled) {

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

            spapr_dr_connector_new(OBJECT(phb),

                                   SPAPR_DR_CONNECTOR_TYPE_PCI,

                                   (sphb->index << 16) | i);

        }

    }

    if (!info->finish_realize) {

        error_setg(errp, "finish_realize not defined");

        return;

    }

    info->finish_realize(sphb, errp);

    sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free);

}


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

                                   int depth, GetByteContext *gb)

{

    uint8_t *output, *output_end;

    int p1, p2, line=avctx->height - 1, pos=0, i;

    uint16_t pix16;

    uint32_t pix32;

    unsigned int width= FFABS(pic->linesize[0]) / (depth >> 3);

    output     = pic->data[0] + (avctx->height - 1) * pic->linesize[0];

    output_end = pic->data[0] +  avctx->height      * pic->linesize[0];

    while (bytestream2_get_bytes_left(gb) > 0) {

        p1 = bytestream2_get_byteu(gb);

        if(p1 == 0) { //Escape code

            p2 = bytestream2_get_byte(gb);

            if(p2 == 0) { //End-of-line

                if (--line < 0) {

                    if (bytestream2_get_be16(gb) == 1) { // end-of-picture

                        return 0;

                    } else {

                        av_log(avctx, AV_LOG_ERROR,

                               "Next line is beyond picture bounds (%d bytes left)\n",

                               bytestream2_get_bytes_left(gb));

                        return AVERROR_INVALIDDATA;

                    }

                }

                output = pic->data[0] + line * pic->linesize[0];

                pos = 0;

                continue;

            } else if(p2 == 1) { //End-of-picture

                return 0;

            } else if(p2 == 2) { //Skip

                p1 = bytestream2_get_byte(gb);

                p2 = bytestream2_get_byte(gb);

                line -= p2;

                pos += p1;

                if (line < 0 || pos >= width){

                    av_log(avctx, AV_LOG_ERROR, "Skip beyond picture bounds\n");

                    return -1;

                }

                output = pic->data[0] + line * pic->linesize[0] + pos * (depth >> 3);

                continue;

            }

            // Copy data

            if ((pic->linesize[0] > 0 && output + p2 * (depth >> 3) > output_end) ||

                (pic->linesize[0] < 0 && output + p2 * (depth >> 3) < output_end)) {

                bytestream2_skip(gb, 2 * (depth >> 3));

                continue;

            } else if (bytestream2_get_bytes_left(gb) < p2 * (depth >> 3)) {

                av_log(avctx, AV_LOG_ERROR, "bytestream overrun\n");

                return AVERROR_INVALIDDATA;

            }

            if ((depth == 8) || (depth == 24)) {

                for(i = 0; i < p2 * (depth >> 3); i++) {

                    *output++ = bytestream2_get_byteu(gb);

                }

                // RLE8 copy is actually padded - and runs are not!

                if(depth == 8 && (p2 & 1)) {

                    bytestream2_skip(gb, 1);

                }

            } else if (depth == 16) {

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

                    *(uint16_t*)output = bytestream2_get_le16u(gb);

                    output += 2;

                }

            } else if (depth == 32) {

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

                    *(uint32_t*)output = bytestream2_get_le32u(gb);

                    output += 4;

                }

            }

            pos += p2;

        } else { //run of pixels

            uint8_t pix[3]; //original pixel

            if ((pic->linesize[0] > 0 && output + p1 * (depth >> 3) > output_end) ||

                (pic->linesize[0] < 0 && output + p1 * (depth >> 3) < output_end))

                continue;

            switch(depth){

            case  8:

                pix[0] = bytestream2_get_byte(gb);

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

                        *output++ = pix[0];

                break;

            case 16:

                pix16  = bytestream2_get_le16(gb);

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

                        *(uint16_t*)output = pix16;

                        output += 2;

                }

                break;

            case 24:

                pix[0] = bytestream2_get_byte(gb);

                pix[1] = bytestream2_get_byte(gb);

                pix[2] = bytestream2_get_byte(gb);

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

                        *output++ = pix[0];

                        *output++ = pix[1];

                        *output++ = pix[2];

                }

                break;

            case 32:

                pix32  = bytestream2_get_le32(gb);

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

                        *(uint32_t*)output = pix32;

                        output += 4;

                }

                break;

            }

            pos += p1;

        }

    }

    av_log(avctx, AV_LOG_WARNING, "MS RLE warning: no end-of-picture code\n");

    return 0;

}


static void RENAME(SwScale_YV12slice)(unsigned char* srcptr[],int stride[], int srcSliceY ,

			     int srcSliceH, uint8_t* dstptr[], int dststride, int dstbpp,

			     int srcW, int srcH, int dstW, int dstH){

unsigned int lumXInc= (srcW << 16) / dstW;

unsigned int lumYInc= (srcH << 16) / dstH;

unsigned int chrXInc;

unsigned int chrYInc;

static int dstY;

// used to detect a size change

static int oldDstW= -1;

static int oldSrcW= -1;

static int oldDstH= -1;

static int oldSrcH= -1;

static int oldFlags=-1;

static int lastInLumBuf;

static int lastInChrBuf;

int chrDstW, chrDstH;

static int lumBufIndex=0;

static int chrBufIndex=0;

static int firstTime=1;

int widthAlign= dstbpp==12 ? 16 : 8;

if(((dstW + widthAlign-1)&(~(widthAlign-1))) > dststride)

{

	dstW&= ~(widthAlign-1);

	if(firstTime)

		fprintf(stderr, "SwScaler: Warning: dstStride is not a multiple of %d!\n"

				"SwScaler: ->lowering width to compensate, new width=%d\n"

				"SwScaler: ->cannot do aligned memory acesses anymore\n",

				widthAlign, dstW);

}

//printf("%d %d %d %d\n", srcW, srcH, dstW, dstH);

//printf("%d %d %d %d\n", lumXInc, lumYInc, srcSliceY, srcSliceH);

#ifdef HAVE_MMX2

canMMX2BeUsed= (lumXInc <= 0x10000 && (dstW&31)==0 && (srcW&15)==0) ? 1 : 0;

if(!canMMX2BeUsed && lumXInc <= 0x10000 && (srcW&15)==0 && sws_flags==SWS_FAST_BILINEAR)

{

	if(firstTime) //FIXME only if verbose ?

		fprintf(stderr, "SwScaler: output Width is not a multiple of 32 -> no MMX2 scaler\n");

}

#endif

if(firstTime)

{

#if defined (DITHER1XBPP) && defined (HAVE_MMX)

	char *dither= " dithered";

#else

	char *dither= "";

#endif

	if(sws_flags==SWS_FAST_BILINEAR)

		fprintf(stderr, "SwScaler: FAST_BILINEAR scaler ");

	else if(sws_flags==SWS_BILINEAR)

		fprintf(stderr, "SwScaler: BILINEAR scaler ");

	else if(sws_flags==SWS_BICUBIC)

		fprintf(stderr, "SwScaler: BICUBIC scaler ");

	else

		fprintf(stderr, "SwScaler: ehh flags invalid?! ");

	if(dstbpp==15)

		fprintf(stderr, "with%s BGR15 output ", dither);

	else if(dstbpp==16)

		fprintf(stderr, "with%s BGR16 output ", dither);

	else if(dstbpp==24)

		fprintf(stderr, "with BGR24 output ");

	else if(dstbpp==32)

		fprintf(stderr, "with BGR32 output ");

	else if(dstbpp==12)

		fprintf(stderr, "with YV12 output ");

	else

		fprintf(stderr, "without output ");

#ifdef HAVE_MMX2

		fprintf(stderr, "using MMX2\n");

#elif defined (HAVE_3DNOW)

		fprintf(stderr, "using 3DNOW\n");

#elif defined (HAVE_MMX)

		fprintf(stderr, "using MMX\n");

#elif defined (ARCH_X86)

		fprintf(stderr, "using X86 ASM2\n");

#else

		fprintf(stderr, "using C\n");

#endif

}

// match pixel 0 of the src to pixel 0 of dst and match pixel n-2 of src to pixel n-2 of dst

// n-2 is the last chrominance sample available

// this is not perfect, but noone shuld notice the difference, the more correct variant

// would be like the vertical one, but that would require some special code for the

// first and last pixel

if(sws_flags==SWS_FAST_BILINEAR)

{

	if(canMMX2BeUsed) 	lumXInc+= 20;

	else			lumXInc = ((srcW-2)<<16)/(dstW-2) - 20;

}

if(fullUVIpol && !(dstbpp==12)) 	chrXInc= lumXInc>>1, chrDstW= dstW;

else					chrXInc= lumXInc,    chrDstW= dstW>>1;

if(dstbpp==12)	chrYInc= lumYInc,    chrDstH= dstH>>1;

else		chrYInc= lumYInc>>1, chrDstH= dstH;

  // force calculation of the horizontal interpolation of the first line

  if(srcSliceY ==0){

//	printf("dstW %d, srcw %d, mmx2 %d\n", dstW, srcW, canMMX2BeUsed);

	lumBufIndex=0;

	chrBufIndex=0;

	dstY=0;

	//precalculate horizontal scaler filter coefficients

	if(oldDstW!=dstW || oldSrcW!=srcW || oldFlags!=sws_flags)

	{

#ifdef HAVE_MMX

		const int filterAlign=4;

#else

		const int filterAlign=1;

#endif

		oldDstW= dstW; oldSrcW= srcW; oldFlags= sws_flags;

		if(sws_flags != SWS_FAST_BILINEAR)

		{

			RENAME(initFilter)(hLumFilter, hLumFilterPos, &hLumFilterSize, lumXInc,

					   srcW   , dstW   , filterAlign, 1<<14);

			RENAME(initFilter)(hChrFilter, hChrFilterPos, &hChrFilterSize, chrXInc,

					   srcW>>1, chrDstW, filterAlign, 1<<14);

		}

#ifdef HAVE_MMX2

// cant downscale !!!

		if(canMMX2BeUsed && sws_flags == SWS_FAST_BILINEAR)

		{

			initMMX2HScaler(dstW   , lumXInc, funnyYCode);

			initMMX2HScaler(chrDstW, chrXInc, funnyUVCode);

		}

#endif

	} // Init Horizontal stuff

	if(oldDstH!=dstH || oldSrcH!=srcH || oldFlags!=sws_flags)

	{

		int i;

		oldDstH= dstH; oldSrcH= srcH; oldFlags= sws_flags; //FIXME swsflags conflict with x check

		// deallocate pixbufs

		for(i=0; i<vLumBufSize; i++) free(lumPixBuf[i]);

		for(i=0; i<vChrBufSize; i++) free(chrPixBuf[i]);

		RENAME(initFilter)(vLumFilter, vLumFilterPos, &vLumFilterSize, lumYInc,

				srcH   , dstH,    1, (1<<12)-4);

		RENAME(initFilter)(vChrFilter, vChrFilterPos, &vChrFilterSize, chrYInc,

				srcH>>1, chrDstH, 1, (1<<12)-4);

		// Calculate Buffer Sizes so that they wont run out while handling these damn slices

		vLumBufSize= vLumFilterSize; vChrBufSize= vChrFilterSize;

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

		{

			int chrI= i*chrDstH / dstH;

			int nextSlice= MAX(vLumFilterPos[i   ] + vLumFilterSize - 1,

					 ((vChrFilterPos[chrI] + vChrFilterSize - 1)<<1));

			nextSlice&= ~1; // Slices start at even boundaries

			if(vLumFilterPos[i   ] + vLumBufSize < nextSlice)

				vLumBufSize= nextSlice - vLumFilterPos[i   ];

			if(vChrFilterPos[chrI] + vChrBufSize < (nextSlice>>1))

				vChrBufSize= (nextSlice>>1) - vChrFilterPos[chrI];

		}

		// allocate pixbufs (we use dynamic allocation because otherwise we would need to

		// allocate several megabytes to handle all possible cases)

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

			lumPixBuf[i]= lumPixBuf[i+vLumBufSize]= (uint16_t*)memalign(8, 4000);

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

			chrPixBuf[i]= chrPixBuf[i+vChrBufSize]= (uint16_t*)memalign(8, 8000);

		//try to avoid drawing green stuff between the right end and the stride end

		for(i=0; i<vLumBufSize; i++) memset(lumPixBuf[i], 0, 4000);

		for(i=0; i<vChrBufSize; i++) memset(chrPixBuf[i], 64, 8000);

#ifdef HAVE_MMX

		// pack filter data for mmx code

		for(i=0; i<vLumFilterSize*dstH; i++)

			lumMmxFilter[4*i]=lumMmxFilter[4*i+1]=lumMmxFilter[4*i+2]=lumMmxFilter[4*i+3]=

				vLumFilter[i];

		for(i=0; i<vChrFilterSize*chrDstH; i++)

			chrMmxFilter[4*i]=chrMmxFilter[4*i+1]=chrMmxFilter[4*i+2]=chrMmxFilter[4*i+3]=

				vChrFilter[i];

#endif

	}

	lastInLumBuf= -1;

	lastInChrBuf= -1;

  } // if(firstLine)

	for(;dstY < dstH; dstY++){

		unsigned char *dest =dstptr[0]+dststride*dstY;

		unsigned char *uDest=dstptr[1]+(dststride>>1)*(dstY>>1);

		unsigned char *vDest=dstptr[2]+(dststride>>1)*(dstY>>1);

		const int chrDstY= dstbpp==12 ? (dstY>>1) : dstY;

		const int firstLumSrcY= vLumFilterPos[dstY]; //First line needed as input

		const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input

		const int lastLumSrcY= firstLumSrcY + vLumFilterSize -1; // Last line needed as input

		const int lastChrSrcY= firstChrSrcY + vChrFilterSize -1; // Last line needed as input

		if(sws_flags == SWS_FAST_BILINEAR)

		{

			//handle holes

			if(firstLumSrcY > lastInLumBuf) lastInLumBuf= firstLumSrcY-1;

			if(firstChrSrcY > lastInChrBuf) lastInChrBuf= firstChrSrcY-1;

		}

		ASSERT(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1)

		ASSERT(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1)

		// Do we have enough lines in this slice to output the dstY line

		if(lastLumSrcY < srcSliceY + srcSliceH && lastChrSrcY < ((srcSliceY + srcSliceH)>>1))

		{

			//Do horizontal scaling

			while(lastInLumBuf < lastLumSrcY)

			{

				uint8_t *src= srcptr[0]+(lastInLumBuf + 1 - srcSliceY)*stride[0];

				lumBufIndex++;

				ASSERT(lumBufIndex < 2*vLumBufSize)

				ASSERT(lastInLumBuf + 1 - srcSliceY < srcSliceH)

				ASSERT(lastInLumBuf + 1 - srcSliceY >= 0)

//				printf("%d %d\n", lumBufIndex, vLumBufSize);

				RENAME(hyscale)(lumPixBuf[ lumBufIndex ], dstW, src, srcW, lumXInc);

				lastInLumBuf++;

			}

			while(lastInChrBuf < lastChrSrcY)

			{

				uint8_t *src1= srcptr[1]+(lastInChrBuf + 1 - (srcSliceY>>1))*stride[1];

				uint8_t *src2= srcptr[2]+(lastInChrBuf + 1 - (srcSliceY>>1))*stride[2];

				chrBufIndex++;

				ASSERT(chrBufIndex < 2*vChrBufSize)

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) < (srcSliceH>>1))

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) >= 0)

				RENAME(hcscale)(chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, srcW>>1, chrXInc);

				lastInChrBuf++;

			}

			//wrap buf index around to stay inside the ring buffer

			if(lumBufIndex >= vLumBufSize ) lumBufIndex-= vLumBufSize;

			if(chrBufIndex >= vChrBufSize ) chrBufIndex-= vChrBufSize;

		}

		else // not enough lines left in this slice -> load the rest in the buffer

		{

/*		printf("%d %d Last:%d %d LastInBuf:%d %d Index:%d %d Y:%d FSize: %d %d BSize: %d %d\n",

			firstChrSrcY,firstLumSrcY,lastChrSrcY,lastLumSrcY,

			lastInChrBuf,lastInLumBuf,chrBufIndex,lumBufIndex,dstY,vChrFilterSize,vLumFilterSize,

			vChrBufSize, vLumBufSize);

*/

			//Do horizontal scaling

			while(lastInLumBuf+1 < srcSliceY + srcSliceH)

			{

				uint8_t *src= srcptr[0]+(lastInLumBuf + 1 - srcSliceY)*stride[0];

				lumBufIndex++;

				ASSERT(lumBufIndex < 2*vLumBufSize)

				ASSERT(lastInLumBuf + 1 - srcSliceY < srcSliceH)

				ASSERT(lastInLumBuf + 1 - srcSliceY >= 0)

				RENAME(hyscale)(lumPixBuf[ lumBufIndex ], dstW, src, srcW, lumXInc);

				lastInLumBuf++;

			}

			while(lastInChrBuf+1 < ((srcSliceY + srcSliceH)>>1))

			{

				uint8_t *src1= srcptr[1]+(lastInChrBuf + 1 - (srcSliceY>>1))*stride[1];

				uint8_t *src2= srcptr[2]+(lastInChrBuf + 1 - (srcSliceY>>1))*stride[2];

				chrBufIndex++;

				ASSERT(chrBufIndex < 2*vChrBufSize)

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) < (srcSliceH>>1))

				ASSERT(lastInChrBuf + 1 - (srcSliceY>>1) >= 0)

				RENAME(hcscale)(chrPixBuf[ chrBufIndex ], chrDstW, src1, src2, srcW>>1, chrXInc);

				lastInChrBuf++;

			}

			//wrap buf index around to stay inside the ring buffer

			if(lumBufIndex >= vLumBufSize ) lumBufIndex-= vLumBufSize;

			if(chrBufIndex >= vChrBufSize ) chrBufIndex-= vChrBufSize;

			break; //we cant output a dstY line so lets try with the next slice

		}

#ifdef HAVE_MMX

		b5Dither= dither8[dstY&1];

		g6Dither= dither4[dstY&1];

		g5Dither= dither8[dstY&1];

		r5Dither= dither8[(dstY+1)&1];

#endif

		if(dstbpp==12) //YV12

		{

			if(dstY&1) uDest=vDest= NULL; //FIXME split functions in lumi / chromi

			if(vLumFilterSize == 1 && vChrFilterSize == 1) // Unscaled YV12

			{

				int16_t *lumBuf = lumPixBuf[0];

				int16_t *chrBuf= chrPixBuf[0];

				RENAME(yuv2yuv1)(lumBuf, chrBuf, dest, uDest, vDest, dstW);

			}

			else //General YV12

			{

				int16_t **lumSrcPtr= lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

				int16_t **chrSrcPtr= chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

				RENAME(yuv2yuvX)(

					vLumFilter+dstY*vLumFilterSize     , lumSrcPtr, vLumFilterSize,

					vChrFilter+(dstY>>1)*vChrFilterSize, chrSrcPtr, vChrFilterSize,

					dest, uDest, vDest, dstW,

					lumMmxFilter+dstY*vLumFilterSize*4, chrMmxFilter+(dstY>>1)*vChrFilterSize*4);

			}

		}

		else

		{

			int16_t **lumSrcPtr= lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

			int16_t **chrSrcPtr= chrPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

			ASSERT(lumSrcPtr + vLumFilterSize - 1 < lumPixBuf + vLumBufSize*2);

			ASSERT(chrSrcPtr + vChrFilterSize - 1 < chrPixBuf + vChrBufSize*2);

			if(vLumFilterSize == 1 && vChrFilterSize == 2) //Unscaled RGB

			{

				int chrAlpha= vChrFilter[2*dstY+1];

				RENAME(yuv2rgb1)(*lumSrcPtr, *chrSrcPtr, *(chrSrcPtr+1),

						 dest, dstW, chrAlpha, dstbpp);

			}

			else if(vLumFilterSize == 2 && vChrFilterSize == 2) //BiLinear Upscale RGB

			{

				int lumAlpha= vLumFilter[2*dstY+1];

				int chrAlpha= vChrFilter[2*dstY+1];

				RENAME(yuv2rgb2)(*lumSrcPtr, *(lumSrcPtr+1), *chrSrcPtr, *(chrSrcPtr+1),

						 dest, dstW, lumAlpha, chrAlpha, dstbpp);

			}

			else //General RGB

			{

				RENAME(yuv2rgbX)(

					vLumFilter+dstY*vLumFilterSize, lumSrcPtr, vLumFilterSize,

					vChrFilter+dstY*vChrFilterSize, chrSrcPtr, vChrFilterSize,

					dest, dstW, dstbpp,

					lumMmxFilter+dstY*vLumFilterSize*4, chrMmxFilter+dstY*vChrFilterSize*4);

			}

		}

	}

#ifdef HAVE_MMX

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	firstTime=0;

}


void ff_mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)

{

    AVFrameSideData *side_data;

    mpeg1_encode_sequence_header(s);

    /* mpeg1 picture header */

    put_header(s, PICTURE_START_CODE);

    /* temporal reference */

    // RAL: s->picture_number instead of s->fake_picture_number

    put_bits(&s->pb, 10,

             (s->picture_number - s->gop_picture_number) & 0x3ff);

    put_bits(&s->pb, 3, s->pict_type);

    s->vbv_delay_ptr = s->pb.buf + put_bits_count(&s->pb) / 8;

    put_bits(&s->pb, 16, 0xFFFF);               /* vbv_delay */

    // RAL: Forward f_code also needed for B-frames

    if (s->pict_type == AV_PICTURE_TYPE_P ||

        s->pict_type == AV_PICTURE_TYPE_B) {

        put_bits(&s->pb, 1, 0);                 /* half pel coordinates */

        if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)

            put_bits(&s->pb, 3, s->f_code);     /* forward_f_code */

        else

            put_bits(&s->pb, 3, 7);             /* forward_f_code */

    }

    // RAL: Backward f_code necessary for B-frames

    if (s->pict_type == AV_PICTURE_TYPE_B) {

        put_bits(&s->pb, 1, 0);                 /* half pel coordinates */

        if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)

            put_bits(&s->pb, 3, s->b_code);     /* backward_f_code */

        else

            put_bits(&s->pb, 3, 7);             /* backward_f_code */

    }

    put_bits(&s->pb, 1, 0);                     /* extra bit picture */

    s->frame_pred_frame_dct = 1;

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

        put_header(s, EXT_START_CODE);

        put_bits(&s->pb, 4, 8);                 /* pic ext */

        if (s->pict_type == AV_PICTURE_TYPE_P ||

            s->pict_type == AV_PICTURE_TYPE_B) {

            put_bits(&s->pb, 4, s->f_code);

            put_bits(&s->pb, 4, s->f_code);

        } else {

            put_bits(&s->pb, 8, 255);

        }

        if (s->pict_type == AV_PICTURE_TYPE_B) {

            put_bits(&s->pb, 4, s->b_code);

            put_bits(&s->pb, 4, s->b_code);

        } else {

            put_bits(&s->pb, 8, 255);

        }

        put_bits(&s->pb, 2, s->intra_dc_precision);

        assert(s->picture_structure == PICT_FRAME);

        put_bits(&s->pb, 2, s->picture_structure);

        if (s->progressive_sequence)

            put_bits(&s->pb, 1, 0);             /* no repeat */

        else

            put_bits(&s->pb, 1, s->current_picture_ptr->f.top_field_first);

        /* XXX: optimize the generation of this flag with entropy measures */

        s->frame_pred_frame_dct = s->progressive_sequence;

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

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

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

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

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

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

        s->progressive_frame = s->progressive_sequence;

        /* chroma_420_type */

        put_bits(&s->pb, 1, s->chroma_format ==

                            CHROMA_420 ? s->progressive_frame : 0);

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

        put_bits(&s->pb, 1, 0);                 /* composite_display_flag */

    }

    if (s->scan_offset) {

        int i;

        put_header(s, USER_START_CODE);

        for (i = 0; i < sizeof(svcd_scan_offset_placeholder); i++)

            put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);

    }

    side_data = av_frame_get_side_data(&s->current_picture_ptr->f,

                                       AV_FRAME_DATA_STEREO3D);

    if (side_data) {

        AVStereo3D *stereo = (AVStereo3D *)side_data->data;

        uint8_t fpa_type;

        switch (stereo->type) {

        case AV_STEREO3D_SIDEBYSIDE:

            fpa_type = 0x03;

            break;

        case AV_STEREO3D_TOPBOTTOM:

            fpa_type = 0x04;

            break;

        case AV_STEREO3D_2D:

            fpa_type = 0x08;

            break;

        case AV_STEREO3D_SIDEBYSIDE_QUINCUNX:

            fpa_type = 0x23;

            break;

        default:

            fpa_type = 0;

            break;

        }

        if (fpa_type != 0) {

            put_header(s, USER_START_CODE);

            put_bits(&s->pb, 8, 'J');   // S3D_video_format_signaling_identifier

            put_bits(&s->pb, 8, 'P');

            put_bits(&s->pb, 8, '3');

            put_bits(&s->pb, 8, 'D');

            put_bits(&s->pb, 8, 0x03);  // S3D_video_format_length

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

            put_bits(&s->pb, 7, fpa_type); // S3D_video_format_type

            put_bits(&s->pb, 8, 0x04);  // reserved_data[0]

            put_bits(&s->pb, 8, 0xFF);  // reserved_data[1]

        }

    }

    s->mb_y = 0;

    ff_mpeg1_encode_slice_header(s);

}


static void qmp_input_type_any(Visitor *v, const char *name, QObject **obj,

                               Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, true, errp);

    *obj = NULL;

    if (!qobj) {

        return;

    }

    qobject_incref(qobj);

    *obj = qobj;

}


void *g_try_malloc(size_t n_bytes)

{

    __coverity_negative_sink__(n_bytes);

    return malloc(n_bytes == 0 ? 1 : n_bytes);

}


static void FUNCC(pred8x8l_vertical_add)(uint8_t *_pix, const int16_t *_block,

                                         ptrdiff_t stride)

{

    int i;

    pixel *pix = (pixel*)_pix;

    const dctcoef *block = (const dctcoef*)_block;

    stride >>= sizeof(pixel)-1;

    pix -= stride;

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

        pixel v = pix[0];

        pix[1*stride]= v += block[0];

        pix[2*stride]= v += block[8];

        pix[3*stride]= v += block[16];

        pix[4*stride]= v += block[24];

        pix[5*stride]= v += block[32];

        pix[6*stride]= v += block[40];

        pix[7*stride]= v += block[48];

        pix[8*stride]= v +  block[56];

        pix++;

        block++;

    }

}


int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, unsigned num)

{

    uint32_t exit_at_level[33] = { 404 };

    unsigned i, j, p, code;

    for (p = 0; (bits[p] == 0) && (p < num); ++p)

        ;

    if (p == num)

        return 0;

    codes[p] = 0;

    if (bits[p] > 32)

        return AVERROR_INVALIDDATA;

    for (i = 0; i < bits[p]; ++i)

        exit_at_level[i+1] = 1 << i;

    ++p;

    for (i = p; (bits[i] == 0) && (i < num); ++i)

        ;

    if (i == num)

        return 0;

    for (; p < num; ++p) {

        if (bits[p] > 32)

             return AVERROR_INVALIDDATA;

        if (bits[p] == 0)

             continue;

        // find corresponding exit(node which the tree can grow further from)

        for (i = bits[p]; i > 0; --i)

            if (exit_at_level[i])

                break;

        if (!i) // overspecified tree

             return AVERROR_INVALIDDATA;

        code = exit_at_level[i];

        exit_at_level[i] = 0;

        // construct code (append 0s to end) and introduce new exits

        for (j = i + 1 ;j <= bits[p]; ++j)

            exit_at_level[j] = code + (1 << (j - 1));

        codes[p] = code;

    }

    //no exits should be left (underspecified tree - ie. unused valid vlcs - not allowed by SPEC)

    for (p = 1; p < 33; p++)

        if (exit_at_level[p])

            return AVERROR_INVALIDDATA;

    return 0;

}


static int tftp_session_allocate(Slirp *slirp, struct sockaddr_storage *srcsas,

                                 struct tftp_t *tp)

{

  struct tftp_session *spt;

  int k;

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

    spt = &slirp->tftp_sessions[k];

    if (!tftp_session_in_use(spt))

        goto found;

    /* sessions time out after 5 inactive seconds */

    if ((int)(curtime - spt->timestamp) > 5000) {

        tftp_session_terminate(spt);

        goto found;

    }

  }

  return -1;

 found:

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

  spt->client_addr = *srcsas;

  spt->fd = -1;

  spt->block_size = 512;

  spt->client_port = tp->udp.uh_sport;

  spt->slirp = slirp;

  tftp_session_update(spt);

  return k;

}


static int tcp_get_msgfd(CharDriverState *chr)

{

    TCPCharDriver *s = chr->opaque;

    return s->msgfd;

}


static void decode_cdlms(WmallDecodeCtx *s)

{

    int c, i;

    int cdlms_send_coef = get_bits1(&s->gb);

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

	s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;

	for(i = 0; i < s->cdlms_ttl[c]; i++) {

	    s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;

	}

	for(i = 0; i < s->cdlms_ttl[c]; i++) {

	    s->cdlms[c][i].scaling = get_bits(&s->gb, 4);

	}

	if(cdlms_send_coef) {

	    for(i = 0; i < s->cdlms_ttl[c]; i++) {

		int cbits, shift_l, shift_r, j;

		cbits = av_log2(s->cdlms[c][i].order);

		if(1 << cbits < s->cdlms[c][i].order)

		    cbits++;

		s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;

		cbits = av_log2(s->cdlms[c][i].scaling + 1);

		if(1 << cbits < s->cdlms[c][i].scaling + 1)

		    cbits++;

		s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;

		shift_l = 32 - s->cdlms[c][i].bitsend;

		shift_r = 32 - 2 - s->cdlms[c][i].scaling;

		for(j = 0; j < s->cdlms[c][i].coefsend; j++) {

		    s->cdlms[c][i].coefs[j] =

			(get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;

		}

	    }

	}

    }

}


static void lan9118_eeprom_cmd(lan9118_state *s, int cmd, int addr)

{

    s->e2p_cmd = (s->e2p_cmd & 0x10) | (cmd << 28) | addr;

    switch (cmd) {

    case 0:

        s->e2p_data = s->eeprom[addr];

        DPRINTF("EEPROM Read %d = 0x%02x\n", addr, s->e2p_data);

    case 1:

        s->eeprom_writable = 0;

        DPRINTF("EEPROM Write Disable\n");

    case 2: /* EWEN */

        s->eeprom_writable = 1;

        DPRINTF("EEPROM Write Enable\n");

    case 3: /* WRITE */

        if (s->eeprom_writable) {

            s->eeprom[addr] &= s->e2p_data;

            DPRINTF("EEPROM Write %d = 0x%02x\n", addr, s->e2p_data);

        } else {

            DPRINTF("EEPROM Write %d (ignored)\n", addr);

        }

    case 4: /* WRAL */

        if (s->eeprom_writable) {

            for (addr = 0; addr < 128; addr++) {

                s->eeprom[addr] &= s->e2p_data;

            }

            DPRINTF("EEPROM Write All 0x%02x\n", s->e2p_data);

        } else {

            DPRINTF("EEPROM Write All (ignored)\n");

        }

    case 5: /* ERASE */

        if (s->eeprom_writable) {

            s->eeprom[addr] = 0xff;

            DPRINTF("EEPROM Erase %d\n", addr);

        } else {

            DPRINTF("EEPROM Erase %d (ignored)\n", addr);

        }

    case 6: /* ERAL */

        if (s->eeprom_writable) {

            memset(s->eeprom, 0xff, 128);

            DPRINTF("EEPROM Erase All\n");

        } else {

            DPRINTF("EEPROM Erase All (ignored)\n");

        }

    case 7: /* RELOAD */

        lan9118_reload_eeprom(s);

    }

}


static void sigp_store_status_at_address(CPUState *cs, run_on_cpu_data arg)

{

    S390CPU *cpu = S390_CPU(cs);

    SigpInfo *si = arg.host_ptr;

    uint32_t address = si->param & 0x7ffffe00u;

    /* cpu has to be stopped */

    if (s390_cpu_get_state(cpu) != CPU_STATE_STOPPED) {

        set_sigp_status(si, SIGP_STAT_INCORRECT_STATE);

        return;

    }

    cpu_synchronize_state(cs);

    if (s390_store_status(cpu, address, false)) {

        set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);

        return;

    }

    si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;

}


static void ppc_prep_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    const char *boot_device = machine->boot_order;

    MemoryRegion *sysmem = get_system_memory();

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    Nvram *m48t59;

#if 0

    MemoryRegion *xcsr = g_new(MemoryRegion, 1);

#endif

    int linux_boot, i, nb_nics1;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    uint32_t kernel_base, initrd_base;

    long kernel_size, initrd_size;

    DeviceState *dev;

    PCIHostState *pcihost;

    PCIBus *pci_bus;

    PCIDevice *pci;

    ISABus *isa_bus;

    ISADevice *isa;

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    sysctrl = g_malloc0(sizeof(sysctrl_t));

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (machine->cpu_model == NULL)

        machine->cpu_model = "602";

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

        cpu = cpu_ppc_init(machine->cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        if (env->flags & POWERPC_FLAG_RTC_CLK) {

            /* POWER / PowerPC 601 RTC clock frequency is 7.8125 MHz */

            cpu_ppc_tb_init(env, 7812500UL);

        } else {

            /* Set time-base frequency to 100 Mhz */

            cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

        }

        qemu_register_reset(ppc_prep_reset, cpu);

    }

    /* allocate RAM */

    memory_region_allocate_system_memory(ram, NULL, "ppc_prep.ram", ram_size);

    memory_region_add_subregion(sysmem, 0, ram);

    if (linux_boot) {

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                hw_error("qemu: could not load initial ram disk '%s'\n",

                          initrd_filename);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* For now, OHW cannot boot from the network. */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        hw_error("Only 6xx bus is supported on PREP machine\n");

    }

    dev = qdev_create(NULL, "raven-pcihost");

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    qdev_prop_set_string(dev, "bios-name", bios_name);

    qdev_prop_set_uint32(dev, "elf-machine", ELF_MACHINE);

    pcihost = PCI_HOST_BRIDGE(dev);

    object_property_add_child(qdev_get_machine(), "raven", OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");

    if (pci_bus == NULL) {

        fprintf(stderr, "Couldn't create PCI host controller.\n");

        exit(1);

    }

    sysctrl->contiguous_map_irq = qdev_get_gpio_in(dev, 0);

    /* PCI -> ISA bridge */

    pci = pci_create_simple(pci_bus, PCI_DEVFN(1, 0), "i82378");

    cpu = POWERPC_CPU(first_cpu);

    qdev_connect_gpio_out(&pci->qdev, 0,

                          cpu->env.irq_inputs[PPC6xx_INPUT_INT]);

    qdev_connect_gpio_out(&pci->qdev, 1,

                          qemu_allocate_irq(cpu_request_exit, NULL, 0));

    sysbus_connect_irq(&pcihost->busdev, 0, qdev_get_gpio_in(&pci->qdev, 9));

    sysbus_connect_irq(&pcihost->busdev, 1, qdev_get_gpio_in(&pci->qdev, 11));

    sysbus_connect_irq(&pcihost->busdev, 2, qdev_get_gpio_in(&pci->qdev, 9));

    sysbus_connect_irq(&pcihost->busdev, 3, qdev_get_gpio_in(&pci->qdev, 11));

    isa_bus = ISA_BUS(qdev_get_child_bus(DEVICE(pci), "isa.0"));

    /* Super I/O (parallel + serial ports) */

    isa = isa_create(isa_bus, TYPE_PC87312);

    dev = DEVICE(isa);

    qdev_prop_set_uint8(dev, "config", 13); /* fdc, ser0, ser1, par0 */

    qdev_init_nofail(dev);

    /* init basic PC hardware */

    pci_vga_init(pci_bus);

    nb_nics1 = nb_nics;

    if (nb_nics1 > NE2000_NB_MAX)

        nb_nics1 = NE2000_NB_MAX;

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

        if (nd_table[i].model == NULL) {

	    nd_table[i].model = g_strdup("ne2k_isa");

        }

        if (strcmp(nd_table[i].model, "ne2k_isa") == 0) {

            isa_ne2000_init(isa_bus, ne2000_io[i], ne2000_irq[i],

                            &nd_table[i]);

        } else {

            pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);

        }

    }

    ide_drive_get(hd, ARRAY_SIZE(hd));

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

        isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i],

                     hd[2 * i],

		     hd[2 * i + 1]);

    }

    isa_create_simple(isa_bus, "i8042");

    cpu = POWERPC_CPU(first_cpu);

    sysctrl->reset_irq = cpu->env.irq_inputs[PPC6xx_INPUT_HRESET];

    portio_list_init(&prep_port_list, NULL, prep_portio_list, sysctrl, "prep");

    portio_list_add(&prep_port_list, isa_address_space_io(isa), 0x0);

    /* PowerPC control and status register group */

#if 0

    memory_region_init_io(xcsr, NULL, &PPC_XCSR_ops, NULL, "ppc-xcsr", 0x1000);

    memory_region_add_subregion(sysmem, 0xFEFF0000, xcsr);

#endif

    if (usb_enabled()) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

    }

    m48t59 = m48t59_init_isa(isa_bus, 0x0074, NVRAM_SIZE, 2000, 59);

    if (m48t59 == NULL)

        return;

    sysctrl->nvram = m48t59;

    /* Initialise NVRAM */

    PPC_NVRAM_set_params(m48t59, NVRAM_SIZE, "PREP", ram_size,

                         ppc_boot_device,

                         kernel_base, kernel_size,

                         kernel_cmdline,

                         initrd_base, initrd_size,

                         /* XXX: need an option to load a NVRAM image */

                         0,

                         graphic_width, graphic_height, graphic_depth);

}


int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
                          BdrvCheckMode fix)
{
    BDRVQcowState *s = bs->opaque;
    BdrvCheckResult pre_compare_res;
    int64_t size, highest_cluster, nb_clusters;
    uint16_t *refcount_table = NULL;
    bool rebuild = false;
    int ret;
    size = bdrv_getlength(bs->file);
    if (size < 0) {
        res->check_errors++;
        return size;
    nb_clusters = size_to_clusters(s, size);
    if (nb_clusters > INT_MAX) {
        res->check_errors++;
        return -EFBIG;
    res->bfi.total_clusters =
        size_to_clusters(s, bs->total_sectors * BDRV_SECTOR_SIZE);
    ret = calculate_refcounts(bs, res, fix, &rebuild, &refcount_table,
    /* In case we don't need to rebuild the refcount structure (but want to fix
     * something), this function is immediately called again, in which case the
     * result should be ignored */
    pre_compare_res = *res;
    compare_refcounts(bs, res, 0, &rebuild, &highest_cluster, refcount_table,
                      nb_clusters);
    if (rebuild && (fix & BDRV_FIX_ERRORS)) {
        fprintf(stderr, "Rebuilding refcount structure\n");
        ret = rebuild_refcount_structure(bs, res, &refcount_table,
    } else if (fix) {
            fprintf(stderr, "ERROR need to rebuild refcount structures\n");
            res->check_errors++;
            ret = -EIO;
        if (res->leaks || res->corruptions) {
            *res = pre_compare_res;
            compare_refcounts(bs, res, fix, &rebuild, &highest_cluster,
                              refcount_table, nb_clusters);
    /* check OFLAG_COPIED */
    ret = check_oflag_copied(bs, res, fix);
    res->image_end_offset = (highest_cluster + 1) * s->cluster_size;
    ret = 0;
fail:
    g_free(refcount_table);
    return ret;


static void pmac_ide_atapi_transfer_cb(void *opaque, int ret)

{

    DBDMA_io *io = opaque;

    MACIOIDEState *m = io->opaque;

    IDEState *s = idebus_active_if(&m->bus);

    int64_t offset;

    MACIO_DPRINTF("pmac_ide_atapi_transfer_cb\n");

    if (ret < 0) {

        MACIO_DPRINTF("DMA error: %d\n", ret);

        ide_atapi_io_error(s, ret);

        goto done;

    }

    if (!m->dma_active) {

        MACIO_DPRINTF("waiting for data (%#x - %#x - %x)\n",

                      s->nsector, io->len, s->status);

        /* data not ready yet, wait for the channel to get restarted */

        io->processing = false;

        return;

    }

    if (s->io_buffer_size <= 0) {

        MACIO_DPRINTF("End of IDE transfer\n");

        ide_atapi_cmd_ok(s);

        m->dma_active = false;

        goto done;

    }

    if (io->len == 0) {

        MACIO_DPRINTF("End of DMA transfer\n");

        goto done;

    }

    if (s->lba == -1) {

        /* Non-block ATAPI transfer - just copy to RAM */

        s->io_buffer_size = MIN(s->io_buffer_size, io->len);

        cpu_physical_memory_write(io->addr, s->io_buffer, s->io_buffer_size);

        ide_atapi_cmd_ok(s);

        m->dma_active = false;

        goto done;

    }

    /* Calculate current offset */

    offset = (int64_t)(s->lba << 11) + s->io_buffer_index;

    pmac_dma_read(s->blk, offset, io->len, pmac_ide_atapi_transfer_cb, io);

    return;

done:

    if (ret < 0) {

        block_acct_failed(blk_get_stats(s->blk), &s->acct);

    } else {

        block_acct_done(blk_get_stats(s->blk), &s->acct);

    }

    io->dma_end(opaque);

}


static void qemu_chr_parse_spice_port(QemuOpts *opts, ChardevBackend *backend,

                                      Error **errp)

{

    const char *name = qemu_opt_get(opts, "name");

    ChardevSpicePort *spiceport;

    if (name == NULL) {

        error_setg(errp, "chardev: spice port: no name given");

        return;

    }

    spiceport = backend->u.spiceport = g_new0(ChardevSpicePort, 1);

    qemu_chr_parse_common(opts, qapi_ChardevSpicePort_base(spiceport));

    spiceport->fqdn = g_strdup(name);

}


void qemu_fd_register(int fd)

{

    WSAEventSelect(fd, qemu_event_handle, FD_READ | FD_ACCEPT | FD_CLOSE |

                   FD_CONNECT | FD_WRITE | FD_OOB);

}


static struct pxa2xx_i2s_s *pxa2xx_i2s_init(target_phys_addr_t base,

                qemu_irq irq, struct pxa2xx_dma_state_s *dma)

{

    int iomemtype;

    struct pxa2xx_i2s_s *s = (struct pxa2xx_i2s_s *)

            qemu_mallocz(sizeof(struct pxa2xx_i2s_s));

    s->base = base;

    s->irq = irq;

    s->dma = dma;

    s->data_req = pxa2xx_i2s_data_req;

    pxa2xx_i2s_reset(s);

    iomemtype = cpu_register_io_memory(0, pxa2xx_i2s_readfn,

                    pxa2xx_i2s_writefn, s);

    cpu_register_physical_memory(s->base & 0xfff00000, 0xfffff, iomemtype);

    register_savevm("pxa2xx_i2s", base, 0,

                    pxa2xx_i2s_save, pxa2xx_i2s_load, s);

    return s;

}


static void perf_nesting(void)

{

    unsigned int i, maxcycles, maxnesting;

    double duration;

    maxcycles = 10000;

    maxnesting = 1000;

    Coroutine *root;

    g_test_timer_start();

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

        NestData nd = {

            .n_enter  = 0,

            .n_return = 0,

            .max      = maxnesting,

        };

        root = qemu_coroutine_create(nest);

        qemu_coroutine_enter(root, &nd);

    }

    duration = g_test_timer_elapsed();

    g_test_message("Nesting %u iterations of %u depth each: %f s\n",

        maxcycles, maxnesting, duration);

}


void hpet_init(qemu_irq *irq) {

    int i, iomemtype;

    HPETState *s;

    DPRINTF ("hpet_init\n");

    s = qemu_mallocz(sizeof(HPETState));

    hpet_statep = s;

    s->irqs = irq;

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

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

        timer->qemu_timer = qemu_new_timer(vm_clock, hpet_timer, timer);

    }

    vmstate_register(-1, &vmstate_hpet, s);

    qemu_register_reset(hpet_reset, s);

    /* HPET Area */

    iomemtype = cpu_register_io_memory(hpet_ram_read,

                                       hpet_ram_write, s);

    cpu_register_physical_memory(HPET_BASE, 0x400, iomemtype);

}


void slavio_serial_ms_kbd_init(target_phys_addr_t base, qemu_irq irq,

                               int disabled, int clock, int it_shift)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "escc");

    qdev_prop_set_uint32(dev, "disabled", disabled);

    qdev_prop_set_uint32(dev, "frequency", clock);

    qdev_prop_set_uint32(dev, "it_shift", it_shift);

    qdev_prop_set_chr(dev, "chrB", NULL);

    qdev_prop_set_chr(dev, "chrA", NULL);

    qdev_prop_set_uint32(dev, "chnBtype", mouse);

    qdev_prop_set_uint32(dev, "chnAtype", kbd);

    qdev_init_nofail(dev);

    s = sysbus_from_qdev(dev);

    sysbus_connect_irq(s, 0, irq);

    sysbus_connect_irq(s, 1, irq);

    sysbus_mmio_map(s, 0, base);

}


static int list_pci(ClpReqRspListPci *rrb, uint8_t *cc)

{

    S390PCIBusDevice *pbdev;

    uint32_t res_code, initial_l2, g_l2, finish;

    int rc, idx;

    uint64_t resume_token;

    rc = 0;

    if (lduw_p(&rrb->request.hdr.len) != 32) {

        res_code = CLP_RC_LEN;

        rc = -EINVAL;

        goto out;

    }

    if ((ldl_p(&rrb->request.fmt) & CLP_MASK_FMT) != 0) {

        res_code = CLP_RC_FMT;

        rc = -EINVAL;

        goto out;

    }

    if ((ldl_p(&rrb->request.fmt) & ~CLP_MASK_FMT) != 0 ||

        ldq_p(&rrb->request.reserved1) != 0 ||

        ldq_p(&rrb->request.reserved2) != 0) {

        res_code = CLP_RC_RESNOT0;

        rc = -EINVAL;

        goto out;

    }

    resume_token = ldq_p(&rrb->request.resume_token);

    if (resume_token) {

        pbdev = s390_pci_find_dev_by_idx(resume_token);

        if (!pbdev) {

            res_code = CLP_RC_LISTPCI_BADRT;

            rc = -EINVAL;

            goto out;

        }

    }

    if (lduw_p(&rrb->response.hdr.len) < 48) {

        res_code = CLP_RC_8K;

        rc = -EINVAL;

        goto out;

    }

    initial_l2 = lduw_p(&rrb->response.hdr.len);

    if ((initial_l2 - LIST_PCI_HDR_LEN) % sizeof(ClpFhListEntry)

        != 0) {

        res_code = CLP_RC_LEN;

        rc = -EINVAL;

        *cc = 3;

        goto out;

    }

    stl_p(&rrb->response.fmt, 0);

    stq_p(&rrb->response.reserved1, 0);

    stq_p(&rrb->response.reserved2, 0);

    stl_p(&rrb->response.mdd, FH_MASK_SHM);

    stw_p(&rrb->response.max_fn, PCI_MAX_FUNCTIONS);

    rrb->response.entry_size = sizeof(ClpFhListEntry);

    finish = 0;

    idx = resume_token;

    g_l2 = LIST_PCI_HDR_LEN;

    do {

        pbdev = s390_pci_find_dev_by_idx(idx);

        if (!pbdev) {

            finish = 1;

            break;

        }

        stw_p(&rrb->response.fh_list[idx - resume_token].device_id,

            pci_get_word(pbdev->pdev->config + PCI_DEVICE_ID));

        stw_p(&rrb->response.fh_list[idx - resume_token].vendor_id,

            pci_get_word(pbdev->pdev->config + PCI_VENDOR_ID));

        /* Ignore RESERVED devices. */

        stl_p(&rrb->response.fh_list[idx - resume_token].config,

            pbdev->state == ZPCI_FS_STANDBY ? 0 : 1 << 31);

        stl_p(&rrb->response.fh_list[idx - resume_token].fid, pbdev->fid);

        stl_p(&rrb->response.fh_list[idx - resume_token].fh, pbdev->fh);

        g_l2 += sizeof(ClpFhListEntry);

        /* Add endian check for DPRINTF? */

        DPRINTF("g_l2 %d vendor id 0x%x device id 0x%x fid 0x%x fh 0x%x\n",

            g_l2,

            lduw_p(&rrb->response.fh_list[idx - resume_token].vendor_id),

            lduw_p(&rrb->response.fh_list[idx - resume_token].device_id),

            ldl_p(&rrb->response.fh_list[idx - resume_token].fid),

            ldl_p(&rrb->response.fh_list[idx - resume_token].fh));

        idx++;

    } while (g_l2 < initial_l2);

    if (finish == 1) {

        resume_token = 0;

    } else {

        resume_token = idx;

    }

    stq_p(&rrb->response.resume_token, resume_token);

    stw_p(&rrb->response.hdr.len, g_l2);

    stw_p(&rrb->response.hdr.rsp, CLP_RC_OK);

out:

    if (rc) {

        DPRINTF("list pci failed rc 0x%x\n", rc);

        stw_p(&rrb->response.hdr.rsp, res_code);

    }

    return rc;

}


abi_long do_sigaltstack(abi_ulong uss_addr, abi_ulong uoss_addr, abi_ulong sp)

{

    int ret;

    struct target_sigaltstack oss;

    /* XXX: test errors */

    if(uoss_addr)

    {

        __put_user(target_sigaltstack_used.ss_sp, &oss.ss_sp);

        __put_user(target_sigaltstack_used.ss_size, &oss.ss_size);

        __put_user(sas_ss_flags(sp), &oss.ss_flags);

    }

    if(uss_addr)

    {

        struct target_sigaltstack *uss;

        struct target_sigaltstack ss;

	ret = -TARGET_EFAULT;

        if (!lock_user_struct(VERIFY_READ, uss, uss_addr, 1)

	    || __get_user(ss.ss_sp, &uss->ss_sp)

	    || __get_user(ss.ss_size, &uss->ss_size)

	    || __get_user(ss.ss_flags, &uss->ss_flags))

            goto out;

        unlock_user_struct(uss, uss_addr, 0);

	ret = -TARGET_EPERM;

	if (on_sig_stack(sp))

            goto out;

	ret = -TARGET_EINVAL;

	if (ss.ss_flags != TARGET_SS_DISABLE

            && ss.ss_flags != TARGET_SS_ONSTACK

            && ss.ss_flags != 0)

            goto out;

	if (ss.ss_flags == TARGET_SS_DISABLE) {

            ss.ss_size = 0;

            ss.ss_sp = 0;

	} else {

            ret = -TARGET_ENOMEM;

            if (ss.ss_size < MINSIGSTKSZ)

                goto out;

	}

        target_sigaltstack_used.ss_sp = ss.ss_sp;

        target_sigaltstack_used.ss_size = ss.ss_size;

    }

    if (uoss_addr) {

        ret = -TARGET_EFAULT;

        if (copy_to_user(uoss_addr, &oss, sizeof(oss)))

            goto out;

    }

    ret = 0;

out:

    return ret;

}


void ff_mov_close_hinting(MOVTrack *track) {

    AVFormatContext* rtp_ctx = track->rtp_ctx;

    uint8_t *ptr;

    av_freep(&track->enc);

    sample_queue_free(&track->sample_queue);

    if (!rtp_ctx)

        return;

    if (rtp_ctx->pb) {

        av_write_trailer(rtp_ctx);

        url_close_dyn_buf(rtp_ctx->pb, &ptr);

        av_free(ptr);

    }

    av_metadata_free(&rtp_ctx->streams[0]->metadata);

    av_metadata_free(&rtp_ctx->metadata);

    av_free(rtp_ctx->streams[0]);

    av_freep(&rtp_ctx);

}


void laio_cleanup(void *s_)
{
    struct qemu_laio_state *s = s_;
    event_notifier_cleanup(&s->e);
    g_free(s);


static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)

{

    MXFStreamContext *sc = st->priv_data;

    AVIOContext *pb = s->pb;

    int stored_height = (st->codec->height+15)/16*16;

    int display_height;

    int f1, f2;

    unsigned desc_size = size+8+8+8+8+8+8+5+16+sc->interlaced*4+12+20;

    if (sc->interlaced && sc->field_dominance)

        desc_size += 5;

    mxf_write_generic_desc(s, st, key, desc_size);

    mxf_write_local_tag(pb, 4, 0x3203);

    avio_wb32(pb, st->codec->width);

    mxf_write_local_tag(pb, 4, 0x3202);

    avio_wb32(pb, stored_height>>sc->interlaced);

    mxf_write_local_tag(pb, 4, 0x3209);

    avio_wb32(pb, st->codec->width);

    if (st->codec->height == 608) // PAL + VBI

        display_height = 576;

    else if (st->codec->height == 512)  // NTSC + VBI

        display_height = 486;

    else

        display_height = st->codec->height;

    mxf_write_local_tag(pb, 4, 0x3208);

    avio_wb32(pb, display_height>>sc->interlaced);

    // component depth

    mxf_write_local_tag(pb, 4, 0x3301);

    avio_wb32(pb, sc->component_depth);

    // horizontal subsampling

    mxf_write_local_tag(pb, 4, 0x3302);

    avio_wb32(pb, 2);

    // frame layout

    mxf_write_local_tag(pb, 1, 0x320C);

    avio_w8(pb, sc->interlaced);

    // video line map

    switch (st->codec->height) {

    case  576: f1 = 23; f2 = st->codec->codec_id == AV_CODEC_ID_DVVIDEO ? 335 : 336; break;

    case  608: f1 =  7; f2 = 320; break;

    case  480: f1 = 20; f2 = st->codec->codec_id == AV_CODEC_ID_DVVIDEO ? 285 : 283; break;

    case  512: f1 =  7; f2 = 270; break;

    case  720: f1 = 26; f2 =   0; break; // progressive

    case 1080: f1 = 21; f2 = 584; break;

    default:   f1 =  0; f2 =   0; break;

    }

    if (!sc->interlaced) {

        f2  = 0;

        f1 *= 2;

    }

    mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);

    avio_wb32(pb, sc->interlaced ? 2 : 1);

    avio_wb32(pb, 4);

    avio_wb32(pb, f1);

    if (sc->interlaced)

        avio_wb32(pb, f2);

    mxf_write_local_tag(pb, 8, 0x320E);

    avio_wb32(pb, sc->aspect_ratio.num);

    avio_wb32(pb, sc->aspect_ratio.den);

    mxf_write_local_tag(pb, 16, 0x3201);

    avio_write(pb, *sc->codec_ul, 16);

    if (sc->interlaced && sc->field_dominance) {

        mxf_write_local_tag(pb, 1, 0x3212);

        avio_w8(pb, sc->field_dominance);

    }

}


static void pc_dimm_init(Object *obj)

{

    PCDIMMDevice *dimm = PC_DIMM(obj);

    object_property_add(obj, PC_DIMM_SIZE_PROP, "int", pc_dimm_get_size,

                        NULL, NULL, NULL, &error_abort);

    object_property_add_link(obj, PC_DIMM_MEMDEV_PROP, TYPE_MEMORY_BACKEND,

                             (Object **)&dimm->hostmem,

                             qdev_prop_allow_set_link_before_realize,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &error_abort);

}


static always_inline int find_pte (CPUState *env, mmu_ctx_t *ctx,

                                   int h, int rw)

{

#if defined(TARGET_PPC64)

    if (env->mmu_model == POWERPC_MMU_64B)

        return find_pte64(ctx, h, rw);

#endif

    return find_pte32(ctx, h, rw);

}


static void tcp_chr_accept(void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    struct sockaddr_in saddr;

#ifndef _WIN32

    struct sockaddr_un uaddr;

#endif

    struct sockaddr *addr;

    socklen_t len;

    int fd;

    for(;;) {

#ifndef _WIN32

	if (s->is_unix) {

	    len = sizeof(uaddr);

	    addr = (struct sockaddr *)&uaddr;

	} else

#endif

	{

	    len = sizeof(saddr);

	    addr = (struct sockaddr *)&saddr;

	}

        fd = accept(s->listen_fd, addr, &len);

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

            return;

        } else if (fd >= 0) {

            if (s->do_telnetopt)

                tcp_chr_telnet_init(fd);

            break;

        }

    }

    socket_set_nonblock(fd);

    if (s->do_nodelay)

        socket_set_nodelay(fd);

    s->fd = fd;

    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);

    tcp_chr_connect(chr);

}


static void test_visitor_out_native_list_int8(TestOutputVisitorData *data,

                                              const void *unused)

{

    test_native_list(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_S8);

}


static void tcg_reg_alloc_mov(TCGContext *s, const TCGOpDef *def,

                              const TCGArg *args, uint16_t dead_args,

                              uint8_t sync_args)

{

    TCGRegSet allocated_regs;

    TCGTemp *ts, *ots;

    TCGType otype, itype;

    tcg_regset_set(allocated_regs, s->reserved_regs);

    ots = &s->temps[args[0]];

    ts = &s->temps[args[1]];

    /* Note that otype != itype for no-op truncation.  */

    otype = ots->type;

    itype = ts->type;

    /* If the source value is not in a register, and we're going to be

       forced to have it in a register in order to perform the copy,

       then copy the SOURCE value into its own register first.  That way

       we don't have to reload SOURCE the next time it is used. */

    if (((NEED_SYNC_ARG(0) || ots->fixed_reg) && ts->val_type != TEMP_VAL_REG)

        || ts->val_type == TEMP_VAL_MEM) {

        temp_load(s, ts, tcg_target_available_regs[itype], allocated_regs);

    }

    if (IS_DEAD_ARG(0) && !ots->fixed_reg) {

        /* mov to a non-saved dead register makes no sense (even with

           liveness analysis disabled). */

        assert(NEED_SYNC_ARG(0));

        /* The code above should have moved the temp to a register. */

        assert(ts->val_type == TEMP_VAL_REG);

        if (!ots->mem_allocated) {

            temp_allocate_frame(s, args[0]);

        }

        if (ots->indirect_reg) {

            tcg_regset_set_reg(allocated_regs, ts->reg);

            temp_load(s, ots->mem_base,

                      tcg_target_available_regs[TCG_TYPE_PTR],

                      allocated_regs);

        }

        tcg_out_st(s, otype, ts->reg, ots->mem_base->reg, ots->mem_offset);

        if (IS_DEAD_ARG(1)) {

            temp_dead(s, ts);

        }

        temp_dead(s, ots);

    } else if (ts->val_type == TEMP_VAL_CONST) {

        /* propagate constant */

        if (ots->val_type == TEMP_VAL_REG) {

            s->reg_to_temp[ots->reg] = NULL;

        }

        ots->val_type = TEMP_VAL_CONST;

        ots->val = ts->val;

        if (IS_DEAD_ARG(1)) {

            temp_dead(s, ts);

        }

    } else {

        /* The code in the first if block should have moved the

           temp to a register. */

        assert(ts->val_type == TEMP_VAL_REG);

        if (IS_DEAD_ARG(1) && !ts->fixed_reg && !ots->fixed_reg) {

            /* the mov can be suppressed */

            if (ots->val_type == TEMP_VAL_REG) {

                s->reg_to_temp[ots->reg] = NULL;

            }

            ots->reg = ts->reg;

            temp_dead(s, ts);

        } else {

            if (ots->val_type != TEMP_VAL_REG) {

                /* When allocating a new register, make sure to not spill the

                   input one. */

                tcg_regset_set_reg(allocated_regs, ts->reg);

                ots->reg = tcg_reg_alloc(s, tcg_target_available_regs[otype],

                                         allocated_regs, ots->indirect_base);

            }

            tcg_out_mov(s, otype, ots->reg, ts->reg);

        }

        ots->val_type = TEMP_VAL_REG;

        ots->mem_coherent = 0;

        s->reg_to_temp[ots->reg] = ots;

        if (NEED_SYNC_ARG(0)) {

            tcg_reg_sync(s, ots->reg, allocated_regs);

        }

    }

}


static void start_children(FFStream *feed)
{
    if (no_launch)
        return;
    for (; feed; feed = feed->next) {
        if (feed->child_argv && !feed->pid) {
            feed->pid_start = time(0);
            feed->pid = fork();
            if (feed->pid < 0) {
                fprintf(stderr, "Unable to create children\n");
                exit(1);
            }
            if (!feed->pid) {
                /* In child */
                char pathname[1024];
                char *slash;
                int i;
                for (i = 3; i < 256; i++) {
                    close(i);
                }
                if (!ffserver_debug) {
                    i = open("/dev/null", O_RDWR);
                    if (i)
                        dup2(i, 0);
                    dup2(i, 1);
                    dup2(i, 2);
                    if (i)
                        close(i);
                }
                pstrcpy(pathname, sizeof(pathname), my_program_name);
                slash = strrchr(pathname, '/');
                if (!slash) {
                    slash = pathname;
                } else {
                    slash++;
                }
                strcpy(slash, "ffmpeg");
                /* This is needed to make relative pathnames work */
                chdir(my_program_dir);
                execvp(pathname, feed->child_argv);
                _exit(1);
            }
        }
    }
}


int ff_h264_check_intra_pred_mode(H264Context *h, int mode){

    MpegEncContext * const s = &h->s;

    static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};

    static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};

    if(mode > 6U) {

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

        return -1;

    }

    if(!(h->top_samples_available&0x8000)){

        mode= top[ mode ];

        if(mode<0){

            av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);

            return -1;

        }

    }

    if((h->left_samples_available&0x8080) != 0x8080){

        mode= left[ mode ];

        if(h->left_samples_available&0x8080){ //mad cow disease mode, aka MBAFF + constrained_intra_pred

            mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);

        }

        if(mode<0){

            av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);

            return -1;

        }

    }

    return mode;

}


void replay_finish_event(void)

{

    replay_has_unread_data = 0;

    replay_fetch_data_kind();

}


static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)

{

    BDRVQcow2State *s = bs->opaque;

    uint64_t cluster_offset;

    int index_in_cluster, ret;

    unsigned int bytes;

    int64_t status = 0;

    bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);

    qemu_co_mutex_lock(&s->lock);

    ret = qcow2_get_cluster_offset(bs, sector_num << 9, &bytes,

                                   &cluster_offset);

    qemu_co_mutex_unlock(&s->lock);

    if (ret < 0) {

        return ret;

    }

    *pnum = bytes >> BDRV_SECTOR_BITS;

    if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&

        !s->cipher) {

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);

        *file = bs->file->bs;

        status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;

    }

    if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {

        status |= BDRV_BLOCK_ZERO;

    } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {

        status |= BDRV_BLOCK_DATA;

    }

    return status;

}


static void vfio_iommu_map_notify(Notifier *n, void *data)

{

    VFIOGuestIOMMU *giommu = container_of(n, VFIOGuestIOMMU, n);

    VFIOContainer *container = giommu->container;

    IOMMUTLBEntry *iotlb = data;

    hwaddr iova = iotlb->iova + giommu->iommu_offset;

    MemoryRegion *mr;

    hwaddr xlat;

    hwaddr len = iotlb->addr_mask + 1;

    void *vaddr;

    int ret;

    trace_vfio_iommu_map_notify(iova, iova + iotlb->addr_mask);

    if (iotlb->target_as != &address_space_memory) {

        error_report("Wrong target AS \"%s\", only system memory is allowed",

                     iotlb->target_as->name ? iotlb->target_as->name : "none");

        return;

    }

    /*

     * The IOMMU TLB entry we have just covers translation through

     * this IOMMU to its immediate target.  We need to translate

     * it the rest of the way through to memory.

     */

    rcu_read_lock();

    mr = address_space_translate(&address_space_memory,

                                 iotlb->translated_addr,

                                 &xlat, &len, iotlb->perm & IOMMU_WO);

    if (!memory_region_is_ram(mr)) {

        error_report("iommu map to non memory area %"HWADDR_PRIx"",

                     xlat);

        goto out;

    }

    /*

     * Translation truncates length to the IOMMU page size,

     * check that it did not truncate too much.

     */

    if (len & iotlb->addr_mask) {

        error_report("iommu has granularity incompatible with target AS");

        goto out;

    }

    if ((iotlb->perm & IOMMU_RW) != IOMMU_NONE) {

        vaddr = memory_region_get_ram_ptr(mr) + xlat;

        ret = vfio_dma_map(container, iova,

                           iotlb->addr_mask + 1, vaddr,

                           !(iotlb->perm & IOMMU_WO) || mr->readonly);

        if (ret) {

            error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "

                         "0x%"HWADDR_PRIx", %p) = %d (%m)",

                         container, iova,

                         iotlb->addr_mask + 1, vaddr, ret);

        }

    } else {

        ret = vfio_dma_unmap(container, iova, iotlb->addr_mask + 1);

        if (ret) {

            error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "

                         "0x%"HWADDR_PRIx") = %d (%m)",

                         container, iova,

                         iotlb->addr_mask + 1, ret);

        }

    }

out:

    rcu_read_unlock();

}


static int local_truncate(FsContext *ctx, V9fsPath *fs_path, off_t size)

{

    char buffer[PATH_MAX];

    char *path = fs_path->data;

    return truncate(rpath(ctx, path, buffer), size);

}


static bool is_zero_sectors(BlockDriverState *bs, int64_t start,

                            uint32_t count)

{

    int nr;

    BlockDriverState *file;

    int64_t res;

    if (start + count > bs->total_sectors) {

        count = bs->total_sectors - start;

    }

    if (!count) {

        return true;

    }

    res = bdrv_get_block_status_above(bs, NULL, start, count,

                                      &nr, &file);

    return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == count;

}


static int mc_subpel(DiracContext *s, DiracBlock *block, const uint8_t *src[5],

                     int x, int y, int ref, int plane)

{

    Plane *p = &s->plane[plane];

    uint8_t **ref_hpel = s->ref_pics[ref]->hpel[plane];

    int motion_x = block->u.mv[ref][0];

    int motion_y = block->u.mv[ref][1];

    int mx, my, i, epel, nplanes = 0;

    if (plane) {

        motion_x >>= s->chroma_x_shift;

        motion_y >>= s->chroma_y_shift;

    }

    mx         = motion_x & ~(-1 << s->mv_precision);

    my         = motion_y & ~(-1 << s->mv_precision);

    motion_x >>= s->mv_precision;

    motion_y >>= s->mv_precision;

    /* normalize subpel coordinates to epel */

    /* TODO: template this function? */

    mx      <<= 3 - s->mv_precision;

    my      <<= 3 - s->mv_precision;

    x += motion_x;

    y += motion_y;

    epel = (mx|my)&1;

    /* hpel position */

    if (!((mx|my)&3)) {

        nplanes = 1;

        src[0] = ref_hpel[(my>>1)+(mx>>2)] + y*p->stride + x;

    } else {

        /* qpel or epel */

        nplanes = 4;

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

            src[i] = ref_hpel[i] + y*p->stride + x;

        /* if we're interpolating in the right/bottom halves, adjust the planes as needed

           we increment x/y because the edge changes for half of the pixels */

        if (mx > 4) {

            src[0] += 1;

            src[2] += 1;

            x++;

        }

        if (my > 4) {

            src[0] += p->stride;

            src[1] += p->stride;

            y++;

        }

        /* hpel planes are:

           [0]: F  [1]: H

           [2]: V  [3]: C */

        if (!epel) {

            /* check if we really only need 2 planes since either mx or my is

               a hpel position. (epel weights of 0 handle this there) */

            if (!(mx&3)) {

                /* mx == 0: average [0] and [2]

                   mx == 4: average [1] and [3] */

                src[!mx] = src[2 + !!mx];

                nplanes = 2;

            } else if (!(my&3)) {

                src[0] = src[(my>>1)  ];

                src[1] = src[(my>>1)+1];

                nplanes = 2;

            }

        } else {

            /* adjust the ordering if needed so the weights work */

            if (mx > 4) {

                FFSWAP(const uint8_t *, src[0], src[1]);

                FFSWAP(const uint8_t *, src[2], src[3]);

            }

            if (my > 4) {

                FFSWAP(const uint8_t *, src[0], src[2]);

                FFSWAP(const uint8_t *, src[1], src[3]);

            }

            src[4] = epel_weights[my&3][mx&3];

        }

    }

    /* fixme: v/h _edge_pos */

    if ((unsigned)x > p->width +EDGE_WIDTH/2 - p->xblen ||

        (unsigned)y > p->height+EDGE_WIDTH/2 - p->yblen) {

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

            ff_emulated_edge_mc(s->edge_emu_buffer[i], src[i], p->stride,

                                p->xblen, p->yblen, x, y,

                                p->width+EDGE_WIDTH/2, p->height+EDGE_WIDTH/2);

            src[i] = s->edge_emu_buffer[i];

        }

    }

    return (nplanes>>1) + epel;

}


static void iscsi_nop_timed_event(void *opaque)

{

    IscsiLun *iscsilun = opaque;

    if (iscsi_get_nops_in_flight(iscsilun->iscsi) > MAX_NOP_FAILURES) {

        error_report("iSCSI: NOP timeout. Reconnecting...");

        iscsi_reconnect(iscsilun->iscsi);

    }

    if (iscsi_nop_out_async(iscsilun->iscsi, NULL, NULL, 0, NULL) != 0) {

        error_report("iSCSI: failed to sent NOP-Out. Disabling NOP messages.");

        return;

    }

    timer_mod(iscsilun->nop_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + NOP_INTERVAL);

    iscsi_set_events(iscsilun);

}


void qemu_mutex_lock_iothread(void)

{

    if (kvm_enabled()) {

        qemu_mutex_lock(&qemu_fair_mutex);

        qemu_mutex_lock(&qemu_global_mutex);

        qemu_mutex_unlock(&qemu_fair_mutex);

    } else

        qemu_signal_lock(100);

}


static bool is_special_wait_psw(CPUState *cs)

{

    /* signal quiesce */

    return cs->kvm_run->psw_addr == 0xfffUL;

}


static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)

{

    int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;

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

        sl->luma_weight_flag[i]   = 0;

        sl->chroma_weight_flag[i] = 0;

    }

    if (field < 0) {

        if (h->picture_structure == PICT_FRAME) {

            cur_poc = h->cur_pic_ptr->poc;

        } else {

            cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];

        }

        if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&

            sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {

            sl->use_weight        = 0;

            sl->use_weight_chroma = 0;

            return;

        }

        ref_start  = 0;

        ref_count0 = sl->ref_count[0];

        ref_count1 = sl->ref_count[1];

    } else {

        cur_poc    = h->cur_pic_ptr->field_poc[field];

        ref_start  = 16;

        ref_count0 = 16 + 2 * sl->ref_count[0];

        ref_count1 = 16 + 2 * sl->ref_count[1];

    }

    sl->use_weight               = 2;

    sl->use_weight_chroma        = 2;

    sl->luma_log2_weight_denom   = 5;

    sl->chroma_log2_weight_denom = 5;

    for (ref0 = ref_start; ref0 < ref_count0; ref0++) {

        int poc0 = sl->ref_list[0][ref0].poc;

        for (ref1 = ref_start; ref1 < ref_count1; ref1++) {

            int w = 32;

            if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {

                int poc1 = sl->ref_list[1][ref1].poc;

                int td   = av_clip_int8(poc1 - poc0);

                if (td) {

                    int tb = av_clip_int8(cur_poc - poc0);

                    int tx = (16384 + (FFABS(td) >> 1)) / td;

                    int dist_scale_factor = (tb * tx + 32) >> 8;

                    if (dist_scale_factor >= -64 && dist_scale_factor <= 128)

                        w = 64 - dist_scale_factor;

                }

            }

            if (field < 0) {

                sl->implicit_weight[ref0][ref1][0] =

                sl->implicit_weight[ref0][ref1][1] = w;

            } else {

                sl->implicit_weight[ref0][ref1][field] = w;

            }

        }

    }

}


int inet_connect_opts(QemuOpts *opts)

{

    struct addrinfo ai,*res,*e;

    const char *addr;

    const char *port;

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int sock,rc;

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

    ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    addr = qemu_opt_get(opts, "host");

    port = qemu_opt_get(opts, "port");

    if (addr == NULL || port == NULL) {

        fprintf(stderr, "inet_connect: host and/or port not specified\n");

        return -1;

    }

    if (qemu_opt_get_bool(opts, "ipv4", 0))

        ai.ai_family = PF_INET;

    if (qemu_opt_get_bool(opts, "ipv6", 0))

        ai.ai_family = PF_INET6;

    /* lookup */

    if (0 != (rc = getaddrinfo(addr, port, &ai, &res))) {

        fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port,

                gai_strerror(rc));

	return -1;

    }

    if (sockets_debug)

        inet_print_addrinfo(__FUNCTION__, res);

    for (e = res; e != NULL; e = e->ai_next) {

        if (getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,

                            uaddr,INET6_ADDRSTRLEN,uport,32,

                            NI_NUMERICHOST | NI_NUMERICSERV) != 0) {

            fprintf(stderr,"%s: getnameinfo: oops\n", __FUNCTION__);

            continue;

        }

        sock = socket(e->ai_family, e->ai_socktype, e->ai_protocol);

        if (sock < 0) {

            fprintf(stderr,"%s: socket(%s): %s\n", __FUNCTION__,

            inet_strfamily(e->ai_family), strerror(errno));

            continue;

        }

        setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));

        /* connect to peer */

        if (connect(sock,e->ai_addr,e->ai_addrlen) < 0) {

            if (sockets_debug || NULL == e->ai_next)

                fprintf(stderr, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__,

                        inet_strfamily(e->ai_family),

                        e->ai_canonname, uaddr, uport, strerror(errno));

            closesocket(sock);

            continue;

        }

        if (sockets_debug)

            fprintf(stderr, "%s: connect(%s,%s,%s,%s): OK\n", __FUNCTION__,

                    inet_strfamily(e->ai_family),

                    e->ai_canonname, uaddr, uport);

        freeaddrinfo(res);

        return sock;

    }

    freeaddrinfo(res);

    return -1;

}


static void vhost_commit(MemoryListener *listener)

{

}


static struct dirent *local_readdir(FsContext *ctx, V9fsFidOpenState *fs)

{

    struct dirent *entry;

again:

    entry = readdir(fs->dir.stream);

    if (!entry) {

        return NULL;

    }

    if (ctx->export_flags & V9FS_SM_MAPPED) {

        entry->d_type = DT_UNKNOWN;

    } else if (ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        if (!strcmp(entry->d_name, VIRTFS_META_DIR)) {

            /* skp the meta data directory */

            goto again;

        }

        entry->d_type = DT_UNKNOWN;

    }

    return entry;

}


void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)

{

    int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;

    int max_xfer_len = 0;

    int64_t sector_num = 0;

    if (mrb->num_reqs == 1) {

        submit_requests(blk, mrb, 0, 1, -1);

        mrb->num_reqs = 0;

        return;

    }

    max_xfer_len = blk_get_max_transfer_length(mrb->reqs[0]->dev->blk);

    max_xfer_len = MIN_NON_ZERO(max_xfer_len, BDRV_REQUEST_MAX_SECTORS);

    qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),

          &multireq_compare);

    for (i = 0; i < mrb->num_reqs; i++) {

        VirtIOBlockReq *req = mrb->reqs[i];

        if (num_reqs > 0) {

            bool merge = true;

            /* merge would exceed maximum number of IOVs */

            if (niov + req->qiov.niov > IOV_MAX) {

                merge = false;

            }

            /* merge would exceed maximum transfer length of backend device */

            if (req->qiov.size / BDRV_SECTOR_SIZE + nb_sectors > max_xfer_len) {

                merge = false;

            }

            /* requests are not sequential */

            if (sector_num + nb_sectors != req->sector_num) {

                merge = false;

            }

            if (!merge) {

                submit_requests(blk, mrb, start, num_reqs, niov);

                num_reqs = 0;

            }

        }

        if (num_reqs == 0) {

            sector_num = req->sector_num;

            nb_sectors = niov = 0;

            start = i;

        }

        nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;

        niov += req->qiov.niov;

        num_reqs++;

    }

    submit_requests(blk, mrb, start, num_reqs, niov);

    mrb->num_reqs = 0;

}


static int xen_pt_bar_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                               uint32_t *value, uint32_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint32_t valid_emu_mask = 0;

    uint32_t bar_emu_mask = 0;

    int index;

    /* get BAR index */

    index = xen_pt_bar_offset_to_index(reg->offset);

    if (index < 0 || index >= PCI_NUM_REGIONS) {

        XEN_PT_ERR(&s->dev, "Internal error: Invalid BAR index [%d].\n", index);

        return -1;

    }

    /* use fixed-up value from kernel sysfs */

    *value = base_address_with_flags(&s->real_device.io_regions[index]);

    /* set emulate mask depend on BAR flag */

    switch (s->bases[index].bar_flag) {

    case XEN_PT_BAR_FLAG_MEM:

        bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;

        break;

    case XEN_PT_BAR_FLAG_IO:

        bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;

        break;

    case XEN_PT_BAR_FLAG_UPPER:

        bar_emu_mask = XEN_PT_BAR_ALLF;

        break;

    default:

        break;

    }

    /* emulate BAR */

    valid_emu_mask = bar_emu_mask & valid_mask;

    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);

    return 0;

}


static int encode_apng(AVCodecContext *avctx, AVPacket *pkt,
                       const AVFrame *pict, int *got_packet)
{
    PNGEncContext *s = avctx->priv_data;
    int ret;
    int enc_row_size;
    size_t max_packet_size;
    APNGFctlChunk fctl_chunk = {0};
    if (pict && avctx->codec_id == AV_CODEC_ID_APNG && s->color_type == PNG_COLOR_TYPE_PALETTE) {
        uint32_t checksum = ~av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), ~0U, pict->data[1], 256 * sizeof(uint32_t));
        if (avctx->frame_number == 0) {
            s->palette_checksum = checksum;
        } else if (checksum != s->palette_checksum) {
            av_log(avctx, AV_LOG_ERROR,
                   "Input contains more than one unique palette. APNG does not support multiple palettes.\n");
            return -1;
        }
    }
    enc_row_size    = deflateBound(&s->zstream, (avctx->width * s->bits_per_pixel + 7) >> 3);
    max_packet_size =
        AV_INPUT_BUFFER_MIN_SIZE + // headers
        avctx->height * (
            enc_row_size +
            (4 + 12) * (((int64_t)enc_row_size + IOBUF_SIZE - 1) / IOBUF_SIZE) // fdAT * ceil(enc_row_size / IOBUF_SIZE)
        );
    if (max_packet_size > INT_MAX)
        return AVERROR(ENOMEM);
    if (avctx->frame_number == 0) {
        s->bytestream = avctx->extradata = av_malloc(FF_MIN_BUFFER_SIZE);
        if (!avctx->extradata)
            return AVERROR(ENOMEM);
        ret = encode_headers(avctx, pict);
        if (ret < 0)
            return ret;
        avctx->extradata_size = s->bytestream - avctx->extradata;
        s->last_frame_packet = av_malloc(max_packet_size);
        if (!s->last_frame_packet)
            return AVERROR(ENOMEM);
    } else if (s->last_frame) {
        ret = ff_alloc_packet2(avctx, pkt, max_packet_size, 0);
        if (ret < 0)
            return ret;
        memcpy(pkt->data, s->last_frame_packet, s->last_frame_packet_size);
        pkt->size = s->last_frame_packet_size;
        pkt->pts = pkt->dts = s->last_frame->pts;
    }
    if (pict) {
        s->bytestream_start =
        s->bytestream       = s->last_frame_packet;
        s->bytestream_end   = s->bytestream + max_packet_size;
        // We're encoding the frame first, so we have to do a bit of shuffling around
        // to have the image data write to the correct place in the buffer
        fctl_chunk.sequence_number = s->sequence_number;
        ++s->sequence_number;
        s->bytestream += 26 + 12;
        ret = apng_encode_frame(avctx, pict, &fctl_chunk, &s->last_frame_fctl);
        if (ret < 0)
            return ret;
        fctl_chunk.delay_num = 0; // delay filled in during muxing
        fctl_chunk.delay_den = 0;
    } else {
        s->last_frame_fctl.dispose_op = APNG_DISPOSE_OP_NONE;
    }
    if (s->last_frame) {
        uint8_t* last_fctl_chunk_start = pkt->data;
        uint8_t buf[26];
        AV_WB32(buf + 0, s->last_frame_fctl.sequence_number);
        AV_WB32(buf + 4, s->last_frame_fctl.width);
        AV_WB32(buf + 8, s->last_frame_fctl.height);
        AV_WB32(buf + 12, s->last_frame_fctl.x_offset);
        AV_WB32(buf + 16, s->last_frame_fctl.y_offset);
        AV_WB16(buf + 20, s->last_frame_fctl.delay_num);
        AV_WB16(buf + 22, s->last_frame_fctl.delay_den);
        buf[24] = s->last_frame_fctl.dispose_op;
        buf[25] = s->last_frame_fctl.blend_op;
        png_write_chunk(&last_fctl_chunk_start, MKTAG('f', 'c', 'T', 'L'), buf, 26);
        *got_packet = 1;
    }
    if (pict) {
        if (!s->last_frame) {
            s->last_frame = av_frame_alloc();
            if (!s->last_frame)
                return AVERROR(ENOMEM);
        } else if (s->last_frame_fctl.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {
            if (!s->prev_frame) {
                s->prev_frame = av_frame_alloc();
                if (!s->prev_frame)
                    return AVERROR(ENOMEM);
                s->prev_frame->format = pict->format;
                s->prev_frame->width = pict->width;
                s->prev_frame->height = pict->height;
                if ((ret = av_frame_get_buffer(s->prev_frame, 32)) < 0)
                    return ret;
            }
            // Do disposal, but not blending
            memcpy(s->prev_frame->data[0], s->last_frame->data[0],
                   s->last_frame->linesize[0] * s->last_frame->height);
            if (s->last_frame_fctl.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {
                uint32_t y;
                uint8_t bpp = (s->bits_per_pixel + 7) >> 3;
                for (y = s->last_frame_fctl.y_offset; y < s->last_frame_fctl.y_offset + s->last_frame_fctl.height; ++y) {
                    size_t row_start = s->last_frame->linesize[0] * y + bpp * s->last_frame_fctl.x_offset;
                    memset(s->prev_frame->data[0] + row_start, 0, bpp * s->last_frame_fctl.width);
                }
            }
        }
        av_frame_unref(s->last_frame);
        ret = av_frame_ref(s->last_frame, (AVFrame*)pict);
        if (ret < 0)
            return ret;
        s->last_frame_fctl = fctl_chunk;
        s->last_frame_packet_size = s->bytestream - s->bytestream_start;
    } else {
        av_frame_free(&s->last_frame);
    }
    return 0;
}


void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, uint8_t *segment, uint8_t *ref)

{

    VP56RangeCoder *c = &s->c;

    if (s->segmentation.update_map)

        *segment = vp8_rac_get_tree(c, vp8_segmentid_tree, s->prob->segmentid);

    else

        *segment = ref ? *ref : *segment;

    s->segment = *segment;

    mb->skip = s->mbskip_enabled ? vp56_rac_get_prob(c, s->prob->mbskip) : 0;

    if (s->keyframe) {

        mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_intra, vp8_pred16x16_prob_intra);

        if (mb->mode == MODE_I4x4) {

            decode_intra4x4_modes(s, c, mb_x, 1);

        } else {

            const uint32_t modes = vp8_pred4x4_mode[mb->mode] * 0x01010101u;

            AV_WN32A(s->intra4x4_pred_mode_top + 4 * mb_x, modes);

            AV_WN32A(s->intra4x4_pred_mode_left, modes);

        }

        s->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, vp8_pred8x8c_prob_intra);

        mb->ref_frame = VP56_FRAME_CURRENT;

    } else if (vp56_rac_get_prob_branchy(c, s->prob->intra)) {

        // inter MB, 16.2

        if (vp56_rac_get_prob_branchy(c, s->prob->last))

            mb->ref_frame = vp56_rac_get_prob(c, s->prob->golden) ?

                VP56_FRAME_GOLDEN2 /* altref */ : VP56_FRAME_GOLDEN;

        else

            mb->ref_frame = VP56_FRAME_PREVIOUS;

        s->ref_count[mb->ref_frame-1]++;

        // motion vectors, 16.3

        decode_mvs(s, mb, mb_x, mb_y);

    } else {

        // intra MB, 16.1

        mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16);

        if (mb->mode == MODE_I4x4)

            decode_intra4x4_modes(s, c, mb_x, 0);

        s->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, s->prob->pred8x8c);

        mb->ref_frame = VP56_FRAME_CURRENT;

        mb->partitioning = VP8_SPLITMVMODE_NONE;

        AV_ZERO32(&mb->bmv[0]);

    }

}


static av_cold int join_init(AVFilterContext *ctx)

{

    JoinContext *s = ctx->priv;

    int ret, i;

    if (!(s->channel_layout = av_get_channel_layout(s->channel_layout_str))) {

        av_log(ctx, AV_LOG_ERROR, "Error parsing channel layout '%s'.\n",

               s->channel_layout_str);

        return AVERROR(EINVAL);

    }

    s->nb_channels  = av_get_channel_layout_nb_channels(s->channel_layout);

    s->channels     = av_mallocz_array(s->nb_channels, sizeof(*s->channels));

    s->buffers      = av_mallocz_array(s->nb_channels, sizeof(*s->buffers));

    s->input_frames = av_mallocz_array(s->inputs, sizeof(*s->input_frames));

    if (!s->channels || !s->buffers|| !s->input_frames)

        return AVERROR(ENOMEM);

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

        s->channels[i].out_channel = av_channel_layout_extract_channel(s->channel_layout, i);

        s->channels[i].input       = -1;

    }

    if ((ret = parse_maps(ctx)) < 0)

        return ret;

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

        char name[32];

        AVFilterPad pad = { 0 };

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

        pad.type           = AVMEDIA_TYPE_AUDIO;

        pad.name           = av_strdup(name);

        if (!pad.name)

            return AVERROR(ENOMEM);

        pad.filter_frame   = filter_frame;

        pad.needs_fifo = 1;

        ff_insert_inpad(ctx, i, &pad);

    }

    return 0;

}


static int virtio_net_can_receive(VLANClientState *vc)

{

    VirtIONet *n = vc->opaque;

    return do_virtio_net_can_receive(n, VIRTIO_NET_MAX_BUFSIZE);

}


static av_cold int v4l2_encode_init(AVCodecContext *avctx)

{

    V4L2m2mContext *s = avctx->priv_data;

    V4L2Context *capture = &s->capture;

    V4L2Context *output = &s->output;

    int ret;

    /* common settings output/capture */

    output->height = capture->height = avctx->height;

    output->width = capture->width = avctx->width;

    /* output context */

    output->av_codec_id = AV_CODEC_ID_RAWVIDEO;

    output->av_pix_fmt = avctx->pix_fmt;

    /* capture context */

    capture->av_codec_id = avctx->codec_id;

    capture->av_pix_fmt = AV_PIX_FMT_NONE;

    ret = ff_v4l2_m2m_codec_init(avctx);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "can't configure encoder\n");

        return ret;

    }

    return v4l2_prepare_encoder(s);

}


static int nvdec_vp9_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)

{

    NVDECContext *ctx = avctx->internal->hwaccel_priv_data;

    void *tmp;

    tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,

                          (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));

    if (!tmp)

        return AVERROR(ENOMEM);

    ctx->slice_offsets = tmp;

    if (!ctx->bitstream)

        ctx->bitstream = (uint8_t*)buffer;

    ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;

    ctx->bitstream_len += size;

    ctx->nb_slices++;

    return 0;

}


bool visit_start_union(Visitor *v, bool data_present, Error **errp)

{

    if (v->start_union) {

        return v->start_union(v, data_present, errp);

    }

    return true;

}


static int mxf_read_header(AVFormatContext *s)

{

    MXFContext *mxf = s->priv_data;

    KLVPacket klv;

    int64_t essence_offset = 0;

    int ret;

    mxf->last_forward_tell = INT64_MAX;

    mxf->edit_units_per_packet = 1;

    if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {

        av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");

        return AVERROR_INVALIDDATA;

    }

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

    mxf->fc = s;

    mxf->run_in = avio_tell(s->pb);

    mxf_read_random_index_pack(s);

    while (!url_feof(s->pb)) {

        const MXFMetadataReadTableEntry *metadata;

        if (klv_read_packet(&klv, s->pb) < 0) {

            /* EOF - seek to previous partition or stop */

            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)

                break;

            else

                continue;

        }

        PRINT_KEY(s, "read header", klv.key);

        av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);

        if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||

            IS_KLV_KEY(klv.key, mxf_essence_element_key) ||

            IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||

            IS_KLV_KEY(klv.key, mxf_system_item_key)) {

            if (!mxf->current_partition) {

                av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");

                return AVERROR_INVALIDDATA;

            }

            if (!mxf->current_partition->essence_offset) {

                /* for OP1a we compute essence_offset

                 * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)

                 * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset

                 *       for OPAtom we still need the actual essence_offset though (the KL's length can vary)

                 */

                int64_t op1a_essence_offset =

                    round_to_kag(mxf->current_partition->this_partition +

                                 mxf->current_partition->pack_length,       mxf->current_partition->kag_size) +

                    round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +

                    round_to_kag(mxf->current_partition->index_byte_count,  mxf->current_partition->kag_size);

                if (mxf->op == OPAtom) {

                    /* point essence_offset to the actual data

                    * OPAtom has all the essence in one big KLV

                    */

                    mxf->current_partition->essence_offset = avio_tell(s->pb);

                    mxf->current_partition->essence_length = klv.length;

                } else {

                    /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf)  */

                    mxf->current_partition->essence_offset = op1a_essence_offset;

                }

            }

            if (!essence_offset)

                essence_offset = klv.offset;

            /* seek to footer, previous partition or stop */

            if (mxf_parse_handle_essence(mxf) <= 0)

                break;

            continue;

        } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&

                   klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {

            /* next partition pack - keep going, seek to previous partition or stop */

            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)

                break;

            else if (mxf->parsing_backward)

                continue;

            /* we're still parsing forward. proceed to parsing this partition pack */

        }

        for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {

            if (IS_KLV_KEY(klv.key, metadata->key)) {

                int res;

                if (klv.key[5] == 0x53) {

                    res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);

                } else {

                    uint64_t next = avio_tell(s->pb) + klv.length;

                    res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);

                    /* only seek forward, else this can loop for a long time */

                    if (avio_tell(s->pb) > next) {

                        av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",

                               klv.offset);

                        return AVERROR_INVALIDDATA;

                    }

                    avio_seek(s->pb, next, SEEK_SET);

                }

                if (res < 0) {

                    av_log(s, AV_LOG_ERROR, "error reading header metadata\n");

                    return res;

                }

                break;

            }

        }

        if (!metadata->read)

            avio_skip(s->pb, klv.length);

    }

    /* FIXME avoid seek */

    if (!essence_offset)  {

        av_log(s, AV_LOG_ERROR, "no essence\n");

        return AVERROR_INVALIDDATA;

    }

    avio_seek(s->pb, essence_offset, SEEK_SET);

    mxf_compute_essence_containers(mxf);

    /* we need to do this before computing the index tables

     * to be able to fill in zero IndexDurations with st->duration */

    if ((ret = mxf_parse_structural_metadata(mxf)) < 0)

        goto fail;

    if ((ret = mxf_compute_index_tables(mxf)) < 0)

        goto fail;

    if (mxf->nb_index_tables > 1) {

        /* TODO: look up which IndexSID to use via EssenceContainerData */

        av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",

               mxf->nb_index_tables, mxf->index_tables[0].index_sid);

    } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {

        av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");

        ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    mxf_handle_small_eubc(s);

    return 0;

fail:

    mxf_read_close(s);

    return ret;

}


static bool arm_cpu_has_work(CPUState *cs)

{

    ARMCPU *cpu = ARM_CPU(cs);

    return !cpu->powered_off

        && cs->interrupt_request &

        (CPU_INTERRUPT_FIQ | CPU_INTERRUPT_HARD

         | CPU_INTERRUPT_VFIQ | CPU_INTERRUPT_VIRQ

         | CPU_INTERRUPT_EXITTB);

}


exynos4210_combiner_read(void *opaque, target_phys_addr_t offset, unsigned size)

{

    struct Exynos4210CombinerState *s =

            (struct Exynos4210CombinerState *)opaque;

    uint32_t req_quad_base_n;    /* Base of registers quad. Multiply it by 4 and

                                   get a start of corresponding group quad */

    uint32_t grp_quad_base_n;    /* Base of group quad */

    uint32_t reg_n;              /* Register number inside the quad */

    uint32_t val;

    req_quad_base_n = offset >> 4;

    grp_quad_base_n = req_quad_base_n << 2;

    reg_n = (offset - (req_quad_base_n << 4)) >> 2;

    if (req_quad_base_n >= IIC_NGRP) {

        /* Read of ICIPSR register */

        return s->icipsr[reg_n];

    }

    val = 0;

    switch (reg_n) {

    /* IISTR */

    case 2:

        val |= s->group[grp_quad_base_n].src_pending;

        val |= s->group[grp_quad_base_n + 1].src_pending << 8;

        val |= s->group[grp_quad_base_n + 2].src_pending << 16;

        val |= s->group[grp_quad_base_n + 3].src_pending << 24;

        break;

    /* IIMSR */

    case 3:

        val |= s->group[grp_quad_base_n].src_mask &

        s->group[grp_quad_base_n].src_pending;

        val |= (s->group[grp_quad_base_n + 1].src_mask &

                s->group[grp_quad_base_n + 1].src_pending) << 8;

        val |= (s->group[grp_quad_base_n + 2].src_mask &

                s->group[grp_quad_base_n + 2].src_pending) << 16;

        val |= (s->group[grp_quad_base_n + 3].src_mask &

                s->group[grp_quad_base_n + 3].src_pending) << 24;

        break;

    default:

        if (offset >> 2 >= IIC_REGSET_SIZE) {

            hw_error("exynos4210.combiner: overflow of reg_set by 0x"

                    TARGET_FMT_plx "offset\n", offset);

        }

        val = s->reg_set[offset >> 2];

        return 0;

    }

    return val;

}


static void int8x8_fmul_int32_c(float *dst, const int8_t *src, int scale)

{

    float fscale = scale / 16.0;

    int i;

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

        dst[i] = src[i] * fscale;

}