/** @addtogroup generic
 * @{
 */

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

void udebug_stoppable_begin(void)
{
	int nsc;
	call_t *db_call;

	spinlock_lock(&TASK->lock);

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

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

	if (TASK->stop_request == true && nsc == 0) {
		TASK->stop_request = false;
		TASK->debug_begin_call = NULL;
		spinlock_unlock(&TASK->lock);

		IPC_SET_RETVAL(db_call->data, 0);
		klog_printf("udebug_stoppable_begin/ipc_answer");
		ipc_answer(&TASK->answerbox, db_call);		
	} else {
	        spinlock_unlock(&TASK->lock);
	}
}

void udebug_stoppable_end(void)
{
restart:
	spinlock_lock(&TASK->lock);

	if (TASK->stop_request) {
		TASK->debug_begin_call = NULL;
		spinlock_unlock(&TASK->lock);
		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;
		spinlock_unlock(&TASK->lock);
	}
}

void udebug_syscall_event(void)
{
	spinlock_lock(&TASK->lock);
	/* being debugged + have go */
	if (TASK->being_debugged && !TASK->stop_request) { /* locking! */
		klog_printf("udebug_syscall_event");
		IPC_SET_RETVAL(TASK->debug_go_call->data, 0);
		klog_printf("udebug_syscall_event/ipc_answer");

		ipc_answer(&TASK->answerbox, TASK->debug_go_call);
		spinlock_unlock(&TASK->lock);
		waitq_sleep(&THREAD->go_wq);
	} else {
		spinlock_unlock(&TASK->lock);
	}
}

/** @}
 */
