#include "fdc.h"

int motor_status=0;	//off
volatile int floppy_flag=0;

#define FDC_DOR		0x3f2
#define FDC_MSR		0x3f4
#define FDC_DRS		0x3f4
#define FDC_DATA	0x3f5
#define FDC_DIR		0x3f7
#define FDC_CCR		0x3f7

/* commands */

#define CMD_SPECIFY	0x03
#define CMD_WRITE	0x45
#define CMD_READ	0x46 //0xe6
#define CMD_RECAL	0x07
#define CMD_SENSEI	0x08
#define CMD_SEEK	0x0f

typedef enum
{
 floppy_dir_read = 1,
 floppy_dir_write = 2
}floppy_dir;

void sendbyte(byte data)
{
 volatile byte msr;
 int tmo;
 for(tmo=0;tmo<128;tmo++)
  {
   msr=inportb(FDC_MSR);
   if((msr & 0xc0)==0x80)
     {
       outportb(FDC_DATA,data);
       return;
     }
    delay(100);
  }
 printf("send byte time out\n");
}

byte getbyte()
{
 volatile byte msr;
 int tmo;
 for(tmo=0;tmo<128;tmo++)
  {
   msr=inportb(FDC_MSR);
   if((msr & 0xd0)==0xd0)
     return inportb(FDC_DATA);
   delay(100);
  }
 printf("getbyte time out\n");
}

void motor(int onoff)
{
 if(onoff==1)
  {
    outportb(FDC_DOR,0x1c);
    delay(300);
    motor_status=1;
  }
 else if(onoff==0)
  {
   outportb(FDC_DOR,0x0c);
   //delay(500);
   motor_status=0;
  }
}

void fdc_handler(struct regs *r)
{
 floppy_flag=1;
 return;
}

void check_int(byte *st0,byte *cyl)
{
 sendbyte(CMD_SENSEI);
 *st0=getbyte();
 *cyl=getbyte();
}

void wait()
{
 while(floppy_flag==0);
 floppy_flag=0;
 return;
}

void reset() 
{
 byte st0,cyl;int i;
 outportb(FDC_DOR,0); //motor off/no dma
 
 outportb(FDC_DOR,0x0c);	//enable
   
   wait();

 for(i=0;i<4;i++)
   check_int(&st0,&cyl);

 outportb(FDC_CCR,0);	//set transfer speed 

 sendbyte(CMD_SPECIFY);
 sendbyte(0xdf);
 sendbyte(0x02);
  
}

void recalibrate()
{
 int i;byte st0,cyl=-1;
 motor(1); //turn motor on
 for(i=0;i<10;i++)
  {
   sendbyte(CMD_RECAL);
   sendbyte(0);
   wait();
   check_int(&st0,&cyl);
   //if(st0 & 0xc0)
     //printf("errorr calbirate\n");
   if(!cyl)
    {
      motor(0);
      return;
    }
  }
 printf("calbirate error\n");
 motor(0);
}

void init_floppy()
{
 printf("init floppy ...");
 irq_install_handler(6,fdc_handler);
 reset();
 recalibrate();
 printf("[Done]\n");
}

void seek(byte head,byte track)
{
 int i;byte st0,cyl=-1;
 motor(1); //turn motor on

  for(i=0;i<10;i++)
   {
    sendbyte(CMD_SEEK);
    sendbyte(head << 2);
    sendbyte(track);
   
    wait();
    check_int(&st0,&cyl);
  
    //if(st0 & 0xC0)
     //printf("error seek command");
    if(cyl==track)	
     {
      //okay seek
      motor(0);
      return;
     }
    }
 motor(0);
 printf("error seek command");
}

void dma_init(floppy_dir dir)
{
 union
  {
   byte b[4];
   unsigned long l;
  }a,c;
 a.l=(unsigned) &floppy_dmabuf;
 c.l=(unsigned) floppy_dmalen - 1;

 if((a.l >> 24) || (c.l >> 16) || (((a.l&0xffff)+c.l)>>16)) 
     printf("floppy_dma_init: static buffer problem\n"); 
 
 unsigned char mode;
 switch(dir)
  {
   case floppy_dir_read:mode=0x46;break;
   case floppy_dir_write:mode=0x4a;break;
  }
 outportb(0x0a, 0x06);   // mask chan 2 

 outportb(0x0c, 0xff);   // reset flip-flop 
 outportb(0x04, a.b[0]); //  - address low byte 
 outportb(0x04, a.b[1]); //  - address high byte 

 outportb(0x81, a.b[2]); // external page register 

 outportb(0x0c, 0xff);   // reset flip-flop 
 outportb(0x05, c.b[0]); //  - count low byte 
 outportb(0x05, c.b[1]); //  - count high byte 

 outportb(0x0b, mode);   // set mode 

 outportb(0x0a, 0x02);   // unmask chan 2 

}

void do_track(byte head,byte trk,byte sector,floppy_dir dir)
{
 int i;
 byte cmd;byte head_drive=0;
 static const int flags = 0xC0;
 switch(dir)
  {
   case floppy_dir_read:
    cmd=CMD_READ;break;
   case floppy_dir_write:
    cmd=CMD_WRITE;break;	
  }
 //seek both heads
 seek(head,trk);delay(500);
 for(i=0;i<10;i++)
  {
   motor(1);	//turn motor 0n
   dma_init(dir);
   //delay(2000);
   sendbyte(cmd);  // set above for current direction 
   if(head>0)
     head_drive=4;
   sendbyte(head_drive);    // 0:0:0:0:0:HD:US1:US0 = head and drive 
   sendbyte(trk);  // cylinder 
   sendbyte(head);    // first head (should match with above) 
   sendbyte(sector);    // first sector, strangely counts from 1 
   sendbyte(2);    // bytes/sector, 128*2^x (x=2 -> 512) 
   sendbyte(18);   // number of tracks to operate on 
   sendbyte(0x1b); // GAP3 length, 27 is default for 3.5" 
   sendbyte(0xff); // data length (0xff if B/S != 0) 
   wait();
   byte st0, st1, st2, rcy, rhe, rse, bps;
   int error = 0;
   st0=getbyte();
   st1=getbyte();
   st2=getbyte();
   rcy=getbyte();
   rhe=getbyte();
   rse=getbyte();
   bps=getbyte();
   if(st0 & 0xC0) { 
            static const char * status[] = 
            { 0, "error", "invalid command", "drive not ready" }; 
            printf("floppy_do_sector: status = %s\n", status[st0 >> 6]); 
            error = 1; 
        } 
        if(st1 & 0x80) { 
            printf("floppy_do_sector: end of cylinder\n"); 
            error = 1; 
        } 
        if(st0 & 0x08) { 
            printf("floppy_do_sector: drive not ready\n"); 
            error = 1; 
        } 
        if(st1 & 0x20) { 
            printf("floppy_do_sector: CRC error\n"); 
            error = 1; 
        } 
        if(st1 & 0x10) { 
            printf("floppy_do_sector: controller timeout\n"); 
            error = 1; 
        } 
        if(st1 & 0x04) { 
            printf("floppy_do_sector: no data found\n"); 
            error = 1; 
        } 
        if((st1|st2) & 0x01) { 
            printf("floppy_do_sector: no address mark found\n"); 
            error = 1; 
        } 
        if(st2 & 0x40) { 
            printf("floppy_do_sector: deleted address mark\n"); 
            error = 1; 
        } 
        if(st2 & 0x20) { 
            printf("floppy_do_sector: CRC error in data\n"); 
            error = 1; 
        } 
        if(st2 & 0x10) { 
            printf("floppy_do_sector: wrong cylinder\n"); 
            error = 1; 
        } 
        if(st2 & 0x04) { 
            printf("floppy_do_sector: uPD765 sector not found\n"); 
            error = 1; 
        } 
        if(st2 & 0x02) { 
            printf("floppy_do_sector: bad cylinder\n"); 
            error = 1; 
        } 
        if(bps != 0x2) { 
            printf("floppy_do_sector: wanted 512B/sector, got %d", (1<<(bps+7))); 
            error = 1; 
        } 
        if(st1 & 0x02) { 
            printf("floppy_do_sector: not writable\n"); 
            error = 2; 
        } 

        if(!error) { 
            motor(0); 
            return ; 
        } 
        if(error > 1) { 
            //printf("floppy_do_sector: not retrying..\n"); 
            motor(0); 
            return ; 
        } 

  }
 //motor(0);
 //printf("ok\n");
}

void f_read(byte head,byte trk,byte sector)
{
 
 recalibrate();
 do_track(head,trk,sector,floppy_dir_read);
 reset();
 
}

void f_write(byte head,byte trk,byte sector)
{
 
 recalibrate();
 do_track(head,trk,sector,floppy_dir_write);
 reset();
 
}

int chs_to_lba(byte head,byte track,byte sector)
{
 int lba;
 lba=((18 * 2 * track) + (18 * head) + sector ) -1 ;
 return lba;
}

void lba_to_chs(unsigned int lba)
{
 unsigned int track =( (lba /18 )/ 2) ;
 unsigned int head  = (lba / 18) % 2;
 unsigned int sector= (lba % 18) + 1;
 printf("LBA is %d\n",lba);
 printf("the head is %d\n",head);
 printf("the track is %d\n",track);
 printf("the sector is %d\n",sector);
}

void floppy_read(unsigned int lba)
{
 unsigned int track =( (lba /18 )/ 2) ;
 unsigned int head  = (lba / 18) % 2;
 unsigned int sector= (lba % 18) + 1;
 recalibrate();
 //delay(500);
 f_read(head,track,sector);
 //delay(500);
}

void floppy_write(unsigned int lba)
{
 unsigned int track =( (lba /18 )/ 2) ;
 unsigned int head  = (lba / 18) % 2;
 unsigned int sector= (lba % 18) + 1;
 recalibrate();
 //delay(500);
 f_write(head,track,sector);
 //delay(500);
}







































