// I/O ports wrapper definitions and prototypes
// This file might need tweaking if you're trying to port my code to other
// x86 Unix platforms.  Code is already available for Linux, FreeBSD, and 
// QNX; see the Makefile.
//
// Original Linux code by: Patrick Reynolds <patrickr@virginia.edu>
// QNX code by: Anders Arpteg <aa11ac@hik.se>
// FreeBSD code by: Patrick Reynolds <patrickr@virginia.edu> and Charles 
//                  Henrich <henrich@msu.edu>
// Inlining implemented by: Philip Blundell <philip.blundell@pobox.com>

#ifndef PORT_H
#define PORT_H

#include <unistd.h>
#include "config.h"

#ifdef LINUX
#include <asm/io.h>
#elif defined(QNX)
#include <conio.h>
#elif defined(FREEBSD)
#include <machine/cpufunc.h>
#include <stdio.h>
#elif defined(BSDI)
#include <machine/inline.h>
#elif defined(LYNX)
#include "lynx-io.h"
#else
#error Please define a platform in the Makefile
#endif

class port_t {
public:
  port_t(int iport);
  ~port_t(void);

  inline int read_data(void) { return inb(port); }
  inline int read_status(void) { return inb(port+1); }
  inline int read_control(void) { return inb(port+2); }

#if defined(LINUX) || defined(LYNX)
  inline void write_data(int data) { outb(data, port); }
  inline void write_control(int data) { outb(control_reg = data, port2); }
  inline void setbit_control(int data) { outb(control_reg |= data, port2); }
  inline void clearbit_control(int data) { outb(control_reg &= ~data, port2); }
#else // QNX and *BSD use (port, data) instead
  inline void write_data(int data) { outb(port, data); }
  inline void write_control(int data) { outb(port2, control_reg = data); }
  inline void setbit_control(int data) { outb(port2, control_reg |= data); }
  inline void clearbit_control(int data) { outb(port2, control_reg &= ~data); }
#endif

  inline int get_port() { return port; }
  inline operator bool () const { return port != -1; }

private:
  int port;        // number of the base port
  int port1;       // port+1, precalculated for speed
  int port2;       // port+2, precalculated for speed
  int control_reg; // current contents of the control register
#ifdef LOCKING
  int lock_fd;
  int lock(int portnum);
  void unlock(int portnum);
#endif

#ifdef FREEBSD
  FILE *devio;
#endif
};

#endif
