#include <stdint.h>

uint8_t io_in8(uint16_t port) {
  uint8_t r;
  asm volatile("inb %1, %0" : "=a"(r) : "dN"(port));
  return r;
}
void io_out8(uint16_t port, uint8_t value) {
  asm volatile("outb %1, %0" :: "dN"(port), "a"(value));
}

uint16_t io_in16(uint16_t port) {
  uint16_t r;
  asm volatile("in %%dx, %%ax" : "=a"(r) : "d"(port));
  return r;
}
void io_out16(uint16_t port, uint16_t value) {
  asm volatile("out %%ax, %%dx" :: "a"(value), "d"(port));
}

uint32_t io_in32(uint16_t port) {
  uint32_t r;
  asm volatile("inl %%dx, %%eax" : "=a"(r) : "d"(port));
  return r;
}
void io_out32(uint16_t port, uint32_t value) {
  asm volatile("outl %%eax, %%dx" :: "d"(port), "a"(value));
}

void io_ins16(uint16_t port, void *addr, int cnt) {
  asm volatile(
    "cld; rep insw"
    : "+D"(addr), "+c"(cnt)
    : "d"(port)
    : "memory", "cc"
  );
}

void io_outs16(uint16_t port, const void *addr, int cnt) {
  asm volatile(
    "cld; rep outsw"
    : "+S"(addr), "+c"(cnt)
    : "d"(port)
    : "memory", "cc"
  );
}
