/*
 * Copyright 1998-2003 VIA Technologies, Inc. All Rights Reserved.
 * Copyright 2001-2003 S3 Graphics, Inc. All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sub license,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * VIA, S3 GRAPHICS, AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */


#ifndef SAVAGE_VGAHWMMIO_H
#define SAVAGE_VGAHWMMIO_H


#include "xf86_ansic.h"
#include "compiler.h"
#include "vgaHW.h"
#include "xf86.h"
#include "xf86Resources.h"
#include "xf86Pci.h"
#include "xf86PciInfo.h"
#include "xf86_OSproc.h"
#include "xf86Cursor.h"
#include "mipointer.h"
#include "micmap.h"
#include "fb.h"
#include "xf86cmap.h"
#include "vbe.h"
#include "xaa.h"
#include "xf86xv.h"

#include "savage_regs.h"

#ifdef XF86DRI
#include "xf86drm.h"

#define _XF86DRI_SERVER_
#include "savage_dripriv.h"
#include "dri.h"
#include "GL/glxint.h"

#include "xf86dri.h"
#include "dri.h"

#include "GL/glxint.h"
#include "savage_dri.h"
#include "savage_drm.h"
#include "savage_vbe.h"
#endif


#ifndef uint
typedef unsigned int            uint;
#endif
#ifndef ulong
typedef unsigned long           ulong;
#endif
#ifndef ushort
typedef unsigned short          ushort;
#endif
#ifndef uchar
typedef unsigned char           uchar;
#endif

/*
 * macros for VGA register(CRXX/SRXX) read/write
 * address should get by VGA module
 */
#define VGAIN8(addr) MMIO_IN8(psav->MapBase+0x8000, addr)
#define VGAIN16(addr) MMIO_IN16(psav->MapBase+0x8000, addr)
#define VGAIN(addr) MMIO_IN32(psav->MapBase+0x8000, addr)
#define VGAOUT8(addr,val) MMIO_OUT8(psav->MapBase+0x8000, addr, val)
#define VGAOUT16(addr,val) MMIO_OUT16(psav->MapBase+0x8000, addr, val)
#define VGAOUT(addr,val) MMIO_OUT32(psav->MapBase+0x8000, addr, val)

#define INREG8(addr) MMIO_IN8(psav->MapBase, addr)
#define INREG16(addr) MMIO_IN16(psav->MapBase, addr)
#define INREG32(addr) MMIO_IN32(psav->MapBase, addr)
#define OUTREG8(addr,val) MMIO_OUT8(psav->MapBase, addr, val)
#define OUTREG16(addr,val) MMIO_OUT16(psav->MapBase, addr, val)
#define OUTREG32(addr,val) MMIO_OUT32(psav->MapBase, addr, val)
#define INREG(addr) INREG32(addr) 
#define OUTREG(addr,val) OUTREG32(addr,val) 

#if X_BYTE_ORDER == X_LITTLE_ENDIAN
#define B_O16(x)  (x)
#define B_O32(x)  (x)
#else
#define B_O16(x)  ((((x) & 0xff) << 8) | (((x) & 0xff) >> 8))
#define B_O32(x)  ((((x) & 0xff) << 24) | (((x) & 0xff00) << 8) \
                  | (((x) & 0xff0000) >> 8) | (((x) & 0xff000000) >> 24))
#endif
#define L_ADD(x)  (B_O32(x) & 0xffff) + ((B_O32(x) >> 12) & 0xffff00)

#define SAVAGE_CRT_ON	1
#define SAVAGE_LCD_ON	2
#define SAVAGE_TV_ON	4

#define SAVAGEIOMAPSIZE	0x80000


typedef struct _S3VMODEENTRY {
   unsigned short Width;
   unsigned short Height;
   unsigned short VesaMode;
   unsigned char RefreshCount;
   unsigned char * RefreshRate;
} SavageModeEntry, *SavageModeEntryPtr;


typedef struct _S3VMODETABLE {
   unsigned short NumModes;
   SavageModeEntry Modes[1];
} SavageModeTableRec, *SavageModeTablePtr;


typedef struct {
    unsigned int mode, refresh;
    unsigned char SR08, SR0E, SR0F;
    unsigned char SR10, SR11, SR12, SR13, SR15, SR18, SR29, SR30;
    unsigned char SR54[8];
    unsigned char Clock;
    unsigned char CR31, CR32, CR33, CR34, CR36, CR3A, CR3B, CR3C;
    unsigned char CR40, CR41, CR42, CR43, CR45;
    unsigned char CR50, CR51, CR53, CR55, CR58, CR5B, CR5D, CR5E;
    unsigned char CR60, CR63, CR65, CR66, CR67, CR68, CR69, CR6D, CR6F;
    unsigned char CR86, CR88;
    unsigned char CR90, CR91, CRB0;
    unsigned int  STREAMS[22];	/* yuck, streams regs */
    unsigned int  MMPR0, MMPR1, MMPR2, MMPR3;
} SavageRegRec, *SavageRegPtr;


/*  Tiling defines */
#define TILE_SIZE_BYTE     2048   /* 0x800, 2K */

#define TILEHEIGHT_16BPP        16
#define TILEHEIGHT_32BPP        16
#define TILEHEIGHT              16      /* all 16 and 32bpp tiles are 16 lines high */

#define TILEWIDTH_BYTES         128     /* 2048/TILEHEIGHT (** not for use w/8bpp tiling) */
#define TILEWIDTH8BPP_BYTES     64      /* 2048/TILEHEIGHT_8BPP */
#define TILEWIDTH_16BPP         64      /* TILEWIDTH_BYTES/2-BYTES-PER-PIXEL */
#define TILEWIDTH_32BPP         32      /* TILEWIDTH_BYTES/4-BYTES-PER-PIXEL */


/* Bitmap descriptor structures for BCI */
typedef struct _HIGH {
    ushort Stride;
    uchar Bpp;
    uchar ResBWTile;
} HIGH;

typedef struct _BMPDESC1 {
    ulong Offset;
    HIGH  HighPart;
} BMPDESC1;

typedef struct _BMPDESC2 {
    ulong LoPart;
    ulong HiPart;
} BMPDESC2;

typedef union _BMPDESC {
    BMPDESC1 bd1;
    BMPDESC2 bd2;
} BMPDESC;

typedef struct _TvInfo {
    long TvEndScratchBuf;
    long TvStartScratchBuf;
    int TvChip;    
    unsigned long   TvStandardSupport;/* S3_TVSTD_SUPPORT_xx format */
    TVTECH_TYPE     TvStandardInUse;/* S3_TVSTD_SUPPORT_xx format */
    TVSIGNAL_TYPE   TvSignalType;/* Current (more types defined) */
    int TvI2CAddress;
    int	TvSizeX;
    int	TvSizeY;
    Bool TvUnderscanning;
    Bool TvForcePanning;
} TvInfoRec,*TvInfoPtr;

typedef struct _StatInfo {
    int     origMode;
    int     pageCnt;    
    pointer statBuf;
    int     realSeg;    
    int     realOff;
} StatInfoRec,*StatInfoPtr;
    
typedef struct _Savage {
    SavageRegRec	SavedReg;
    SavageRegRec	ModeReg;
    xf86CursorInfoPtr	CursorInfoRec;
    Bool		ModeStructInit;
    Bool		NeedSTREAMS;
    Bool		STREAMSRunning;
    int			Bpp, Bpl, ScissB;
    unsigned		PlaneMask;
    I2CBusPtr		I2C;
    I2CBusPtr		DVI;
    unsigned char       DDCPort;
    unsigned char       I2CPort;

    int			videoRambytes;
    int			videoRamKbytes;
    int			MemOffScreen;
    int         endfb;
    CARD32		CursorKByte;

    /* These are physical addresses. */
    unsigned long	FrameBufferBase;
    unsigned long	MmioBase;
    unsigned long	ApertureBase;
    unsigned long	ShadowPhysical;

    /* These are linear addresses. */
    unsigned char*	MapBase;
    unsigned char*	BciMem;
    unsigned char*	MapBaseDense;
    unsigned char*	FBBase;
    unsigned char*	ApertureMap;
    unsigned char*	FBStart;
    CARD32 volatile *	ShadowVirtual;

    Bool		PrimaryVidMapped;
    int			dacSpeedBpp;
    int			minClock, maxClock;
    int			HorizScaleFactor;
    int			MCLK, REFCLK, LCDclk;
    double		refclk_fact;
    int			GEResetCnt;

    /* Here are all the Options */
    Bool		ShowCache;
    Bool		pci_burst;
    Bool		NoPCIRetry;
    Bool		fifo_conservative;
    Bool		fifo_moderate;
    Bool		fifo_aggressive;
    Bool		hwcursor;
    Bool		NoAccel;
    Bool		shadowFB;
    Bool		UseBIOS;
    int			rotate;
    double		LCDClock;
    Bool		ShadowStatus;
    Bool		CrtOnly;

    Bool		LcdOn;
    Bool		TvOn;
    
    /*add by peterzhu*/
    Bool		SAA7111;	/* program SAA7111 or not?? */
    Bool		v4l_videoin;	/* v4l video in or user mode way---add by peterzhu*/
    int			v4l_devnum;	/* v4l device number, 0,1,2....*/
    Bool		double_buffer;  /* whether Video in is double buffer*/
    
    Bool		Panning;
    Bool		FPExpansion;
    Bool 		Switchmode;

    int			PanelX;		/* panel width */
    int			PanelY;		/* panel height */
    int			iResX;		/* crtc X display */
    int			iResY;		/* crtc Y display */
    int			XFactor;	/* overlay X factor */
    int			YFactor;	/* overlay Y factor */
    int			displayXoffset; /* overlay X offset */
    int			displayYoffset; /* overlay Y offset */
    int			XExpansion;	/* expansion factor in x */
    int			XExp1;
    int			XExp2;
    int			YExp1;
    int			YExp2;
    int			YExpansion;	/* expansion factor in y */

    CloseScreenProcPtr	CloseScreen;
    pciVideoPtr	PciInfo;
    PCITAG		PciTag;
    int			Chipset;
    int			ChipId;
    int			ChipRev;
    const char *ChipName;
    int         DrvVersion;    
    int         BiosVersion;

    vbeInfoPtr	pVbe;
    int			EntityIndex;
    int			ShadowCounter;
    
    /* The various Savage wait handlers. */
    int			(*WaitQueue)(struct _Savage *, int);
    int			(*WaitIdle)(struct _Savage *);
    int			(*WaitIdleEmpty)(struct _Savage *);

    /* Support for shadowFB and rotation */
    unsigned char *	ShadowPtr;
    int			ShadowPitch;
    void		(*PointerMoved)(int index, int x, int y);

    /* Support for XAA acceleration */
    XAAInfoRecPtr	AccelInfoRec;
    xRectangle		Rect;
    unsigned int	SavedBciCmd;
    unsigned int	SavedFgColor;
    unsigned int	SavedBgColor;
    unsigned int	SavedSbdOffset;
    unsigned int	SavedSbd;
    unsigned int    SavedClipTopLeft;
    unsigned int    SavedClipBottomRight;

    /* Support for Int10 processing */
    xf86Int10InfoPtr	pInt10;
    SavageModeTablePtr	ModeTable;
    unsigned short	VesaModeList[256];
    int			VesaModeNum;

    /* Support for the Savage command overflow buffer. */
    unsigned long	cobIndex;	/* size index */
    unsigned long	cobSize;	/* size in bytes */
    unsigned long	cobOffset;	/* offset in frame buffer */

    /* Support for DGA */
    int			numDGAModes;
    DGAModePtr		DGAModes;
    Bool		DGAactive;
    int			DGAViewportStatus;

    /* Support for XVideo */
    unsigned int	videoFlags;
    unsigned int	blendBase;
    int			videoFourCC;

#ifdef XF86DRI
    int 		LockHeld;
    Bool 		directRenderingEnabled;
    DRIInfoPtr 		pDRIInfo;
    int 		drmFD;
    int 		numVisualConfigs;
    __GLXvisualConfig*	pVisualConfigs;
    SAVAGEConfigPrivPtr 	pVisualConfigsPriv;
    SAVAGEDRIServerPrivatePtr DRIServerInfo;


#if 0
    Bool		haveQuiescense;
    void		(*GetQuiescence)(ScrnInfoPtr pScrn);
#endif

    int 		agpMode;
    FBLinearPtr		reserved;

    Bool bDisableXvMC;
    
    unsigned int surfaceAllocation[7];
    unsigned int xvmcContext;
    unsigned int DRIrunning;
    unsigned int hwmcOffset;
    unsigned int hwmcSize;

#endif

    XF86VideoAdaptorPtr	adaptor;
    int			VideoZoomMax;

    XF86OffscreenImagePtr offscreenImages;

    /*  Variables relating to multiple display output devices.*/
    int DisplayOutSupport;/* S3_SUPPORT_xxx format.*/
    int DisplayOutsConnected;
    int DisplayOutsActive;/* Displays currently active */
    
    TvInfoRec       TvInfo;
    
    StatInfoRec     StatInfo; /* save the SVGA state */
    
    /* Bitmap Descriptors for BCI */
    BMPDESC GlobalBD;
    BMPDESC PrimaryBD;
    BMPDESC SecondBD;
    /* do we disable tile mode by option? */
    Bool bDisableTile;
    /* if we enable tile,we only support tile under 16/32bpp */
    Bool bTiled;
    int  lDelta;
    int  ulAperturePitch; /* aperture pitch */

    int  l3DDelta; 
    int  ul3DAperturePitch; /* pitch for 3D */
    /*
     * cxMemory is number of pixels across screen width
     * cyMemory is number of scanlines in available adapter memory.
     *
     * cxMemory * cyMemory is used to determine how much memory to
     * allocate to our heap manager.  So make sure that any space at the
     * end of video memory set aside at bInitializeHardware time is kept
     * out of the cyMemory calculation.
     */
    int cxMemory,cyMemory;
    
    int cxScreen;
    
    Bool DualHead;
} SavageRec, *SavagePtr;

/* Video flags. */
#define VF_STREAMS_ON	0x0001

#define SAVPTR(p)	((SavagePtr)((p)->driverPrivate))

/* add for support DRI */
#ifdef XF86DRI

#define SAVAGE_FRONT	0x1
#define SAVAGE_BACK	0x2
#define SAVAGE_DEPTH	0x4
#define SAVAGE_STENCIL	0x8

Bool SAVAGEDRIScreenInit( ScreenPtr pScreen );
Bool SAVAGEInitMC(ScreenPtr pScreen);
void SAVAGEDRICloseScreen( ScreenPtr pScreen );
Bool SAVAGEDRIFinishScreenInit( ScreenPtr pScreen );

Bool SAVAGELockUpdate( ScrnInfoPtr pScrn, drmLockFlags flags );

#if 0
void SAVAGEGetQuiescence( ScrnInfoPtr pScrn );
void SAVAGEGetQuiescenceShared( ScrnInfoPtr pScrn );
#endif

void SAVAGESelectBuffer(ScrnInfoPtr pScrn, int which);

#if 0
Bool SAVAGECleanupDma(ScrnInfoPtr pScrn);
Bool SAVAGEInitDma(ScrnInfoPtr pScrn, int prim_size);
#endif

#define SAVAGE_AGP_1X_MODE		0x01
#define SAVAGE_AGP_2X_MODE		0x02
#define SAVAGE_AGP_4X_MODE		0x04
#define SAVAGE_AGP_MODE_MASK	0x07

#endif


/* Prototypes. */
extern void SavageCommonCalcClock(long freq, int min_m, int min_n1,
			int max_n1, int min_n2, int max_n2,
			long freq_min, long freq_max,
			unsigned char *mdiv, unsigned char *ndiv);
void SavageAdjustFrame(int scrnIndex, int y, int x, int flags);
Bool SavageSwitchMode(int scrnIndex, DisplayModePtr mode, int flags);

/* In savage_cursor.c. */
Bool SavageHWCursorInit(ScreenPtr pScreen);
void SavageShowCursor(ScrnInfoPtr);
void SavageHideCursor(ScrnInfoPtr);

/* In savage_accel.c. */
extern ScrnInfoPtr gpScrn;
Bool SavageInitAccel(ScreenPtr);
void SavageAccelSync(ScrnInfoPtr);

/* In savage_i2c.c. */
Bool SavageI2CInit(ScrnInfoPtr pScrn);

/* In savage_shadow.c */
void SavagePointerMoved(int index, int x, int y);
void SavageRefreshArea(ScrnInfoPtr pScrn, int num, BoxPtr pbox);
void SavageRefreshArea8(ScrnInfoPtr pScrn, int num, BoxPtr pbox);
void SavageRefreshArea16(ScrnInfoPtr pScrn, int num, BoxPtr pbox);
void SavageRefreshArea24(ScrnInfoPtr pScrn, int num, BoxPtr pbox);
void SavageRefreshArea32(ScrnInfoPtr pScrn, int num, BoxPtr pbox);

/* In savage_vbe.c */
Bool SavageSetupDevice(SavagePtr psav);
void SavageSetTextMode(SavagePtr psav);
Bool SavageSetVESAMode(SavagePtr psav, int n, int Refresh);
void SavageFreeBIOSModeTable(SavagePtr psav, SavageModeTablePtr* ppTable);
SavageModeTablePtr SavageGetBIOSModeTable(SavagePtr psav, int iDepth);
ModeStatus SavageMatchBiosMode(ScrnInfoPtr pScrn,int width,int height,int refresh,
                              unsigned int *vesaMode,unsigned int *newRefresh);
int SavageGetBIOSModes(SavagePtr psav,int iDepth,SavageModeEntryPtr s3vModeTable);
Bool SavageSetActiveDevice(SavagePtr psav,int activedev);
Bool SavageSaveRestoreState(SavagePtr psav,Bool save);


unsigned long SAVAGEDRIGetPhyAddress(ScrnInfoPtr pScrn,void * pointer);
Bool          SavageDGAInit(ScreenPtr);

/* In savage_video.c */
void SavageInitVideo(ScreenPtr pScreen);
extern void (*SavageInitStreams)(ScrnInfoPtr pScrn);

/* In savage_util.c */
int  SavageDoUtilCall(ScrnInfoPtr pScrn,char *buf);

#endif /* SAVAGE_VGAHWMMIO_H */


