//
// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// signal.c --
//
// Author           : Thierry Delisle
// Created On       : Mon Jun 5 14:20:42 2017
// Last Modified By : Peter A. Buhr
// Last Modified On : Mon Apr  9 13:52:39 2018
// Update Count     : 36
//

#include "preemption.h"

extern "C" {
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
}

#include "bits/signal.h"

#if !defined(__CFA_DEFAULT_PREEMPTION__)
#define __CFA_DEFAULT_PREEMPTION__ 10`ms
#endif

Duration default_preemption() __attribute__((weak)) {
	return __CFA_DEFAULT_PREEMPTION__;
}

// FwdDeclarations : timeout handlers
static void preempt( processor   * this );
static void timeout( thread_desc * this );

// FwdDeclarations : Signal handlers
void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
void sigHandler_segv     ( __CFA_SIGPARMS__ );
void sigHandler_ill      ( __CFA_SIGPARMS__ );
void sigHandler_fpe      ( __CFA_SIGPARMS__ );
void sigHandler_abort    ( __CFA_SIGPARMS__ );

// FwdDeclarations : alarm thread main
void * alarm_loop( __attribute__((unused)) void * args );

// Machine specific register name
#if   defined( __i386 )
#define CFA_REG_IP gregs[REG_EIP]
#elif defined( __x86_64 )
#define CFA_REG_IP gregs[REG_RIP]
#elif defined( __ARM_ARCH )
#define CFA_REG_IP arm_pc
#else
#error unknown hardware architecture
#endif

KERNEL_STORAGE(event_kernel_t, event_kernel);         // private storage for event kernel
event_kernel_t * event_kernel;                        // kernel public handle to even kernel
static pthread_t alarm_thread;                        // pthread handle to alarm thread

void ?{}(event_kernel_t & this) with( this ) {
	alarms{};
	lock{};
}

enum {
	PREEMPT_NORMAL    = 0,
	PREEMPT_TERMINATE = 1,
};

//=============================================================================================
// Kernel Preemption logic
//=============================================================================================

// Get next expired node
static inline alarm_node_t * get_expired( alarm_list_t * alarms, Time currtime ) {
	if( !alarms->head ) return NULL;                          // If no alarms return null
	if( alarms->head->alarm >= currtime ) return NULL;        // If alarms head not expired return null
	return pop(alarms);                                       // Otherwise just pop head
}

// Tick one frame of the Discrete Event Simulation for alarms
void tick_preemption() {
	alarm_node_t * node = NULL;                     // Used in the while loop but cannot be declared in the while condition
	alarm_list_t * alarms = &event_kernel->alarms;  // Local copy for ease of reading
	Time currtime = __kernel_get_time();			// Check current time once so we everything "happens at once"

	//Loop throught every thing expired
	while( node = get_expired( alarms, currtime ) ) {

		// Check if this is a kernel
		if( node->kernel_alarm ) {
			preempt( node->proc );
		}
		else {
			timeout( node->thrd );
		}

		// Check if this is a periodic alarm
		Duration period = node->period;
		if( period > 0 ) {
			node->alarm = currtime + period;    // Alarm is periodic, add currtime to it (used cached current time)
			insert( alarms, node );             // Reinsert the node for the next time it triggers
		}
		else {
			node->set = false;                  // Node is one-shot, just mark it as not pending
		}
	}

	// If there are still alarms pending, reset the timer
	if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
}

// Update the preemption of a processor and notify interested parties
void update_preemption( processor * this, Duration duration ) {
	alarm_node_t * alarm = this->preemption_alarm;

	// Alarms need to be enabled
	if ( duration > 0 && ! alarm->set ) {
		alarm->alarm = __kernel_get_time() + duration;
		alarm->period = duration;
		register_self( alarm );
	}
	// Zero duration but alarm is set
	else if ( duration == 0 && alarm->set ) {
		unregister_self( alarm );
		alarm->alarm = 0;
		alarm->period = 0;
	}
	// If alarm is different from previous, change it
	else if ( duration > 0 && alarm->period != duration ) {
		unregister_self( alarm );
		alarm->alarm = __kernel_get_time() + duration;
		alarm->period = duration;
		register_self( alarm );
	}
}

//=============================================================================================
// Kernel Signal Tools
//=============================================================================================

__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )

extern "C" {
	// Disable interrupts by incrementing the counter
	void disable_interrupts() {
		TL_GET( preemption_state ).enabled = false;
		__attribute__((unused)) unsigned short new_val = TL_GET( preemption_state ).disable_count + 1;
		TL_GET( preemption_state ).disable_count = new_val;
		verify( new_val < 65_000u );              // If this triggers someone is disabling interrupts without enabling them
	}

	// Enable interrupts by decrementing the counter
	// If counter reaches 0, execute any pending CtxSwitch
	void enable_interrupts( __cfaabi_dbg_ctx_param ) {
		processor   * proc = TL_GET( this_processor ); // Cache the processor now since interrupts can start happening after the atomic add
		thread_desc * thrd = TL_GET( this_thread );	  // Cache the thread now since interrupts can start happening after the atomic add

		unsigned short prev = TL_GET( preemption_state ).disable_count;
		TL_GET( preemption_state ).disable_count -= 1;
		verify( prev != 0u );                     // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );

		// Check if we need to prempt the thread because an interrupt was missed
		if( prev == 1 ) {
			TL_GET( preemption_state ).enabled = true;
			if( proc->pending_preemption ) {
				proc->pending_preemption = false;
				BlockInternal( thrd );
			}
		}

		// For debugging purposes : keep track of the last person to enable the interrupts
		__cfaabi_dbg_debug_do( proc->last_enable = caller; )
	}

	// Disable interrupts by incrementint the counter
	// Don't execute any pending CtxSwitch even if counter reaches 0
	void enable_interrupts_noPoll() {
		unsigned short prev = TL_GET( preemption_state ).disable_count;
		TL_GET( preemption_state ).disable_count -= 1;
		verifyf( prev != 0u, "Incremented from %u\n", prev );                     // If this triggers someone is enabled already enabled interrupts
		if( prev == 1 ) {
			TL_GET( preemption_state ).enabled = true;
		}
	}
}

// sigprocmask wrapper : unblock a single signal
static inline void signal_unblock( int sig ) {
	sigset_t mask;
	sigemptyset( &mask );
	sigaddset( &mask, sig );

	if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
	    abort( "internal error, pthread_sigmask" );
	}
}

// sigprocmask wrapper : block a single signal
static inline void signal_block( int sig ) {
	sigset_t mask;
	sigemptyset( &mask );
	sigaddset( &mask, sig );

	if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
	    abort( "internal error, pthread_sigmask" );
	}
}

// kill wrapper : signal a processor
static void preempt( processor * this ) {
	sigval_t value = { PREEMPT_NORMAL };
	pthread_sigqueue( this->kernel_thread, SIGUSR1, value );
}

// kill wrapper : signal a processor
void terminate(processor * this) {
	this->do_terminate = true;
	sigval_t value = { PREEMPT_TERMINATE };
	pthread_sigqueue( this->kernel_thread, SIGUSR1, value );
}

// reserved for future use
static void timeout( thread_desc * this ) {
	//TODO : implement waking threads
}


// Check if a CtxSwitch signal handler shoud defer
// If true  : preemption is safe
// If false : preemption is unsafe and marked as pending
static inline bool preemption_ready() {
	bool ready = TL_GET( preemption_state ).enabled && !TL_GET( preemption_state ).in_progress; // Check if preemption is safe
	TL_GET( this_processor )->pending_preemption = !ready;			// Adjust the pending flag accordingly
	return ready;
}

//=============================================================================================
// Kernel Signal Startup/Shutdown logic
//=============================================================================================

// Startup routine to activate preemption
// Called from kernel_startup
void kernel_start_preemption() {
	__cfaabi_dbg_print_safe( "Kernel : Starting preemption\n" );

	// Start with preemption disabled until ready
	TL_GET( preemption_state ).enabled = false;
	TL_GET( preemption_state ).disable_count = 1;

	// Initialize the event kernel
	event_kernel = (event_kernel_t *)&storage_event_kernel;
	(*event_kernel){};

	// Setup proper signal handlers
	__cfaabi_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART );         // CtxSwitch handler

	signal_block( SIGALRM );

	pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
}

// Shutdown routine to deactivate preemption
// Called from kernel_shutdown
void kernel_stop_preemption() {
	__cfaabi_dbg_print_safe( "Kernel : Preemption stopping\n" );

	// Block all signals since we are already shutting down
	sigset_t mask;
	sigfillset( &mask );
	sigprocmask( SIG_BLOCK, &mask, NULL );

	// Notify the alarm thread of the shutdown
	sigval val = { 1 };
	pthread_sigqueue( alarm_thread, SIGALRM, val );

	// Wait for the preemption thread to finish
	pthread_join( alarm_thread, NULL );

	// Preemption is now fully stopped

	__cfaabi_dbg_print_safe( "Kernel : Preemption stopped\n" );
}

// Raii ctor/dtor for the preemption_scope
// Used by thread to control when they want to receive preemption signals
void ?{}( preemption_scope & this, processor * proc ) {
	(this.alarm){ proc, (Time){ 0 }, 0`s };
	this.proc = proc;
	this.proc->preemption_alarm = &this.alarm;

	update_preemption( this.proc, this.proc->cltr->preemption_rate );
}

void ^?{}( preemption_scope & this ) {
	disable_interrupts();

	update_preemption( this.proc, 0`s );
}

//=============================================================================================
// Kernel Signal Handlers
//=============================================================================================

// Context switch signal handler
// Receives SIGUSR1 signal and causes the current thread to yield
void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
	__cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.CFA_REG_IP); )

	// SKULLDUGGERY: if a thread creates a processor and the immediately deletes it,
	// the interrupt that is supposed to force the kernel thread to preempt might arrive
	// before the kernel thread has even started running. When that happens an iterrupt
	// we a null 'this_processor' will be caught, just ignore it.
	if(!TL_GET( this_processor )) return;

	choose(sfp->si_value.sival_int) {
		case PREEMPT_NORMAL   : ;// Normal case, nothing to do here
		case PREEMPT_TERMINATE: verify(TL_GET( this_processor )->do_terminate);
		default:
			abort( "internal error, signal value is %d", sfp->si_value.sival_int );
	}

	// Check if it is safe to preempt here
	if( !preemption_ready() ) { return; }

	__cfaabi_dbg_print_buffer_decl( " KERNEL: preempting core %p (%p).\n", this_processor, this_thread);

	TL_GET( preemption_state ).in_progress = true;  // Sync flag : prevent recursive calls to the signal handler
	signal_unblock( SIGUSR1 );                          // We are about to CtxSwitch out of the signal handler, let other handlers in
	TL_GET( preemption_state ).in_progress = false; // Clear the in progress flag

	// Preemption can occur here

	BlockInternal( (thread_desc*)TL_GET( this_thread ) ); // Do the actual CtxSwitch
}

// Main of the alarm thread
// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
void * alarm_loop( __attribute__((unused)) void * args ) {
	// Block sigalrms to control when they arrive
	sigset_t mask;
	sigemptyset( &mask );
	sigaddset( &mask, SIGALRM );

	if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
	    abort( "internal error, pthread_sigmask" );
	}

	// Main loop
	while( true ) {
		// Wait for a sigalrm
		siginfo_t info;
		int sig = sigwaitinfo( &mask, &info );

		if( sig < 0 ) {
			//Error!
			int err = errno;
			switch( err ) {
				case EAGAIN :
				case EINTR :
					continue;
       			case EINVAL :
				 	abort( "Timeout was invalid." );
				default:
				 	abort( "Unhandled error %d", err);
			}
		}

		// If another signal arrived something went wrong
		assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);

		// __cfaabi_dbg_print_safe( "Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
		// Switch on the code (a.k.a. the sender) to
		switch( info.si_code )
		{
		// Timers can apparently be marked as sent for the kernel
		// In either case, tick preemption
		case SI_TIMER:
		case SI_KERNEL:
			// __cfaabi_dbg_print_safe( "Kernel : Preemption thread tick\n" );
			lock( event_kernel->lock __cfaabi_dbg_ctx2 );
			tick_preemption();
			unlock( event_kernel->lock );
			break;
		// Signal was not sent by the kernel but by an other thread
		case SI_QUEUE:
			// For now, other thread only signal the alarm thread to shut it down
			// If this needs to change use info.si_value and handle the case here
			goto EXIT;
		}
	}

EXIT:
	__cfaabi_dbg_print_safe( "Kernel : Preemption thread stopping\n" );
	return NULL;
}

// Local Variables: //
// mode: c //
// tab-width: 4 //
// End: //
