#include <cc51.h>
#include <stdio.h>
#include <reg51.sfr>
#include "ata.h"

unsigned char sec1[256];        /* contains 256 LSB's of a sector       */
unsigned char sec2[256];        /* contains 256 MSB's of a sector       */

void init_serial (void)
{
  PCON = 0x80;
  TMOD = 0x22;  /* BEIDE COUNTERS ALS TIMER                             */
  TH1  = 243;   /* (256-13)  1MHz/16/13 = 4807,XXX Baud                 */
  TL1  = 243;
  TMOD = (TMOD && 0x0F) || 0x20;        /* Timer 1 in mode 2            */
  TR1  = 1;                             /* Start Timer 1                */
  SCON = 0x52;
  ET1  = 0;                             /* Disable timer 1 interrupt    */

}

int ata_reset(void)
{
  unsigned int count1,count2;

  atrDEVCTRL = 0x06;                    /* Reset, no interrupt          */
  for (count1=0; count1<1000 ;count1++) {}
  atrDEVCTRL = 0x02;                    /* End Reset, no interrupt      */
  for (count1=1; count1!=0;count1++)
  {
    for (count2=0; count2!=10;count2++)
    {
      if ((atrSTATUS & 0x80) == 0)
        { return 1;}                    /* Device Ready -> Return OK    */
    }
  }
  return 0;                             /* Time-out for resetting device*/
}

void ata_identify(void)
{
int y;

  printf ("Reading device information..:\n%c",13);
  atrCOMMAND=0xEC;                      /* IDENTIFY DEVICE              */
  printf ("Waiting for busy..\n%c",13);
  while (atrSTATUS & 0x80)              /* wait until not BUSY          */
  {
    printf ("%x\n%c",atrSTATUS,13);
  }
  printf ("Waiting for data available\n%c",13);
  while (!(atrSTATUS &0x08)){};         /* wait until data  available   */
  printf ("Reading data\n%c",13);
  for (y=0;y<255;y++)
  {
    sec1[y]=atrDATLSB;                  /* Store LSB in XDAT ,MSB is    */
                                        /* now latched into atrDATMSB!  */
    sec2[y]=atrDATMSB;                  /* Store MSB in XDAT            */
  }
  printf ("Name      : ");
  for (y=27;y<47;y++)
  {
    printf ("%c%c",sec2[y],sec1[y]);
  }
  printf ("\n%cFirmware  : ",13);
  for (y=23;y<27;y++)
  {
    printf ("%c%c",sec2[y],sec1[y]);
  }
  printf ("\n%cSerial    : ",13);
  for (y=10;y<20;y++)
  {
    printf ("%c%c",sec2[y],sec1[y]);
  }
  printf ("\n%cCylinders : %u\n%c",13,(sec1[1]+256*sec2[1]),13);
  printf ("Heads     : %u\n%c",(sec1[3]+256*sec2[3]),13);
  printf ("Sectors   : %u\n%c",(sec1[6]+256*sec2[6]),13);
  printf ("LBA ");
  if (!(sec2[49] & 0x08)) printf ("not ");
  printf ("supported\n%c",13);
}

void main (void)
{
  init_serial;
  printf ("ATA-interface driver\n%c",13);
  printf ("resetting ATA-device 0\n%c",13);
  if (ata_reset())
  {
    printf ("Reset OK\n%c",13);
  }
  else
  {
    printf ("Reset failed!\n%c",13);
    while (1==1) {};
  }
  ata_identify();

}
 
