/*
 * hal_internal.h - x86-specific function definitions
 *
 * Copyright (c) 2017 Maxime Villard
 *
 * This file is part of ALMOS-MKH.
 *
 * ALMOS-MKH is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2.0 of the License.
 *
 * ALMOS-MKH is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ALMOS-MKH; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <memcpy.h>

#define offsetof(type, member) __builtin_offsetof(type, member)
#define roundup(x, y) ((((x)+((y)-1))/(y))*(y))
#define rounddown(x,y) (((x)/(y))*(y))

#define XASSERT(a)	\
	if (!(a)) { \
		x86_panic((char *)__func__); \
	}

/* hal_init.c */
void cpu_activate(uint32_t gid);
int idt_slot_alloc( void );
void idt_slot_free(int slot);

/* hal_cpu.S */
void invlpg(vaddr_t va);
void sti( void );
void cli( void );
uint64_t rdtsc( void );
uint8_t in8(uint32_t port);
uint16_t in16(uint32_t port);
void out8(uint32_t port, uint8_t val);
void out16(uint32_t port, uint16_t val);
uint64_t rdmsr(uint32_t);
void wrmsr(uint32_t, uint64_t);
void mfence( void );
uint64_t rcr0(void);
vaddr_t rcr2(void);
uint64_t rcr3(void);
void lcr3(uint64_t);
uint64_t rcr4(void);
void lcr4(uint64_t);
void cpuid(uint32_t eax, uint32_t ecx, uint32_t *desc);
void tlbflushg( void );
void tlbflush( void );
void clts( void );
void stts( void );
void pause( void );
void wbinvd( void );

void cpu_context_switch(void *oldctx, void *newctx);

uint32_t atomic_cas_32(volatile uint32_t *ptr, uint32_t exp, uint32_t new);
uint32_t atomic_add_32(volatile uint32_t *ptr, int32_t incr);
uint32_t atomic_and_32(volatile uint32_t *ptr, uint32_t mask);
uint32_t atomic_or_32(volatile uint32_t *ptr, uint32_t mask);

/* hal_gpt.c */
paddr_t hal_gpt_bootstrap_palloc(size_t npages);
vaddr_t hal_gpt_bootstrap_valloc(size_t npages);
void hal_gpt_bootstrap_reset( void );
size_t hal_gpt_bootstrap_uniformize( void );

void hal_gpt_enter(vaddr_t va, paddr_t pa, pt_entry_t flags);
void hal_gpt_enter_range(vaddr_t va, paddr_t pa, size_t n);
void hal_gpt_leave(vaddr_t va);
void hal_gpt_leave_range(vaddr_t va, size_t n);
void hal_gpt_maptree_area(vaddr_t va_start, vaddr_t va_end);
void hal_gpt_init(paddr_t firstpa);

/* hal_special.c */

/* x86_printf.c */
void x86_lock( void );
void x86_unlock( void );

void x86_panic(char *msg);
void x86_putc(char c);
void x86_printf(char *s, ...);

