/*
	xgapos.c

	I don't need the entire xf86config, so I grabbed the appropriate
	chunks of Anders' xf86config mods, hacked some of the extraneous
	stuff out (/proc/mca/pos usually doesn't change after boot, for
	example, and some sscanf magic), and made it dump the important
	stuff - the device section.  Plus a bugfix (which he didn't
	encounter 'cause his adapter is in the last slot checked).

	You may have to change the chipset value for some XGA-1 cards -
	I know mine works, but there may be others.

	Chris Beauregard (chrisb@truespectra.com)
*/

#include <stdio.h>
#include <stdlib.h>

int
main() {
  /*
   * This part was made by Anders Johansson <Anders.Johansson@uab.ericsson.se>
   * This has only been tested on a IBM 9557 (486SLC-2/50 with onboard XGA-2)
   * but should hopefully work with all MCA XGA-2 and probably also XGA-1
   * This needs the MCA patch for 2.0.7 kernel from 1 Sep 96. (or at least
   * the same format for the /proc/mca/pos file.
   */
  const char* const mca_file = "/proc/mca/pos";
  int regflag=0;
  int i,j;
  char ch;
  FILE* proc_mca;
  int posreg[8];  
  int xgareg[8];  
  char tmp[80];
  
  int Instance,IObase,COPbase,MEMbase,BIOSbase;
  
  /*
   * Open the message file.
   */
  if((proc_mca = fopen( "/proc/mca/pos","r"))== 0)
    {
      printf("    # /proc/mca/pos was not found, are you useing the MCA patches ?\n");
      return 1;
    }

 	while(1) {
      /*
       * Get one line.
       */
      if( fgets(tmp,80,proc_mca) == NULL ) break;

	sscanf(tmp,"%*[^:]: %x %x %x %x %x %x %x %x ",&posreg[0],&posreg[1],&posreg[2],&posreg[3],&posreg[4],&posreg[5],&posreg[6],&posreg[7]);

      /*
       * Check if this looks like a XGA type of card
       */
      if(posreg[1] == 0x8f && (posreg[0] > 0xd7 && posreg[0] < 0xdc))
	{
	  regflag++;
	  for(j=0;j<8;j++)
	    {
	      xgareg[j]=posreg[j];
	    }
	}	   
    }
      
  fclose(proc_mca);

  if ( regflag==0 )
    {
      printf( "    # Could not find any pos regs in /proc/mca/pos\n# are you useing the MCA patches ?\n");
      return 1;
    }

  if ( regflag > 1 )
    printf( "    # Warning, looks like more than one XGA card.\n    # Selecting the LAST one.");
  
  /*
   * Calculating configuration from pos regs.
   */
  Instance = (xgareg[2] & 0xe) >> 1;
  IObase = 0x2100 + (Instance << 4);
  MEMbase = (xgareg[4] & 0x000000fe) * 0x1000000 + (Instance << 22);
  COPbase = 0xc1c00 + (((xgareg[2] & 0xf0) >> 4) * 0x2000) + (Instance * 0x80);
  BIOSbase = 0xc0000 + (((xgareg[2] & 0xf0) >> 4) * 0x2000);

  /*
   * Print out result to string.
   */
  printf("    CHIPSET    \"XGA-2\"\n    Instance    %d\n    IObase      0x%x\n    COPbase     0x%x\n    MEMbase     0x%x\n    BIOSbase    0x%x\n", 
	  Instance, IObase,COPbase, MEMbase,BIOSbase);
  return 0;
}     
 
