/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL AND KEVIN E. MARTIN DISCLAIMS ALL WARRANTIES WITH REGARD TO
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS, IN NO EVENT SHALL THOMAS ROELL OR KEVIN E. MARTIN BE LIABLE FOR
 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Author:  Thomas Roell, roell@informatik.tu-muenchen.de
 *
 * Rewritten for the 8514/A by Kevin E. Martin (martin@cs.unc.edu)
 *
 * $Header: /proj/X11/mit/server/ddx/x386/vga/RCS/vga.c,v 1.2 1991/06/27 00:02:49 root Exp $
 */


#include "X.h"
#include "input.h"
#include "scrnintstr.h"
#include "mipointer.h"
#include "cursorstr.h"

#include "compiler.h"

#include "x386.h"
#include "x386Priv.h"
#include "x386OSD.h"
#include "ibm8514.h"
#include "reg8514.h"
#include "cfb.h"
#include "vga.h"

extern void NoopDDA();

ScrnInfoRec vga256InfoRec = {
    FALSE,		/* Bool configured */
    -1,			/* int index */
    ibm8514Probe,      	/* Bool (* Probe)() */
    ibm8514Initialize,	/* Bool (* Init)() */
    ibm8514EnterLeaveVT,/* void (* EnterLeaveVT)() */
    NoopDDA,		/* void (* EnterLeaveMonitor)() */
    NoopDDA,		/* void (* EnterLeaveCursor)() */
    S3AdjustFrame,		/* void (* AdjustFrame)() */
    S3SwitchMode,		/* void (* SwitchMode)() */
    8,			/* int depth */
    8,			/* int bitsPerPixel */
    PseudoColor,       	/* int defaultVisual */
    -1, -1,		/* int virtualX,virtualY */
    -1, -1, -1, -1,	/* int frameX0, frameY0, frameX1, frameY1 */
    NULL,	       	/* char *vendor */
    NULL,	       	/* char *chipset */
    0,			/* int clocks */
    {0, },		/* int clock[MAXCLOCKS] */
    0,			/* int videoRam */
    240, 180,		/* int width, height */
    NULL,	       	/* DisplayModePtr modes */
};

short ibm8514alu[16] = {
    MIX_0,
    MIX_AND,
    MIX_SRC_AND_NOT_DST,
    MIX_SRC,
    MIX_NOT_SRC_AND_DST,
    MIX_DST,
    MIX_XOR,
    MIX_OR,
    MIX_NOR,
    MIX_XNOR,
    MIX_NOT_DST,
    MIX_SRC_OR_NOT_DST,
    MIX_NOT_SRC,
    MIX_NOT_SRC_OR_DST,
    MIX_NAND,
    MIX_1
};

extern miPointerScreenFuncRec x386PointerScreenFuncs;

static int AlreadyInited = FALSE;

static int ibm8514ScreenMode;

/*
 * ibm8514Probe --
 *     probe and initialize the hardware driver
 */
Bool
ibm8514Probe()
{
  DisplayModePtr pMode, pEnd;
  unsigned char config;
      outp(0x3d4, 0x11);
      outp(0x3d5, 0x00);
      outp(0x3d4,0x38);
      outp(0x3d5, 0x48);

      outb(0x3d4, 0x36);
      config = inb(0x3d5);     /*    get amount of vram installed */

      if ((config & 0x20) != 0 ) {
    
	vga256InfoRec.videoRam = 512;
      } else {
	vga256InfoRec.videoRam = 1024; 
      }


	pMode = pEnd = vga256InfoRec.modes;
	do {
	  x386LookupMode(pMode, &vga256InfoRec);
      	  if (pMode->HDisplay * pMode->VDisplay > vga256InfoRec.videoRam*1024)
	    {
	      ErrorF("Too less memory for all resolutions\n");
	      return(FALSE);
	    }
           if (pMode->HDisplay > 1024 || pMode->VDisplay > 768)
	   {
	    ErrorF("Display %dx%d is too large: must be smaller than 1024x768\n",
		   pMode->HDisplay, pMode->VDisplay);
	    return(FALSE);
	  }
	   pMode = pMode->next;
	} while (pMode != pEnd);
        ErrorF("S3\n");	
	return TRUE;
}





/*
 * ibm8514Initialize --
 *      Attempt to find and initialize a VGA framebuffer
 *      Most of the elements of the ScreenRec are filled in.  The
 *      video is enabled for the frame buffer...
 */

Bool
ibm8514Initialize (index, pScreen, argc, argv)
    int            index;        /* The index of pScreen in the ScreenInfo */
    ScreenPtr      pScreen;      /* The Screen to initialize */
    int            argc;         /* The number of the Server's arguments. */
    char           **argv;       /* The arguments themselves. Don't change! */
{
    if (vga256InfoRec.virtualX == 1024 && vga256InfoRec.virtualY == 768) {
	ibm8514ScreenMode = MODE_1024;
    } else if (vga256InfoRec.virtualX == 640 &&
	       vga256InfoRec.virtualY == 480) {
	ibm8514ScreenMode = MODE_640;
    } /*else {
	ErrorF("Illegal screen size: (%dx%d)\n",
	       vga256InfoRec.virtualX, vga256InfoRec.virtualY);
	return FALSE;
    } */

    /* Map io ports, map registers, etc. */
    /* Initialize the screen, saving the original state for Save/Restore
       function */

    Init8514( vga256InfoRec.modes);
    InitEnvironment();
    AlreadyInited = TRUE;

#ifdef testing_8514
    if (ibm8514ScreenMode == MODE_1024)
	vga256InfoRec.virtualY = 512;
#endif

    ibm8514CacheInit(vga256InfoRec.virtualX, vga256InfoRec.virtualY);
    ibm8514FontCache8Init(vga256InfoRec.virtualX, vga256InfoRec.virtualY);

    ibm8514ImageInit();

    if (!ibm8514ScreenInit(pScreen,
			   (pointer) 0,
			   vga256InfoRec.virtualX, vga256InfoRec.virtualY,
			   75, 75,
			   vga256InfoRec.virtualX))
	return(FALSE);

    pScreen->CloseScreen = ibm8514CloseScreen;
    pScreen->SaveScreen = ibm8514SaveScreen;
    pScreen->InstallColormap = ibm8514InstallColormap;
    pScreen->UninstallColormap = ibm8514UninstallColormap;
    pScreen->ListInstalledColormaps = ibm8514ListInstalledColormaps;
    pScreen->StoreColors = ibm8514StoreColors;

    mfbRegisterCopyPlaneProc (pScreen, miCopyPlane);
  
/*    miDCInitialize (pScreen, &x386PointerScreenFuncs); sofware cursor */
    s3CursorInit(0, pScreen);
    return (cfbCreateDefColormap(pScreen));

}

/*
 * ibm8514EnterLeaveVT -- 
 *      grab/ungrab the current VT completely.
 */

void
ibm8514EnterLeaveVT(enter)
     Bool enter;
{
    if (enter) {
	Init8514(vga256InfoRec.modes);
	InitEnvironment();
	AlreadyInited = TRUE;
    } else {
	/*
	 * We come here in many cases, but one is special: When the server
	 * aborts abnormaly. Therefore there MUST be a check whether
	 * vgaOrigVideoState is valid or not.
	 */
	/* The above refers to the video state not being set up until the
	   Initialize function (above) is called.  If it has not been called
	   then "vgaOrigVideoState" will not be initialized and thus cannot be
	   restored!  A similar thing must be done in the 8514.
	   */
	if (AlreadyInited) {
	    CleanUp8514(); ErrorF("\n Exiting\n");
	}
    }
}

/*
 * ibm8514CloseScreen --
 *      called to ensure video is enabled when server exits.
 */

Bool
ibm8514CloseScreen()
{
    /*
     * Hmm... The server may shut down even if it is not running on the
     * current vt. Let's catch this case here.
     */
    if (x386VTSema) ibm8514EnterLeaveVT(LEAVE);
    return(TRUE);
}

/*
 * ibm8514SaveScreen --
 *      blank the screen.
 */

Bool
ibm8514SaveScreen (pScreen, on)
     ScreenPtr     pScreen;
     Bool          on;
{
    if (x386VTSema) {
	if (on) {
	    ibm8514RestoreColor0(pScreen);
	    outpw(DAC_MASK, 0xff);
	} else {
	    outp(DAC_W_INDEX, 0);
	    outp(DAC_DATA, 0);
	    outp(DAC_DATA, 0);
	    outp(DAC_DATA, 0);

	    outpw(DAC_MASK, 0x00);
	}
    }
    return(TRUE);
}



void
S3SwitchMode(mode)
     DisplayModePtr mode;
{
   while ((inpw(0x9ae8) & 0x200) != 0); 
   Init8514(mode);
}


void
S3AdjustFrame(int x, int y)
{
  /* int Base = (y * vga256InfoRec.virtualX + x) >> 2; */
   /* width is always 1024! */

  int Base = (y * 1024 + x) >> 2;

  y = Base & 0xffff00;
  if (y > 0x00ff00) y = 0xff00;
  outw(vgaIOBase + 4, y | 0x000C);

  x = Base & 0xff;
  outw(vgaIOBase + 4, (x << 8) | 0x000D);
}
