/***************************************************************************
 * Copyright (C) 2006-2007 Richard C. Edelman II., All rights Reserved.    *
 *                                                                         *
 * The contents of this file are subject to the QuokOS Public License      *
 * ("QPL") Version 1.0, and You may not copy or use this file in either    *
 * source code or executable form, except in compliance with the terms and *
 * conditions of the QPL.                                                  *
 *                                                                         *
 * You may obtain a copy of the QPL (the "License") from the QuokOS        *
 * Website at http://quokos.quokworld.com.                                 *
 *                                                                         *
 * All software distributed under the Licenses is provided strictly on an  *
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, *
 * AND LICENSOR HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT    *
 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR *
 * PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. See the Licenses for     *
 * specific language governing rights and limitations under the Licenses.  *
 ***************************************************************************/

#include <asm/io.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <kernel/arch/i386/idt.h>
#include <kernel/mm/physical_mm.h>
#include <kernel/dev/disk/floppy/floppy.h>
#include <kernel/dma.h>
#include <kernel/fs/devfs/devfs.h>
#include <kernel/fs/vfs/vfs.h>

/* from pit.c */
extern void delay( unsigned long ms );

static void floppy_motor_cleanup( void );

floppy_drive_t * floppy_drive[4] = { NULL, NULL, NULL, NULL };

floppy_drive_geometry_t floppy_geometries[] =
{
	{  0, 0,  0,   0 }, /* No Floppy */
	{  9, 2, 40, 512 },	/* 360KB 5.25" */
	{ 15, 2, 80, 512 },	/* 1.2MB 5.25" */
	{  9, 2, 80, 512 },	/* 720KB 3.5" */
	{ 18, 2, 80, 512 },	/* 1.44MB 3.5" */
	{ 36, 2, 80, 512 }	/* 2.88MB 3.5" */
};

static unsigned char floppy_motor_state[4] = { FLOPPY_MOTOR_OFF, FLOPPY_MOTOR_OFF, FLOPPY_MOTOR_OFF, FLOPPY_MOTOR_OFF };

static volatile int floppy_waiting = TRUE;
static volatile int motor_ready = FALSE;

/* This mess probes for floppy controllers and attached drives. If anything is found, it attaches the device to DevFS.
One thing missing that would be nice is controller version information. */
int init_floppy_drive( void )
{
	unsigned char cmos_data, floppy_type[4];
	char floppy_name[4];
	char *drive_type_texts[6] = { "None", "360KB 5.25\"", "1.2MB 5.25\"", "720KB 3.5\"", "1.44MB 3.5\"", "2.88MB 3.5\"" };
	int floppy_num = 0, found_floppy = FALSE;;
	struct devfs_device *floppy_device[4] = { NULL, NULL, NULL, NULL };
	struct device_calltable *floppy_calltable = NULL;

	/* ask the BIOS if there is a floppy drive available */
	outb( 0x70, 0x10 );
	cmos_data = inb( 0x71 );

	/* get the first floppy drive */
	floppy_type[0] = cmos_data >> 4;
	/* and now the second */
	floppy_type[1] = cmos_data & 0xF;

	/* most BIOSes don't support more than 2 floppy drives even though the
	controller does, so set the last 2 drives to "None" */
	floppy_type[2] = 0;
	floppy_type[3] = 0;
	
	/* set up the device calltable */
	floppy_calltable = (struct device_calltable *)kmalloc( sizeof(struct device_calltable) );
	if ( floppy_calltable == NULL )
	{
		kprintf( "%s: Error allocating RAM for device calltable.\n", __FILE__ );
		return -ENOMEM;
	}
	
	floppy_calltable->open = floppy_open;
	floppy_calltable->close = floppy_close;
	floppy_calltable->read = floppy_read;
	floppy_calltable->write = floppy_write;
	floppy_calltable->seek = floppy_seek;
	floppy_calltable->clone = NULL;
	floppy_calltable->control = NULL;
	
	interrupt_add_handler( 38, floppy_service_routine );
	
	for ( floppy_num = 0; floppy_num < MAX_FLOPPIES; floppy_num++ )
	{
		if ( floppy_type[floppy_num] > 0 )
		{
			found_floppy = TRUE;
			
			ksprintf( floppy_name, "fd%d", floppy_num );

			/* allocate space for our floppy drive */
			floppy_drive[floppy_num] = (floppy_drive_t *)kmalloc( sizeof(floppy_drive_t) );
			if ( floppy_drive[floppy_num] == NULL )
			{
				kprintf( "WARNING: Unable to allocate RAM for %s -- drive will not be available.\n", floppy_name );
				continue;
			}

			memset( floppy_drive[floppy_num], 0x0, sizeof(floppy_drive_t) );

			/* set up the device */
			strncpy( floppy_drive[ floppy_num ]->name, floppy_name, strlen(floppy_name) );
			
			floppy_drive[ floppy_num ]->geometry = &floppy_geometries[ floppy_type[floppy_num] ];

			floppy_drive[ floppy_num ]->drive_num = floppy_num;

			if ( floppy_num == 0 || floppy_num == 1 )
				floppy_drive[ floppy_num ]->base = FLOPPY_PRIMARY_BASE;
			else if ( floppy_num == 2 || floppy_num == 3 )
				floppy_drive[ floppy_num ]->base = FLOPPY_SECONDARY_BASE;
				
			floppy_drive[ floppy_num ]->locked = FALSE;
			
			/* set up default parameters */
			floppy_drive[ floppy_num ]->params.timeout = FLOPPY_TIMEOUT;
			floppy_drive[ floppy_num ]->params.retries = FLOPPY_MAX_RETRIES;
			floppy_drive[ floppy_num ]->params.write_prot = FALSE;
			
			/* register the device's DevFS structure. This isn't right... 
			this is going based off floppy disks and not controllers :( 
			I'll fix that later though.*/
			if ( floppy_num == 0 || floppy_num == 2 )
			{
				floppy_device[floppy_num] = (struct devfs_device *)kmalloc( sizeof(struct devfs_device) );
				if ( floppy_device[floppy_num] == NULL )
				{
					kprintf( "fd%d: Devices on this controller are unavailable. Unable to allocate RAM for device struct.\n", floppy_num );
					continue;
				}

				floppy_device[ floppy_num ]->device_name = floppy_drive[ floppy_num ]->name;

				floppy_device[ floppy_num ]->type = DEV_BLOCK;
				floppy_device[ floppy_num ]->major = 0;
				floppy_device[ floppy_num ]->minor = 0;

				/* set up an I/O Calltable for this device */
				floppy_device[ floppy_num ]->calltable = floppy_calltable;

				/* register the device with DevFS */
				devfs_register_device( floppy_device[floppy_num] );
			}

			/* tell the user what type of drive we found. */
			kprintf( "fd%d: Detected %s floppy drive.\n", floppy_num, drive_type_texts[ floppy_type[floppy_num] ] );
		}
	}
	
	/* just in case BIOS says no floppy drives are installed, let's free the RAM from our device calltable */
	if ( found_floppy == FALSE )
		kfree( floppy_calltable );
		
	return ESUCCESS;
}

int floppy_service_routine( void )
{
	floppy_waiting = FALSE;

	return ESUCCESS;
}

void floppy_motor_on( floppy_drive_t *floppy )
{
	struct floppy_dor_s dor;

	/* if the motor for this drive is already running, just return */
	if ( floppy_motor_state[floppy->drive_num] == FLOPPY_MOTOR_ON )
		return;

	if ( floppy_motor_state[floppy->drive_num] == FLOPPY_MOTOR_WAITING )
	{
		/* set our motor state to running */
		floppy_motor_state[floppy->drive_num] = FLOPPY_MOTOR_ON;
		return;
	}
	
	/* set our motor state to running */
	floppy_motor_state[floppy->drive_num] = FLOPPY_MOTOR_ON;

	/* clear our register struct */
	dor.data = 0x0;

	dor.bits.drive = floppy->drive_num;

	/* set the bits for the floppy motors, so we don't accidentally turn off a
	motor that should be running.  Because FLOPPY_MOTOR_WAITING is also a valid 'on'
	state, we only set the motor enable bits to false if the cleanup thread
	has shut off the motor. */
	dor.bits.motor0 = (floppy_motor_state[0] == FLOPPY_MOTOR_OFF ? FALSE : TRUE);
	dor.bits.motor1 = (floppy_motor_state[1] == FLOPPY_MOTOR_OFF ? FALSE : TRUE);
	dor.bits.motor2 = (floppy_motor_state[2] == FLOPPY_MOTOR_OFF ? FALSE : TRUE);
	dor.bits.motor3 = (floppy_motor_state[3] == FLOPPY_MOTOR_OFF ? FALSE : TRUE);	
	
	dor.bits.reset = TRUE;
	dor.bits.dma = TRUE;

	outb( floppy->base + FLOPPY_REG_DOR, dor.data );

	/* delay for 500ms for the floppy motor to spin up. */
	delay( 500 );

}

void floppy_motor_off( floppy_drive_t *floppy )
{
	/* we simply set the floppy motor's status to
	waiting, and let the cleanup thread actually turn
	off the motor. */
	floppy_motor_state[floppy->drive_num] = FLOPPY_MOTOR_WAITING;
}

void floppy_motor_cleanup( void )
{
	struct floppy_dor_s dor;
	int ii;
	
	/* sleep for 500ms at a time */

	dor.data = 0x0;

	/* for any drives not set ON, disable the motors */
	dor.bits.motor0 = (floppy_motor_state[0] == FLOPPY_MOTOR_ON ? TRUE : FALSE);
	dor.bits.motor1 = (floppy_motor_state[1] == FLOPPY_MOTOR_ON ? TRUE : FALSE);
	dor.bits.motor2 = (floppy_motor_state[2] == FLOPPY_MOTOR_ON ? TRUE : FALSE);
	dor.bits.motor3 = (floppy_motor_state[3] == FLOPPY_MOTOR_ON ? TRUE : FALSE);
	
	dor.bits.reset = TRUE;
	dor.bits.dma = TRUE;

	/* repeat once for each drive */
	for ( ii = 0; ii < MAX_FLOPPIES; ii++ )
	{
		dor.bits.drive = ii;

		/* turn off the motor */
		outb( floppy_drive[ii]->base + FLOPPY_REG_DOR, dor.data );	

		/* for any motor that was WAITING, set it OFF now */
		if ( floppy_motor_state[ii] == FLOPPY_MOTOR_WAITING )
			floppy_motor_state[ii] = FLOPPY_MOTOR_OFF;

	}
}

int floppy_send_byte( floppy_drive_t * floppy, unsigned char byte )
{
	int timeout = floppy->params.timeout;
	struct floppy_msr_s msr;

	while ( timeout-- )
	{
		/* read MSR */
		msr.data = inb( floppy->base + FLOPPY_REG_MSR );

		/* make sure it's okay to send the byte */
		if ( msr.bits.rqm == 1 && msr.bits.dio == 0 )
		{
			outb( floppy->base + FLOPPY_REG_DATA, byte );
			return ESUCCESS;
		}
		
		/* delay 10ms before trying again. */
		delay( 10 );
	}

	/* timed out waiting for MSR to clear */
	kprintf( "%s: Timed out writing to floppy data port.\n", floppy->name );
	return -EIO;
}

int floppy_get_byte( floppy_drive_t * floppy, unsigned char *byte )
{
	int timeout = floppy->params.timeout;
	struct floppy_msr_s msr;

	while ( timeout-- )
	{
		/* read MSR */
		msr.data = inb( floppy->base + FLOPPY_REG_MSR );

		/* make sure it's okay to get the byte */
		if ( msr.bits.rqm == 1 && msr.bits.dio == 1 )
		{
			*byte = inb( floppy->base + FLOPPY_REG_DATA );
			return ESUCCESS;
		}
		
		/* delay 10ms before trying again */
		delay( 10 );
	}

	/* timed out waiting for MSR to clear */
	kprintf( "%s: Timed out reading from floppy data port.\n", floppy->name );
	return -EIO;
}


int floppy_wait_for_interrupt( floppy_drive_t * floppy, int issue_sis )
{
	int timeout = 100000;
	
	/* floppy_waiting is cleared by the floppy interrupt handler */
	while ( timeout-- )
	{
		if ( floppy_waiting == FALSE )
			break;
		
		/* delay 10ms before trying again */
		delay( 10 );
	}
	
	if ( timeout <= 0 )
		return -EIO;

	/* reset the flag */
	floppy_waiting = TRUE;

	if ( issue_sis == TRUE )
	{
		/* issue sense interrupt command */
		floppy_send_byte( floppy, FLOPPY_CMD_SENSE_INTERRUPT );

		/* Read status codes */
		floppy_get_byte( floppy, &floppy->st0.data );
		floppy_get_byte( floppy, &floppy->current_block );
	}
	
	return ESUCCESS;
}

/* Recalibrate the floppy drive, which sends the heads back to track 0.
Follows figure 8.4 of the Intel 82077AA Floppy Controller Datasheet. */
int floppy_recalibrate( floppy_drive_t * floppy )
{
	int retries = floppy->params.retries;

	/* make sure the motor is turned on */
	floppy_motor_on( floppy );
	
	while ( retries-- )
	{
		/* issue the recalibrate command */
		floppy_send_byte( floppy, FLOPPY_CMD_RECALIBRATE );
		floppy_send_byte( floppy, floppy->drive_num );

		/* if we timed out waiting, try recalibrating again */
		if ( floppy_wait_for_interrupt( floppy, TRUE ) != ESUCCESS )
			continue;

		if ( floppy->st0.bits.ic == 0x00 && floppy->st0.bits.se == 0x01 && 
			floppy->st0.bits.ha == 0x00 && floppy->current_block == 0 )
		{
//			floppy_motor_off( floppy );
			return ESUCCESS;
		}
	}

//	floppy_motor_off( floppy );

	kprintf( "%s: Gave up recalibrating drive after %d retries.\n", floppy->name, floppy->params.retries );
	return -EIO;
}

/* Reset the floppy controller according to Figure 8.3
of the Intel 82077AA Floppy Controller Datasheet. */
int floppy_reset( floppy_drive_t * floppy )
{
	int ii, retval;
	struct floppy_dor_s dor;

	/* disable the controller */
	dor.data = 0x0;
	outb( floppy->base + FLOPPY_REG_DOR, dor.data );

	/* enable the controller */
	dor.bits.dma = TRUE;
	dor.bits.reset = TRUE;
	outb( floppy->base + FLOPPY_REG_DOR, dor.data );

	/* write 0x00 to the config control register -- 
	this sets the transfer rate to 500Kbps */
	outb( floppy->base + FLOPPY_REG_CCR, 0x00 );
	
	/* wait for floppy interrupt. We really shouldn't timeout here,
	it should be almost instantaneous. Anyway, who cares if we do
	timeout. :) */
	floppy_wait_for_interrupt( floppy, FALSE );
	
	/* loop 4 times. floppy_wait_for_interrupt does not do this as per the FALSE above */
	for ( ii = 0; ii < 4; ii++ )
	{
		/* issue the 'sense interrupt' command. */
		floppy_send_byte( floppy, FLOPPY_CMD_SENSE_INTERRUPT );

		/* read the ST0 register */
		floppy_get_byte( floppy, &floppy->st0.data );

		/* get the current block number */
		floppy_get_byte( floppy, &floppy->current_block );
	}

	/* configure the drive -- we accept the defaults here:
	   EIS - No Implied Seeks
	   EFIFO - FIFO Disabled (use DMA for transfers)
	   POLL - Polling Enabled
	   FIFOTHR - FIFO Threshold of 16 bytes
	   PRETRK - Precompensation Track of 0 
	*/
	
	/* specify drive parameters */
	floppy_send_byte( floppy, FLOPPY_CMD_SPECIFY );
    floppy_send_byte( floppy, 0xDF ); /* steprate = 3ms, unload time = 240ms */
    floppy_send_byte( floppy, 0x02 ); /* load time = 16ms, no-DMA = 0 */

	/* Finally, recalibrate the drive so we get a known state */
	retval = floppy_recalibrate( floppy );
	
	if ( retval == ESUCCESS )
		return retval;

	errno = -retval;
	return EFAILURE;
}

int floppy_seek_cylinder( floppy_drive_t *floppy, int block )
{
	if ( floppy->current_block == block )
		return ESUCCESS;

//	floppy_motor_on( floppy );

	/* send seek command */
	floppy_send_byte( floppy, FLOPPY_CMD_SEEK );

	/* specify drive */
	floppy_send_byte( floppy, floppy->drive_num );

	/* specify block */
	floppy_send_byte( floppy, block );

	/* wait for interrupt */
	floppy_wait_for_interrupt( floppy, TRUE );

//	floppy_motor_off( floppy );

	/* make sure we're on the right cylinder */
	if ( floppy->st0.bits.ic == 0x00 && floppy->st0.bits.se == 0x01 
		 && floppy->st0.bits.ha == 0x00 && floppy->current_block == block )
		return ESUCCESS;

	kprintf( "%s: Error seeking to cylinder %d after %d retries.\n", floppy->name, block, floppy->params.retries );
	return -EIO;
}

void floppy_block_geometry( floppy_drive_t *floppy, int block, floppy_drive_geometry_t *geometry )
{
	int temp = block % ( floppy->geometry->heads * floppy->geometry->sectors );
	
	/* Locate the correct cylinder */
	geometry->cylinders = block / ( floppy->geometry->sectors * floppy->geometry->heads );

	/* Locate the correct head */
	geometry->heads = temp / floppy->geometry->sectors;

	/* Locate the correct sector */
	geometry->sectors = temp % floppy->geometry->sectors + 1;
}

int floppy_read_write_block( floppy_drive_t *floppy, void *buffer, int mode )
{
	int seek_retries;
	int cmd_retries;
	floppy_drive_geometry_t block_geometry;
	void *dma_buffer;
	unsigned char throw_away;
	struct floppy_st1_s st1;
	struct floppy_st2_s st2;

	/* Allocate the buffer we'll use for this DMA transfer */
	dma_buffer = phys_alloc_page_low();

	if ( dma_buffer == NULL )
		return -ENOMEM;

	/* if this is a floppy write, copy from our buffer to our dma buffer */
	if ( mode == FLOPPY_WRITE )
		memcpy( dma_buffer, buffer, floppy->geometry->blocksize );

	/* get the proper geometry for the block we are at */
	floppy_block_geometry( floppy, floppy->current_block, &block_geometry );

	for ( seek_retries = floppy->params.retries; seek_retries > 0; seek_retries-- )
	{
		/* seek to the correct location. */
		if ( floppy_seek_cylinder( floppy, block_geometry.cylinders ) != ESUCCESS )
		{
			/* recalibrate the drive before attempting to seek again */
			floppy_recalibrate( floppy );
			continue;
		}

		/* delay to allow the heads to settle */
		delay( 30 ); /* controller datasheets say 15ms, so we'll double it to be safe */

		/* TODO: issue a read id command here to make sure we are indeed on the correct cylinder. Error out if we are not. */	

		/* attempt to issue the command. If this does not return successfully, we'll retry a couple of times.
		If after retrying a few times, we'll attempt to recalibrate the drive and seek again, then try this whole
		thing again */
		for ( cmd_retries = floppy->params.retries; cmd_retries > 0; cmd_retries-- )
		{
			/* initialize the DMA controller */
			if ( mode == FLOPPY_READ )
			{
				/* program the DMA for read (perform a dma write) */
				dma_write( FLOPPY_DMA_CHANNEL, dma_buffer, floppy->geometry->blocksize );

				floppy_send_byte( floppy, FLOPPY_CMD_READ_DATA );
			}
			else if ( mode == FLOPPY_WRITE )
			{
				/* program the DMA for write. (perform a dma read) */
				dma_read( FLOPPY_DMA_CHANNEL, dma_buffer, floppy->geometry->blocksize );

				floppy_send_byte( floppy, FLOPPY_CMD_WRITE_DATA );
			}

			/* now tell the controller what drive, head, cylinder, sector etc.
			TODO: get rid of these magic numbers in here */
	   		floppy_send_byte( floppy, (block_geometry.heads << 2) | floppy->drive_num );
    		floppy_send_byte( floppy, block_geometry.cylinders );
			floppy_send_byte( floppy, block_geometry.heads );
			floppy_send_byte( floppy, block_geometry.sectors );
			floppy_send_byte( floppy, 2 ); /* 512 byte size sectors */
			floppy_send_byte( floppy, floppy->geometry->sectors );
			floppy_send_byte( floppy, 0x1B ); /* GAP3 Length - 27 decimal - standard for 3.5" floppies */
			floppy_send_byte( floppy, 0xFF );


			/* wait for an interrupt from the floppy drive */
			floppy_wait_for_interrupt( floppy, FALSE );
		
			/* read the result phase of the command */
			/* TODO: NEED TO IMPROVE ERROR HANDLING HERE! */
			floppy_get_byte( floppy, &floppy->st0.data ); 	/* STO */
			floppy_get_byte( floppy, &st1.data );			/* ST1 */
			floppy_get_byte( floppy, &st2.data );			/* ST2 */
			floppy_get_byte( floppy, &throw_away );			/* cylinder */
			floppy_get_byte( floppy, &throw_away );			/* head */
			floppy_get_byte( floppy, &throw_away );			/* sector number */
			floppy_get_byte( floppy, &throw_away );			/* sector size */

			/* check the interrupt code in st0 */
			if ( floppy->st0.bits.ic == FLOPPY_CMD_SUCCESS )
			{
				/* if this was a read, copy from the dma buffer to our buffer */
				if ( mode == FLOPPY_READ )
					memcpy( buffer, dma_buffer, floppy->geometry->blocksize );
			
				/* free our dma buffer */
				phys_page_free( dma_buffer );
				return ESUCCESS;
			}
		
		}  /* end command retry loop */

		/* recalibrate the floppy drive before attempting to seek again */
		floppy_recalibrate( floppy );

	} /* end seek retry loop */

	/* free our dma buffer */
	phys_page_free( dma_buffer );

	kprintf( "%s: %s of block %d failed.\n", floppy->name, mode == FLOPPY_READ ? "Read" : "Write", floppy->current_block );
	return -EIO;
}

int floppy_read_write( struct device_handle *handle, char *buffer, unsigned int size, int mode )
{
	unsigned int bytes_rw = 0, block_num = 0, wrote = 1, total_blocks;
	floppy_drive_t * floppy = (floppy_drive_t *)handle->data_ptr;
	int retval = 0;

	/* we can only write block aligned buffers of data */
	if ( size < floppy->geometry->blocksize || size % floppy->geometry->blocksize != 0 )
	{
		errno = EIO;
		return EFAILURE;
	}

	/* calculate how many blocks we need to read or write */
	total_blocks = size / floppy->geometry->blocksize;
	
	floppy_motor_on( floppy );

	/* write 0x00 to the config control register -- 
	this sets the transfer rate to 500Kbps */
	outb( floppy->base + FLOPPY_REG_CCR, 0x00 );

	/* while we still have blocks to read or write, loop... */
	while( block_num++ < total_blocks )
	{
		/* try to read or write the next block */
		retval = floppy_read_write_block( floppy, buffer, mode );
		if( retval != ESUCCESS )
			break;

		/* update the buffer pointer */
		buffer += floppy->geometry->blocksize;

		/* update the total amount of bytes read or written */
		bytes_rw += floppy->geometry->blocksize;

		/* increment the current block for the next read or write */
		floppy->current_block++;
	}

	floppy_motor_off( floppy );

	/* This is a temp call until we get the cleanup function running as its own thread */
	floppy_motor_cleanup();
	
	/* return the total bytes read or written */
	return bytes_rw;
}

int floppy_open( struct device_handle *handle, char *filename )
{
	int ii;
	
	for ( ii = 0; ii < MAX_FLOPPIES; ii++ )
	{
		if ( strncmp( filename, floppy_drive[ii]->name, strlen(filename) ) == ESUCCESS )
		{
			handle->data_ptr = (void *)floppy_drive[ii];
			handle->data_arg = NULL;
				
			/* if the drive is locked (in use), don't allow 
			another process to open it */
			if ( floppy_drive[ii]->locked == TRUE )
				return -EAGAIN;
				
			/* lock the drive so another process can't open it later */
			floppy_drive[ii]->locked = TRUE;

			/* reset the floppy to a known state */
			floppy_reset( floppy_drive[ii] );

			return ESUCCESS;
		}
	}
	
	return -ENXIO;
}

int floppy_close( struct device_handle *handle )
{
	floppy_drive_t *floppy = (floppy_drive_t *)handle->data_ptr;
	
	/* if the floppy isn't locked, it's not in use, so return error */
	if ( floppy->locked == FALSE )
		return -EIO; /* should probably return something other than EIO */

	/* unlock the floppy drive */
	floppy->locked = FALSE;
	
	/* shut off the motor */
//	floppy_motor_off( floppy );

	/* reset the current_block to 0 */
	floppy->current_block = 0;
		
	return ESUCCESS;
}

int floppy_read( struct device_handle *handle, char *buffer, unsigned int bytes )
{
	return floppy_read_write( handle, buffer, bytes, FLOPPY_READ );
}

int floppy_write( struct device_handle *handle, char *buffer, unsigned int bytes )
{
	return floppy_read_write( handle, buffer, bytes, FLOPPY_WRITE );
}

int floppy_seek( struct device_handle *handle, unsigned int offset, char origin )
{
	floppy_drive_t * floppy = (floppy_drive_t *)handle->data_ptr;

	/* calculate the current block from the offset */
	if( origin == VFS_SEEK_START )
		floppy->current_block = ( offset / floppy->geometry->blocksize );
	else if( origin == VFS_SEEK_CURRENT )
		floppy->current_block += ( offset / floppy->geometry->blocksize );
	else if( origin == VFS_SEEK_END )
		floppy->current_block = FLOPPY_TOTAL_BLOCKS - ( offset / floppy->geometry->blocksize );
	else
	{
		errno = EINVAL;
		return EFAILURE;
	}

	/* return the current offset to the caller */
	return ESUCCESS;	
}
