/*
 * Copyright (c) 2008 Jiri Svoboda
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * - The name of the author may not be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/** @addtogroup generic
 * @{
 */

/**
 * @file
 * @brief	Udebug.
 */
 
#include <synch/waitq.h>
#include <console/klog.h>
#include <udebug/udebug.h>
#include <errno.h>
#include <arch.h>

void udebug_task_init(udebug_task_t *ut)
{
	mutex_initialize(&ut->lock);
	ut->dt_state = UDEBUG_TS_INACTIVE;
	ut->begin_call = NULL;
	ut->not_stoppable_count = 0;
	ut->evmask = 0;
}

void udebug_thread_initialize(udebug_thread_t *ut)
{
	waitq_initialize(&ut->go_wq);
	ut->go_call = NULL;
	ut->uspace_state = NULL;
	ut->stop = true;
	ut->stoppable = true;
	ut->debug_active = false;
	ut->cur_event = 0; /* none */
}

static void udebug_wait_for_go(waitq_t *wq)
{
	int rc;
	ipl_t ipl;

	ipl = waitq_sleep_prepare(wq);

	wq->missed_wakeups = 0;	/* Enforce blocking. */
	rc = waitq_sleep_timeout_unsafe(wq, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NONE);

	waitq_sleep_finish(wq, rc, ipl);
}

void udebug_stoppable_begin(void)
{
	int nsc;
	call_t *db_call, *go_call;
	ipl_t ipl;

	ASSERT(THREAD);
	ASSERT(TASK);

	mutex_lock(&TASK->udebug.lock);

	nsc = --TASK->udebug.not_stoppable_count;

	if (TASK->udebug.dt_state == UDEBUG_TS_BEGINNING) {
		klog_printf("udebug_stoppable_begin");
		klog_printf(" - nsc := %d", nsc);
	}

	if (TASK->udebug.dt_state == UDEBUG_TS_BEGINNING && nsc == 0) {
		/*
		 * This was the last non-stoppable thread. Reply to
		 * DEBUG_BEGIN call.
		 */

		db_call = TASK->udebug.begin_call;
		ASSERT(db_call);

		/* Lock order OK, THREAD->udebug.lock is after TASK->udebug.lock */
		ipl = interrupts_disable();
		spinlock_lock(&THREAD->udebug.lock);
		THREAD->udebug.stoppable = true;
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);

		TASK->udebug.dt_state = UDEBUG_TS_ACTIVE;
		TASK->udebug.begin_call = NULL;
		mutex_unlock(&TASK->udebug.lock);

		IPC_SET_RETVAL(db_call->data, 0);
		//klog_printf("udebug_stoppable_begin/ipc_answer");
		ipc_answer(&TASK->answerbox, db_call);		

	} else if (TASK->udebug.dt_state == UDEBUG_TS_ACTIVE) {
		/*
		 * Active debugging session
		 */

		/* Lock order OK, THREAD->udebug.lock is after TASK->udebug.lock */
		ipl = interrupts_disable();
		spinlock_lock(&THREAD->udebug.lock);
		THREAD->udebug.stoppable = true;

		if (THREAD->udebug.debug_active && THREAD->udebug.stop) {
			/*
			 * Thread was requested to stop - answer go call
			 */

			/* Make sure nobody takes this call away from us */
			go_call = THREAD->udebug.go_call;
			THREAD->udebug.go_call = NULL;
			ASSERT(go_call);

			IPC_SET_RETVAL(go_call->data, 0);
			IPC_SET_ARG1(go_call->data, UDEBUG_EVENT_STOP);

			THREAD->udebug.cur_event = UDEBUG_EVENT_STOP;
			spinlock_unlock(&THREAD->udebug.lock);
			interrupts_restore(ipl);

	    		ipc_answer(&TASK->answerbox, go_call);

		        mutex_unlock(&TASK->udebug.lock);
		} else {
			/*
			 * No stop request - nothing happens.
			 */
			spinlock_unlock(&THREAD->udebug.lock);
			interrupts_restore(ipl);
		        mutex_unlock(&TASK->udebug.lock);
		}
	} else {
		/*
		 * All other cases - nothing special happens.
		 */

		/* Lock order OK, THREAD->udebug.lock is after TASK->udebug.lock */
		ipl = interrupts_disable();
		spinlock_lock(&THREAD->udebug.lock);
		THREAD->udebug.stoppable = true;
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);

	        mutex_unlock(&TASK->udebug.lock);
	}
}

void udebug_stoppable_end(void)
{
	ipl_t ipl;

restart:
	mutex_lock(&TASK->udebug.lock);

	/* Lock order OK, THREAD->udebug.lock is after TASK->udebug.lock */
	ipl = interrupts_disable();
	spinlock_lock(&THREAD->udebug.lock);

	if (TASK->udebug.dt_state == UDEBUG_TS_ACTIVE) {
		//klog_printf("udebug_stoppable_end");
		//klog_printf("udebug.stop=%d", THREAD->udebug.stop);
	}

	if (THREAD->udebug.debug_active &&
	    THREAD->udebug.stop == true) {
		TASK->udebug.begin_call = NULL;
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);
		mutex_unlock(&TASK->udebug.lock);

		udebug_wait_for_go(&THREAD->udebug.go_wq);

		goto restart;
		/* must try again - have to lose stoppability atomically */
	} else {
		++TASK->udebug.not_stoppable_count;
		THREAD->udebug.stoppable = false;

		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);
		mutex_unlock(&TASK->udebug.lock);
	}
}

/** Upon being scheduled to run, check if the current thread should stop.
 *
 * This function is called from clock(). Preemption is enabled.
 * interrupts are disabled, but since this is called after
 * being scheduled-in, we can enable them, if we're careful enough
 * not to allow arbitrary recursion.
 */
void udebug_before_thread_runs(void)
{
	ipl_t ipl;

	/* This will happen if we get preempted inside this function. */
	if (THREAD->udebug.in_before_thread_runs)
		return;

	THREAD->udebug.in_before_thread_runs = true;
	ipl = interrupts_enable();

	/* Now we're free to do whatever we need (lock mutexes, sleep, etc.) */

	/* Check if we're supposed to stop */
	udebug_stoppable_begin();
	udebug_stoppable_end();

	interrupts_restore(ipl);
	THREAD->udebug.in_before_thread_runs = false;
}

void udebug_syscall_event(unative_t a1, unative_t a2, unative_t a3,
    unative_t a4, unative_t a5, unative_t a6, unative_t id, unative_t rc,
    bool end_variant)
{
	call_t *call;
	ipl_t ipl;
	udebug_event_t etype;

	etype = end_variant ? UDEBUG_EVENT_SYSCALL_E : UDEBUG_EVENT_SYSCALL_B;

	mutex_lock(&TASK->udebug.lock);

	ipl = interrupts_disable();
	spinlock_lock(&THREAD->udebug.lock);

	/* Must only generate events when in debugging session and have go */
	if (THREAD->udebug.debug_active != true ||
	    THREAD->udebug.stop == true ||
	    (TASK->udebug.evmask & UDEBUG_EVMASK(etype)) == 0) {
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);
		mutex_unlock(&TASK->udebug.lock);
		return;
	}

	//klog_printf("udebug_syscall_event");
	call = THREAD->udebug.go_call;
	THREAD->udebug.go_call = NULL;

	IPC_SET_RETVAL(call->data, 0);
	IPC_SET_ARG1(call->data, etype);
	IPC_SET_ARG2(call->data, id);
	IPC_SET_ARG3(call->data, rc);
	//klog_printf("udebug_syscall_event/ipc_answer");

	THREAD->udebug.syscall_args[0] = a1;
	THREAD->udebug.syscall_args[1] = a2;
	THREAD->udebug.syscall_args[2] = a3;
	THREAD->udebug.syscall_args[3] = a4;
	THREAD->udebug.syscall_args[4] = a5;
	THREAD->udebug.syscall_args[5] = a6;

	/*
	 * Make sure udebug.stop is true when going to sleep
	 * in case we get woken up by DEBUG_END. (At which
	 * point it must be back to the initial true value).
	 */
	THREAD->udebug.stop = true;

	THREAD->udebug.cur_event = etype;
	spinlock_unlock(&THREAD->udebug.lock);
	interrupts_restore(ipl);

	ipc_answer(&TASK->answerbox, call);

	mutex_unlock(&TASK->udebug.lock);

	udebug_wait_for_go(&THREAD->udebug.go_wq);
}

void udebug_thread_b_event(struct thread *t)
{
	call_t *call;
	ipl_t ipl;

	mutex_lock(&TASK->udebug.lock);

	ipl = interrupts_disable();
	spinlock_lock(&THREAD->udebug.lock);

	klog_printf("udebug_thread_b_event");
	klog_printf("- check state");

	/* Must only generate events when in debugging session */
	if (THREAD->udebug.debug_active != true) {
		klog_printf("- debug_active: %s, udebug.stop: %s",
			THREAD->udebug.debug_active ? "yes(+)" : "no(-)",
			THREAD->udebug.stop ? "yes(-)" : "no(+)");
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);
		mutex_unlock(&TASK->udebug.lock);
		return;
	}

	klog_printf("- trigger event");

	call = THREAD->udebug.go_call;
	THREAD->udebug.go_call = NULL;
	IPC_SET_RETVAL(call->data, 0);
	IPC_SET_ARG1(call->data, UDEBUG_EVENT_THREAD_B);
	IPC_SET_ARG2(call->data, (unative_t)t);

	/*
	 * Make sure udebug.stop is true when going to sleep
	 * in case we get woken up by DEBUG_END. (At which
	 * point it must be back to the initial true value).
	 */
	THREAD->udebug.stop = true;

	THREAD->udebug.cur_event = UDEBUG_EVENT_THREAD_B;
	spinlock_unlock(&THREAD->udebug.lock);
	interrupts_restore(ipl);

	ipc_answer(&TASK->answerbox, call);

	mutex_unlock(&TASK->udebug.lock);

	klog_printf("- sleep");
	udebug_wait_for_go(&THREAD->udebug.go_wq);
}

void udebug_thread_e_event(void)
{
	call_t *call;
	ipl_t ipl;

	mutex_lock(&TASK->udebug.lock);

	ipl = interrupts_disable();
	spinlock_lock(&THREAD->udebug.lock);

	klog_printf("udebug_thread_e_event");
	klog_printf("- check state");

	/* Must only generate events when in debugging session */
	if (THREAD->udebug.debug_active != true) {
		klog_printf("- debug_active: %s, udebug.stop: %s",
			THREAD->udebug.debug_active ? "yes(+)" : "no(-)",
			THREAD->udebug.stop ? "yes(-)" : "no(+)");
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);
		mutex_unlock(&TASK->udebug.lock);
		return;
	}

	klog_printf("- trigger event");

	call = THREAD->udebug.go_call;
	THREAD->udebug.go_call = NULL;
	IPC_SET_RETVAL(call->data, 0);
	IPC_SET_ARG1(call->data, UDEBUG_EVENT_THREAD_E);

	/* Prevent any further debug activity in thread */
	THREAD->udebug.debug_active = false;
	THREAD->udebug.cur_event = 0;		/* none */
	THREAD->udebug.stop = true;	/* set to initial value */

	spinlock_unlock(&THREAD->udebug.lock);
	interrupts_restore(ipl);

	ipc_answer(&TASK->answerbox, call);

	mutex_unlock(&TASK->udebug.lock);

	/* This event does not sleep - debugging has finished in this thread */
}

static void breakpoint_trap_event(uintptr_t addr, udebug_event_t etype)
{
	call_t *call;
	ipl_t ipl;

	mutex_lock(&TASK->udebug.lock);

	ipl = interrupts_disable();
	spinlock_lock(&THREAD->udebug.lock);

	/* Must only generate events when in debugging session and have go */
	if (THREAD->udebug.debug_active != true ||
	    THREAD->udebug.stop == true ||
	    (TASK->udebug.evmask & UDEBUG_EVMASK(etype)) == 0) {
		spinlock_unlock(&THREAD->udebug.lock);
		interrupts_restore(ipl);
		mutex_unlock(&TASK->udebug.lock);
		return;
	}

	klog_printf("udebug_breakpoint/trap_event");
	call = THREAD->udebug.go_call;
	THREAD->udebug.go_call = NULL;

	IPC_SET_RETVAL(call->data, 0);
	IPC_SET_ARG1(call->data, etype);
	IPC_SET_ARG2(call->data, addr);

	/*
	 * Make sure udebug.stop is true when going to sleep
	 * in case we get woken up by DEBUG_END. (At which
	 * point it must be back to the initial true value).
	 */
	THREAD->udebug.stop = true;

	THREAD->udebug.cur_event = etype;
	spinlock_unlock(&THREAD->udebug.lock);
	interrupts_restore(ipl);
	klog_printf("- send answer");

	ipc_answer(&TASK->answerbox, call);
	mutex_unlock(&TASK->udebug.lock);

	udebug_wait_for_go(&THREAD->udebug.go_wq);
}

void udebug_breakpoint_event(uintptr_t addr)
{
	breakpoint_trap_event(addr, UDEBUG_EVENT_BREAKPOINT);
}

void udebug_trap_event(uintptr_t addr)
{
	breakpoint_trap_event(addr, UDEBUG_EVENT_TRAP);
}

/**
 * Terminate task debugging session.
 *
 * \param ta->udebug.lock must be already locked.
 * \return Zero on success or negative error code.
 */
int udebug_task_cleanup(struct task *ta)
{
	thread_t *t;
	link_t *cur;
	int flags;
	ipl_t ipl;

	klog_printf("udebug_task_cleanup()");
	klog_printf("task %llu", ta->taskid);

	if (ta->udebug.dt_state == UDEBUG_TS_BEGINNING &&
	    ta->udebug.dt_state != UDEBUG_TS_ACTIVE) {
		klog_printf("udebug_task_cleanup(): task not being debugged");
		return EINVAL;
	}

	/* Finish debugging of all userspace threads */
	for (cur = ta->th_head.next; cur != &ta->th_head; cur = cur->next) {
		t = list_get_instance(cur, thread_t, th_link);

		ipl = interrupts_disable();
		spinlock_lock(&t->udebug.lock);
		spinlock_lock(&t->lock);

		flags = t->flags;

		spinlock_unlock(&t->lock);

		/* Only process userspace threads */
		if ((flags & THREAD_FLAG_USPACE) != 0) {
			/* Prevent any further debug activity in thread */
			t->udebug.debug_active = false;
			t->udebug.cur_event = 0;	/* none */

			/* Still has go? */
			if (t->udebug.stop == false) {
				/*
				* Yes, so clear go. As debug_active == false,
				 * this doesn't affect anything.
				 */
				t->udebug.stop = true;	

				/* Answer GO call */
				klog_printf("answer GO call with EVENT_FINISHED");
				IPC_SET_RETVAL(t->udebug.go_call->data, 0);
				IPC_SET_ARG1(t->udebug.go_call->data, UDEBUG_EVENT_FINISHED);
				/* FIXME: must not call with interrupts disabled!!*/
				ipc_answer(&ta->answerbox, t->udebug.go_call);
				t->udebug.go_call = NULL;
			} else {
				/*
				 * Debug_stop is already at initial value.
				 * Yet this means the thread needs waking up.
				 */

				/*
				 * t's lock must not be held when calling
				 * waitq_wakeup.
				 */
				waitq_wakeup(&t->udebug.go_wq, WAKEUP_FIRST);
			}
		}
		spinlock_unlock(&t->udebug.lock);
		interrupts_restore(ipl);
	}

	ta->udebug.dt_state = UDEBUG_TS_INACTIVE;
	ta->udebug.debugger = NULL;

	return 0;
}


/** @}
 */
