#include <amd64/io.h>
#include <libk/std.h>

/// Perform outb instruction (send 8-bit int)
void outb (uint16_t port, uint8_t v) { __asm__ volatile ("outb %1, %0" ::"dN"(port), "a"(v)); }

/// Perform outw instruction (send 16-bit int)
void outw (uint16_t port, uint16_t v) { __asm__ volatile ("outw %%ax, %%dx" ::"a"(v), "d"(port)); }

/// Perform outl instruction (send 32-bit int)
void outl (uint16_t port, uint32_t v) { __asm__ volatile ("outl %%eax, %%dx" ::"d"(port), "a"(v)); }

/// Perform outsw instruction (send a string)
void outsw (uint16_t port, const void* addr, int cnt) {
  __asm__ volatile ("cld; rep outsw" : "+S"(addr), "+c"(cnt) : "d"(port) : "memory", "cc");
}

/// Perform inb instruction (receive 8-bit int)
uint8_t inb (uint16_t port) {
  uint8_t r;
  __asm__ volatile ("inb %1, %0" : "=a"(r) : "dN"(port));
  return r;
}

/// Perform inw instruction (receive 16-bit int)
uint16_t inw (uint16_t port) {
  uint16_t r;
  __asm__ volatile ("inw %%dx, %%ax" : "=a"(r) : "d"(port));
  return r;
}

/// Perform inl instruction (receive 32-bit int)
uint32_t inl (uint16_t port) {
  uint32_t r;
  __asm__ volatile ("inl %%dx, %%eax" : "=a"(r) : "d"(port));
  return r;
}

/// Perform insw instruction (receive a string)
void insw (uint16_t port, void* addr, int cnt) {
  __asm__ volatile ("cld; rep insw" : "+D"(addr), "+c"(cnt) : "d"(port) : "memory", "cc");
}

/// output a byte on port 0x80, which does a small IO delay
void io_wait (void) { outb (0x80, 0); }
