/***
 ***  convenience routines for doing simple I/O with linux' /dev/port
 ***
 ***  note that you have to have uid=root or gid=kmem to open /dev/port
 *** written and copyright October 1994 by
 ***		Wim Lewis, wiml@{netcom,omnigroup}.com
 ***  distribute, modify, re-use freely!
 ***/
#ifdef __FreeBSD__
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#ifndef inb
#define inb(y) \
    ({ unsigned char _tmp__; \
    asm volatile("inb %1, %0" : "=a" (_tmp__) : "d" ((unsigned short)(y))); \
		_tmp__; })
#endif /* inb */
#ifndef outb
#define outb(x, y) \
    { asm volatile("outb %0, %1" : : "a" ((unsigned char)(y)) ,\
    "d" ((unsigned short)(x))); }
#endif
static int portio_fd= -1;

void close_io()
{
    close(portio_fd);
}

void open_io()
{
    portio_fd=open("/dev/io",O_RDWR);
    if (portio_fd <0 ) {
       perror("cannot open /dev/io");
       exit(errno);
    }
}

void out_byte(int port, unsigned char byte)
{
    outb(port,byte);
}

unsigned char in_byte(int port)
{
    return inb(port);
}
#endif
#ifndef __MSDOS__
/* assume LINUX */
#include "io_ports.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

int dev_port_fd = -1;

void open_io()
{
  dev_port_fd = open("/dev/port", O_RDWR);
  if(dev_port_fd < 0)
  {
    perror("/dev/port");
    exit(errno);
  }
}

void close_io()
{
  close(dev_port_fd);
  dev_port_fd = -1;
}

void out_byte(port, byte)
     int port;
     unsigned char byte;
{
  off_t s;
  int r;

  s = lseek(dev_port_fd, port, 0);
  if(s < 0)
    perror("lseek");
  else if(s != port)
    fprintf(stderr, "out_byte: seeking to %d, went to %ld.\n", port, (long)s);

  r = write(dev_port_fd, &byte, 1);
  if(r != 1)
  {
    fprintf(stderr, "out_byte: write returned %d\n", r);
    if(r < 0) perror("write");
  }
}

unsigned char in_byte(port)
     int port;
{
  off_t s;
  int r;
  unsigned char ch = 0;

  s = lseek(dev_port_fd, port, 0);
  if(s < 0)
    perror("lseek");
  else if(s != port)
    fprintf(stderr, "in_byte: seeking to %d, went to %ld.\n", port, (long)s);

  r = read(dev_port_fd, &ch, 1);
  if(r != 1)
  {
    fprintf(stderr, "in_byte: read returned %d\n", r);
    if(r < 0) perror("read");
  }

  return ch;
}
#else
/* MSDOS - turbo C */
#include <dos.h>
void close_io()
{
   return ; /* dummy - hardware always available to DOS */
}

void open_io()
{
   return ; /* dummy - hardware always available to DOS */
}

void out_byte(int port, unsigned char byte)
{
    outportb(port,byte);
}

unsigned char in_byte(int port)
{
    return inportb(port);
}


#endif
