//
// 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.
//
// invoke.c --
//
// Author           : Thierry Delisle
// Created On       : Tue Jan 17 12:27:26 2016
// Last Modified By : Peter A. Buhr
// Last Modified On : Fri Jul 21 22:28:33 2017
// Update Count     : 1
//

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

#include "libhdr.h"
#include "invoke.h"

#define __CFA_INVOKE_PRIVATE__
#include "invoke.h"

// magically invoke the "main" of the most derived class
// Called from the kernel when starting a coroutine or task so must switch back to user mode.

extern void __suspend_internal(void);
extern void __leave_thread_monitor( struct thread_desc * this );
extern void disable_interrupts();
extern void enable_interrupts( DEBUG_CTX_PARAM );

void CtxInvokeCoroutine(
      void (*main)(void *),
      struct coroutine_desc *(*get_coroutine)(void *),
      void *this
) {
      // LIB_DEBUG_PRINTF("Invoke Coroutine : Received %p (main %p, get_c %p)\n", this, main, get_coroutine);

      struct coroutine_desc* cor = get_coroutine( this );

      if(cor->state == Primed) {
            __suspend_internal();
      }

      cor->state = Active;

      main( this );

      cor->state = Halted;

      //Final suspend, should never return
      __suspend_internal();
      abortf("Resumed dead coroutine");
}

void CtxInvokeThread(
      void (*dtor)(void *),
      void (*main)(void *),
      struct thread_desc *(*get_thread)(void *),
      void *this
) {
      // First suspend, once the thread arrives here,
      // the function pointer to main can be invalidated without risk
      __suspend_internal();

      // Fetch the thread handle from the user defined thread structure
      struct thread_desc* thrd = get_thread( this );

      // Officially start the thread by enabling preemption
      enable_interrupts( DEBUG_CTX );

      // Call the main of the thread
      main( this );

      // To exit a thread we must :
      // 1 - Mark it as halted
      // 2 - Leave its monitor
      // 3 - Disable the interupts
      // 4 - Final suspend
      // The order of these 4 operations is very important
      //Final suspend, should never return
      __leave_thread_monitor( thrd );
      abortf("Resumed dead thread");
}


void CtxStart(
      void (*main)(void *),
      struct coroutine_desc *(*get_coroutine)(void *),
      void *this,
      void (*invoke)(void *)
) {
      // LIB_DEBUG_PRINTF("StartCoroutine : Passing in %p (main %p) to invoke (%p) from start (%p)\n", this, main, invoke, CtxStart);

      struct coStack_t* stack = &get_coroutine( this )->stack;

#if defined( __i386__ )

	struct FakeStack {
	    void *fixedRegisters[3];		  	// fixed registers ebx, edi, esi (popped on 1st uSwitch, values unimportant)
	    uint32_t mxcr;                        // SSE Status and Control bits (control bits are preserved across function calls)
          uint16_t fcw;                         // X97 FPU control word (preserved across function calls)
	    void *rturn;                          // where to go on return from uSwitch
	    void *dummyReturn;				// fake return compiler would have pushed on call to uInvoke
	    void *argument[3];				// for 16-byte ABI, 16-byte alignment starts here
	    void *padding;				// padding to force 16-byte alignment, as "base" is 16-byte aligned
	};

	((struct machine_context_t *)stack->context)->SP = (char *)stack->base - sizeof( struct FakeStack );
	((struct machine_context_t *)stack->context)->FP = NULL;		// terminate stack with NULL fp

	((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->dummyReturn = NULL;
	((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->argument[0] = this;     // argument to invoke
	((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->rturn = invoke;
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->mxcr = 0x1F80; //Vol. 2A 3-520
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->fcw = 0x037F;  //Vol. 1 8-7

#elif defined( __x86_64__ )

      struct FakeStack {
            void *fixedRegisters[5];            // fixed registers rbx, r12, r13, r14, r15
            uint32_t mxcr;                      // SSE Status and Control bits (control bits are preserved across function calls)
            uint16_t fcw;                       // X97 FPU control word (preserved across function calls)
            void *rturn;                        // where to go on return from uSwitch
            void *dummyReturn;                  // NULL return address to provide proper alignment
      };

      ((struct machine_context_t *)stack->context)->SP = (char *)stack->base - sizeof( struct FakeStack );
      ((struct machine_context_t *)stack->context)->FP = NULL;		// terminate stack with NULL fp

      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->dummyReturn = NULL;
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->rturn = CtxInvokeStub;
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->fixedRegisters[0] = this;
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->fixedRegisters[1] = invoke;
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->mxcr = 0x1F80; //Vol. 2A 3-520
      ((struct FakeStack *)(((struct machine_context_t *)stack->context)->SP))->fcw = 0x037F;  //Vol. 1 8-7
#else
      #error Only __i386__ and __x86_64__ is supported for threads in cfa
#endif
}

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