/*
 * hal_exception.c - Implementation of exception handler for x86_64
 *
 * 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 <hal_types.h>
#include <hal_irqmask.h>
#include <hal_exception.h>
#include <thread.h>
#include <errno.h>
#include <core.h>
#include <do_exception.h>

#include <hal_kentry.h>
#include <hal_internal.h>
#include <hal_segmentation.h>

static const char *exc_type[] = {
	[T_PRIVINFLT]= "privileged instruction fault",
	[T_BPTFLT] = "breakpoint trap",
	[T_ARITHTRAP] = "arithmetic trap",
	[T_ASTFLT] = "asynchronous system trap",
	[T_PROTFLT] = "protection fault",
	[T_TRCTRAP] = "trace trap",
	[T_PAGEFLT] = "page fault",
	[T_ALIGNFLT] = "alignment fault",
	[T_DIVIDE] = "integer divide fault",
	[T_NMI] = "non-maskable interrupt",
	[T_OFLOW] = "overflow trap",
	[T_BOUND] = "bounds check fault",
	[T_DNA] = "FPU not available fault",
	[T_DOUBLEFLT] = "double fault",
	[T_FPOPFLT] = "FPU operand fetch fault",
	[T_TSSFLT] = "invalid TSS fault",
	[T_SEGNPFLT] = "segment not present fault",
	[T_STKFLT] = "stack fault",
	[T_MCA] = "machine check fault",
	[T_XMM] = "SSE FP exception",
};
int	exc_types = __arraycount(exc_type);

/*
 * Hexception handler.
 */
void hal_exception_entry(hal_cpu_context_t *ctx)
{
	uint64_t excno = ctx->tf_trapno;
	const char *buf;

	if (excno < exc_types) {
		buf = exc_type[excno];
	} else {
		buf = "unknown exception";
	}

	x86_lock();
	x86_printf("\n****** EXCEPTION OCCURRED ******\n");
	x86_printf("%s\n", (char *)buf);
	x86_printf("-> rip = %Z\n", ctx->tf_rip);
	x86_printf("-> rsp = %Z\n", ctx->tf_rsp);
	x86_printf("-> tls = %Z (gid=%Z)\n", (uint64_t)curcpu(),
	    (uint64_t)hal_get_gid());
	x86_printf("-> err = %Z\n", ctx->tf_err);
	if (excno == T_PAGEFLT)
		x86_printf("-> va  = %Z\n", rcr2());
	x86_printf("****** EXCEPTION OCCURRED ******\n\n");
	x86_unlock();

	while (1);
}

/* -------------------------------------------------------------------------- */

void hal_do_exception( thread_t * this,
                       reg_t    * regs_tbl )
{
	x86_panic((char *)__func__);
}

void hal_exception_dump( thread_t * this,
                         reg_t    * regs_tbl )
{
	x86_panic((char *)__func__);
}

