/**************************************************************************************
 Copyright (c) 2002
      The UbixOS Project

 $Id: dma.c,v 1.5 2002/04/26 22:52:42 reddawg Exp $
**************************************************************************************/

#include <ubixos/io.h>
#include <ubixos/dma.h>

typedef unsigned char   uchar;
typedef unsigned int    uint;

#define LOW_BYTE(x)         (x & 0x00FF)
#define HI_BYTE(x)          ((x & 0xFF00) >> 8)

uchar MaskReg[8]   = { 0x0A, 0x0A, 0x0A, 0x0A, 0xD4, 0xD4, 0xD4, 0xD4 };
uchar ModeReg[8]   = { 0x0B, 0x0B, 0x0B, 0x0B, 0xD6, 0xD6, 0xD6, 0xD6 };
uchar ClearReg[8]  = { 0x0C, 0x0C, 0x0C, 0x0C, 0xD8, 0xD8, 0xD8, 0xD8 };

uchar PagePort[8]  = { 0x87, 0x83, 0x81, 0x82, 0x8F, 0x8B, 0x89, 0x8A };
uchar AddrPort[8]  = { 0x00, 0x02, 0x04, 0x06, 0xC0, 0xC4, 0xC8, 0xCC };
uchar CountPort[8] = { 0x01, 0x03, 0x05, 0x07, 0xC2, 0xC6, 0xCA, 0xCE };

void _dma_xfer(uchar DMA_channel, unsigned char page, unsigned int offset, unsigned int length, uchar mode);

void dma_xfer(uchar channel, unsigned long address, unsigned int length, unsigned char read) {
  unsigned char page=0, mode=0;
  unsigned int offset = 0;
  if (read) {
    mode = 0x48 + channel;
    }
  else {
    mode = 0x44 + channel;
    }
  page = address >> 16;
  offset = address & 0xFFFF;
  length--;
  _dma_xfer(channel, page, offset, length, mode);	
  }	
		

void _dma_xfer(uchar DMA_channel, unsigned char page, unsigned int offset, unsigned int length, uchar mode) {
  asm("cli");
  outportb(MaskReg[DMA_channel], 0x04 | DMA_channel);
  outportb(ClearReg[DMA_channel], 0x00);
  outportb(ModeReg[DMA_channel], mode);
  outportb(AddrPort[DMA_channel], LOW_BYTE(offset));
  outportb(AddrPort[DMA_channel], HI_BYTE(offset));
  outportb(PagePort[DMA_channel], page);
  outportb(CountPort[DMA_channel], LOW_BYTE(length));
  outportb(CountPort[DMA_channel], HI_BYTE(length));
  outportb(MaskReg[DMA_channel], DMA_channel);
  asm("sti");
  }
