// SPDX-License-Identifier: MPL-2.0
#ifndef SH_LIB_ASM_H
#define SH_LIB_ASM_H
#include "std/type.h"
#include "std/status.h"
#include "irq/gdt.h"
#include "irq/tss.h"
#include "irq/idt.h"
// inb instruction wrapper
inline sh_uint8 sh_asm_inb(sh_uint16 port) {
  sh_uint8 val;
  __asm__ volatile ("inb %1, %0":"=a"(val):"Nd"(port));
  return val;
}
// outb instruction wrapper
inline void sh_asm_outb(sh_uint16 port,sh_uint8 val) {
  __asm__ volatile ("outb %0, %1"::"a"(val),"Nd"(port));
}
// rdtsc instruction wrapper
static inline sh_uint64 sh_asm_rdtsc() {
  sh_uint32 lo,hi;
  __asm__ volatile ("rdtsc":"=a"(lo),"=d"(hi));
  return ((sh_uint64)hi<<32)|lo;
}
// invlpg instruction wrapper
static inline void sh_asm_invlpg(void *addr) {
  __asm__ volatile ("invlpg (%0)"::"r"(addr):"memory");
}
// lgdt instruction wrapper
static inline void sh_asm_lgdt(sh_gdt_GDTR gdtr) {
  __asm__ volatile ("lgdt %0"::"m"(gdtr):"memory");
}
// ltr instruction wrapper
static inline void sh_asm_ltr(sh_uint16 tss_selector) {
  __asm__ volatile ("ltr %0"::"r"(tss_selector):"memory");
}
// lidt instruction wrapper
static inline void sh_asm_lidt(sh_idt_IDTR idtr) {
  __asm__ volatile ("lidt %0"::"m"(idtr):"memory");
}
// sidt instruction wrapper
static inline void sh_asm_sidt(sh_idt_IDTR* idtr) {
  __asm__ volatile ("sidt %0":"=m"(*idtr)::"memory");
}
// sti instruction wrapper
static inline void sh_asm_sti() {
  __asm__ volatile ("sti");
}
// cli instruction wrapper
static inline void sh_asm_cli() {
  __asm__ volatile ("cli");
}
// cpuid instruction wrapper
static inline void sh_asm_cpuid(sh_uint32 leaf,sh_uint32 subleaf,sh_uint32 *eax,sh_uint32 *ebx,sh_uint32 *ecx,sh_uint32 *edx){
  __asm__ volatile ("cpuid":"=a"(*eax),"=b"(*ebx),"=c"(*ecx),"=d"(*edx):"a"(leaf),"c"(subleaf));
}
// mfence instruction wrapper
inline void sh_asm_mfence() {
  __asm__ volatile("mfence":::"memory");
}
// lfence instruction wrapper
inline void sh_asm_lfence() {
  __asm__ volatile("lfence":::"memory");
}
// sfence instruction wrapper
inline void sh_asm_sfence() {
  __asm__ volatile("sfence":::"memory");
}
#endif
