/*
 * 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_stoppable_begin(void)
{
	int nsc;
	call_t *db_call, *go_call;
	ipl_t ipl;

	ipl = interrupts_disable();
	spinlock_lock(&TASK->lock);

	nsc = --TASK->not_stoppable_count;
	db_call = TASK->debug_begin_call;

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

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

		/* Lock order OK, THREAD->debug_lock is after TASK->lock */
		spinlock_lock(&THREAD->debug_lock);
		THREAD->debug_stoppable = true;
		spinlock_unlock(&THREAD->debug_lock);

		TASK->dt_state = UDEBUG_TS_ACTIVE;
		TASK->debug_begin_call = NULL;
		spinlock_unlock(&TASK->lock);
		interrupts_restore(ipl);

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

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

		/* Lock order OK, THREAD->debug_lock is after TASK->lock */
		spinlock_lock(&THREAD->debug_lock);
		THREAD->debug_stoppable = true;

		if (THREAD->debug_stop) {
			/*
			 * Thread was requested to stop - answer go call
			 */

			/* Make sure nobody takes this call away from us */
			go_call = THREAD->debug_go_call;
			THREAD->debug_go_call = NULL;

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

			THREAD->cur_event = UDEBUG_EVENT_STOP;
			spinlock_unlock(&THREAD->debug_lock);

	    		ipc_answer(&TASK->answerbox, go_call);

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

		/* Lock order OK, THREAD->debug_lock is after TASK->lock */
		spinlock_lock(&THREAD->debug_lock);
		THREAD->debug_stoppable = true;
		spinlock_unlock(&THREAD->debug_lock);

	        spinlock_unlock(&TASK->lock);
		interrupts_restore(ipl);
	}
}

void udebug_stoppable_end(void)
{
	ipl_t ipl;

restart:
	ipl = interrupts_disable();
	spinlock_lock(&TASK->lock);

	/* Lock order OK, THREAD->debug_lock is after TASK->lock */
	spinlock_lock(&THREAD->debug_lock);

	if (TASK->dt_state == UDEBUG_TS_ACTIVE) {
		klog_printf("udebug_stoppable_end");
		klog_printf("debug_stop=%d", THREAD->debug_stop);
	}

	if ((TASK->dt_state == UDEBUG_TS_BEGINNING ||
	    TASK->dt_state == UDEBUG_TS_ACTIVE) &&
	    THREAD->debug_stop == true) {
		TASK->debug_begin_call = NULL;
		spinlock_unlock(&THREAD->debug_lock);
		spinlock_unlock(&TASK->lock);
		interrupts_restore(ipl);

		klog_printf("udebug_stoppable_end: waitq_sleep");
		waitq_sleep(&THREAD->go_wq);
		goto restart;
		/* must try again - have to lose stoppability atomically */
	} else {
		++TASK->not_stoppable_count;
		THREAD->debug_stoppable = false;

		spinlock_unlock(&THREAD->debug_lock);
		spinlock_unlock(&TASK->lock);
		interrupts_restore(ipl);
	}
}

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)
{
	call_t *call;
	ipl_t ipl;

	ipl = interrupts_disable();
	spinlock_lock(&THREAD->debug_lock);

	/* Must only generate events when in debugging session and have go */
	if (THREAD->debug_active != true ||
	    THREAD->debug_stop == true ||
	    (TASK->debug_evmask & UDEBUG_EM_SYSCALL) == 0) {
		spinlock_unlock(&THREAD->debug_lock);
		interrupts_restore(ipl);
		return;
	}

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

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

	/*
	 * Make sure debug_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->debug_stop = true;

	THREAD->cur_event = UDEBUG_EVENT_SYSCALL;
	spinlock_unlock(&THREAD->debug_lock);

	spinlock_lock(&TASK->lock);
	ipc_answer(&TASK->answerbox, THREAD->debug_go_call);
	spinlock_unlock(&TASK->lock);

	interrupts_restore(ipl);

	waitq_sleep(&THREAD->go_wq);
}

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

	ipl = interrupts_disable();
	spinlock_lock(&THREAD->debug_lock);

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

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

	klog_printf("- trigger event");

	call = THREAD->debug_go_call;
	IPC_SET_RETVAL(call->data, 0);
	IPC_SET_ARG1(call->data, UDEBUG_EVENT_NEW_THREAD);
	IPC_SET_ARG2(call->data, (unative_t)t);

	/*
	 * Make sure debug_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->debug_stop = true;

	THREAD->cur_event = UDEBUG_EVENT_NEW_THREAD;
	spinlock_unlock(&THREAD->debug_lock);

	spinlock_lock(&TASK->lock);
	ipc_answer(&TASK->answerbox, THREAD->debug_go_call);
	spinlock_unlock(&TASK->lock);

	interrupts_restore(ipl);
	klog_printf("- sleep");

	waitq_sleep(&THREAD->go_wq);
}

/**
 * Terminate task debugging session.
 *
 * \param ta Must be already locked and interrupts must be disabled.
 * \return Zero on success or negative error code.
 */
int udebug_task_cleanup(struct task *ta)
{
	thread_t *t;
	link_t *cur;
	int flags;

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

	if (ta->dt_state == UDEBUG_TS_BEGINNING &&
	    ta->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);

		spinlock_lock(&t->debug_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->debug_active = false;
			t->cur_event = 0;	/* none */

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

				/* Answer GO call */
				klog_printf("answer GO call with EVENT_FINISHED");
				IPC_SET_RETVAL(t->debug_go_call->data, 0);
				IPC_SET_ARG1(t->debug_go_call->data, UDEBUG_EVENT_FINISHED);
				ipc_answer(&ta->answerbox, t->debug_go_call);
			} 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->go_wq, WAKEUP_FIRST);
			}
		}
		spinlock_unlock(&t->debug_lock);
	}

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

	return 0;
}


/** @}
 */
