/*
 * Copyright 2010  OpenSourceCodeStewardshipFoundation
 *
 * Licensed under BSD
 */

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

#include "VMS.h"
#include "Queue_impl/BlockingQueue.h"


//===========================================================================
void
shutdownFn( void *dummy, VirtProcr *dummy2 );

void
create_sched_slots( MasterEnv *masterEnv );

//===========================================================================

/*Setup has two phases:
 * 1) Semantic layer first calls init_VMS, which creates masterEnv, and puts
 *    the master virt procr into the work-queue, ready for first "call"
 * 2) Semantic layer then does its own init, which creates the seed virt
 *    procr inside the semantic layer, ready to schedule it when
 *    asked by the first run of the masterLoop.
 *
 *This part is bit weird because VMS really wants to be "always there", and
 * have applications attach and detach..  for now, this VMS is part of
 * the app, so the VMS system starts up as part of running the app.
 *
 *The semantic layer is isolated from the VMS internals by making the
 * semantic layer do setup to a state that it's ready with its
 * initial virt procrs, ready to schedule them to slots when the masterLoop
 * asks.  Without this pattern, the semantic layer's setup would
 * have to modify slots directly to assign the initial virt-procrs, and put
 * them into the workQ itself, breaking the isolation completely.
 *
 * 
 *The semantic layer creates the initial virt procr(s), and adds its
 * own environment to masterEnv, and fills in the pointers to
 * the requestHandler and slaveScheduler plug-in functions
 */

/*This allocates VMS data structures, populates the master VMSProc,
 * and master environment, and returns the master environment to the semantic
 * layer.
 */
void
VMS__init()
 { MasterEnv  *masterEnv;
   CASQueueStruc *workQ;

      //Make the central work-queue
   _VMSWorkQ = makeCASQ();
   workQ     = _VMSWorkQ;

   _VMSMasterEnv = malloc( sizeof(MasterEnv) );
   masterEnv     = _VMSMasterEnv;

      //create the master virtual processor
   masterEnv->masterVirtPr = VMS__create_procr( &masterLoop, masterEnv );

   create_sched_slots( masterEnv );

     //Set slot 0 to be the master virt procr & set flags just in case
   masterEnv->schedSlots[0]->needsProcrAssigned  = FALSE;  //says don't touch
   masterEnv->schedSlots[0]->workIsDone          = FALSE;  //says don't touch
   masterEnv->schedSlots[0]->procrAssignedToSlot = masterEnv->masterVirtPr;
   masterEnv->masterVirtPr->schedSlot = masterEnv->schedSlots[0];
   masterEnv->stillRunning = FALSE;
   
      //First core loop to start up gets this, which will schedule seed Pr
      //TODO: debug: check address of masterVirtPr
   writeCASQ( masterEnv->masterVirtPr, workQ );

   numProcrsCreated = 1;

   //========================================================================
   //                      Create the Threads
   int coreIdx;

   //Make params given to the win threads that animate the core loops
   for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
    { coreLoopThdParams[coreIdx]          = malloc( sizeof(ThdParams) );
      coreLoopThdParams[coreIdx]->coreNum = coreIdx;

         //make the core loop threads, born in suspended state
      coreLoopThdHandles[ coreIdx ] =
         CreateThread ( NULL, // Security attributes
                        0, // Stack size
                        coreLoop,
                        coreLoopThdParams[coreIdx],
                        CREATE_SUSPENDED,
                        &(coreLoopThdIds[coreIdx])
                       );
    }

 }


void
create_sched_slots( MasterEnv *masterEnv )
 { SchedSlot  **schedSlots, **filledSlots;
   int i;

   schedSlots  = malloc( NUM_SCHED_SLOTS * sizeof(SchedSlot *) );
   filledSlots = malloc( NUM_SCHED_SLOTS * sizeof(SchedSlot *) );
   masterEnv->schedSlots  = schedSlots;
   masterEnv->filledSlots = filledSlots;

   for( i = 0; i < NUM_SCHED_SLOTS; i++ )
    {
      schedSlots[i] = malloc( sizeof(SchedSlot) );

         //Set state to mean "handling requests done, slot needs filling"
      schedSlots[i]->workIsDone         = FALSE;
      schedSlots[i]->needsProcrAssigned = TRUE;
    }
 }


/*Semantic layer calls this when it want the system to start running..
 *
 *This starts the core loops running then waits for them to exit.
 */
void
VMS__start_the_work_then_wait_until_done()
 { int coreIdx;
      //Start the core loops running
//===========================================================================
   LARGE_INTEGER stPerfCount, endPerfCount, countFreq;
   unsigned long long count = 0, freq = 0;
   double runTime;

   QueryPerformanceCounter( &stPerfCount );

      //start them running
   for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
    {    //Create the threads
      ResumeThread( coreLoopThdHandles[coreIdx] ); //starts thread
    }

      //wait for all to complete
   for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
    {
      WaitForSingleObject(coreLoopThdHandles[coreIdx], INFINITE);
    }

      //NOTE: do not clean up VMS env here -- semantic layer has to have
      // a chance to clean up its environment first, then do a call to free
      // the Master env and rest of VMS locations

   QueryPerformanceCounter( &endPerfCount );
   count = endPerfCount.QuadPart - stPerfCount.QuadPart;

   QueryPerformanceFrequency( &countFreq );
   freq = countFreq.QuadPart;
   runTime = (double)count / (double)freq;

   printf("\n Time startup to shutdown: %f\n", runTime);
   fflush( stdin );
 }



/*Create stack, then create __cdecl structure on it and put initialData and
 * pointer to the new structure instance into the parameter positions on
 * the stack
 *Then put function pointer into nextInstrPt -- the stack is setup in std
 * call structure, so jumping to function ptr is same as a GCC generated
 * function call
 *No need to save registers on old stack frame, because there's no old
 * animator state to return to --
 *
 */
VirtProcr *
VMS__create_procr( VirtProcrFnPtr fnPtr, void *initialData )
 { VirtProcr *newPr;
   char      *stackLocs, *stackPtr;

   newPr              = malloc( sizeof(VirtProcr) );
   newPr->procrID     = numProcrsCreated++;
   newPr->nextInstrPt = fnPtr;
   newPr->initialData = initialData;

      //fnPtr takes two params -- void *initData & void *animProcr
      //alloc stack locations, make stackPtr be the highest addr minus room
      // for 2 params + return addr.  Return addr (NULL) is in loc pointed to
      // by stackPtr, initData at stackPtr + 4 bytes, animatingPr just above
   stackLocs = malloc( VIRT_PROCR_STACK_SIZE );
   newPr->startOfStack = stackLocs;
   stackPtr = ( (char *)stackLocs + VIRT_PROCR_STACK_SIZE - 0x10 );
      //setup __cdecl on stack -- coreloop will switch to stackPtr before jmp
   *( (int *)stackPtr + 2 ) = (int) newPr; //rightmost param -- 32bit pointer
   *( (int *)stackPtr + 1 ) = (int) initialData;  //next  param to left
   newPr->stackPtr = stackPtr; //core loop will switch to this, then
   newPr->framePtr = stackPtr; //suspend loop will save new stack & frame ptr

   return newPr;
 }


 /*there is a label inside this function -- save the addr of this label in
 * the callingPr struc, as the pick-up point from which to start the next
 * work-unit for that procr.  If turns out have to save registers, then
 * save them in the procr struc too.  Then do assembly jump to the CoreLoop's
 * "done with work-unit" label.  The procr struc is in the request in the
 * slave that animated the just-ended work-unit, so all the state is saved
 * there, and will get passed along, inside the request handler, to the
 * next work-unit for that procr.
 */
void
VMS__suspend_procr( VirtProcr *callingPr )
 { void *jmpPt, *stackPtrAddr, *framePtrAddr, *coreLoopStackPtr;
   void *coreLoopFramePtr;

      //The request to master will cause this suspended virt procr to get
      // scheduled again at some future point -- to resume, core loop jumps
      // to the resume point (below), which causes restore of saved regs and
      // "return" from this call.
   callingPr->nextInstrPt = &&ResumePt;

      //return ownership of the virt procr and sched slot to Master virt pr
   callingPr->schedSlot->workIsDone = TRUE;
//   coreIdx = callingPr->coreAnimatedBy;

   stackPtrAddr      = &(callingPr->stackPtr);
   framePtrAddr      = &(callingPr->framePtr);
   
   jmpPt             = callingPr->coreLoopStartPt;
   coreLoopFramePtr  = callingPr->coreLoopFramePtr;//need this only
   coreLoopStackPtr  = callingPr->coreLoopStackPtr;//shouldn't need -- safety

      //Save the virt procr's stack and frame ptrs, restore coreloop's frame
      // ptr, then jump back to "start" of core loop
      //Note, GCC compiles to assembly that saves esp and ebp in the stack
      // frame -- so have to explicitly do assembly that saves to memory
   asm volatile("movl %0,     %%eax;  \
                 movl %%esp, (%%eax); \
                 movl %1,     %%eax;  \
                 movl %%ebp, (%%eax); \
                 movl %2, %%eax;      \
                 movl %3, %%esp;      \
                 movl %4, %%ebp;      \
                 jmp  %%eax    "      \
   /* outputs */ : "=g" (stackPtrAddr), "=g" (framePtrAddr) \
   /* inputs  */ : "g" (jmpPt), "g"(coreLoopStackPtr), "g"(coreLoopFramePtr)\
   /* clobber */ : "memory", "%eax", "%ebx", "%ecx", "%edx", "%edi","%esi"  \
                ); //list everything as clobbered to force GCC to save all
                   // live vars that are in regs on stack before this
                   // assembly, so that stack pointer is correct, before jmp

ResumePt:
   return;
 }



/*This is equivalent to "jump back to core loop" -- it's mainly only used
 * just after adding dissipate request to a processor -- so the semantic
 * layer is the only place it will be seen and/or used.
 *
 *It does almost the same thing as suspend, except don't need to save the
 * stack nor set the nextInstrPt
 *
 *As of June 30, 2010  just implementing as a call to suspend -- just sugar
 */
void
VMS__return_from_fn( VirtProcr *animatingPr )
 {
   VMS__suspend_procr( animatingPr );
 }


/*Not sure yet the form going to put "dissipate" in, so this is the third
 * possibility -- the semantic layer can just make a macro that looks like
 * a call to its name, then expands to a call to this.
 *
 *As of June 30, 2010  this looks like the top choice..
 *
 *This adds a request to dissipate, then suspends the processor so that the
 * request handler will receive the request.  The request handler is what
 * does the work of freeing memory and removing the processor from the
 * semantic environment's data structures.
 *The request handler also is what figures out when to shutdown the VMS
 * system -- which causes all the core loop threads to die, and returns from
 * the call that started up VMS to perform the work.
 *
 *This form is a bit misleading to understand if one is trying to figure out
 * how VMS works -- it looks like a normal function call, but inside it
 * sends a request to the request handler and suspends the processor, which
 * jumps out of the VMS__dissipate_procr function, and out of all nestings
 * above it, transferring the work of dissipating to the request handler,
 * which then does the actual work -- causing the processor that animated
 * the call of this function to disappear and the "hanging" state of this
 * function to just poof into thin air -- the virtual processor's trace
 * never returns from this call, but instead the virtual processor's trace
 * gets suspended in this call and all the virt processor's state disap-
 * pears -- making that suspend the last thing in the virt procr's trace.
 */
void
VMS__dissipate_procr( VirtProcr *procrToDissipate )
 { VMSReqst *req;

   req = malloc( sizeof(VMSReqst) );
//   req->virtProcrFrom      = callingPr;
   req->reqType               = dissipate;
   req->nextReqst             = procrToDissipate->requests;
   procrToDissipate->requests = req;
   
   VMS__suspend_procr( procrToDissipate );
}


/*This inserts the semantic-layer's request data into standard VMS carrier
 */
inline void
VMS__add_sem_request( void *semReqData, VirtProcr *callingPr )
 { VMSReqst *req;

   req = malloc( sizeof(VMSReqst) );
//   req->virtProcrFrom      = callingPr;
   req->reqType        = semantic;
   req->semReqData     = semReqData;
   req->nextReqst      = callingPr->requests;
   callingPr->requests = req;
 }



//TODO: add a semantic-layer supplied "freer" for the semantic-data portion
// of a request -- IE call with both a virt procr and a fn-ptr to request
// freer (or maybe put request freer as a field in virt procr?)
void
VMS__remove_and_free_top_request( VirtProcr *procrWithReq )
 { VMSReqst *req;

   req = procrWithReq->requests;
   procrWithReq->requests = procrWithReq->requests->nextReqst;
   free( req );
 }


//TODO: add a semantic-layer supplied "freer" for the semantic-data portion
// of a request -- IE call with both a virt procr and a fn-ptr to request
// freer (also maybe put sem request freer as a field in virt procr?)
void
VMS__free_request( VMSReqst *req )
 { 
   free( req );
 }

VMSReqst *
VMS__take_top_request_from( VirtProcr *procrWithReq )
 { VMSReqst *req;

   req = procrWithReq->requests;
   if( req == NULL ) return req;
   
   procrWithReq->requests = procrWithReq->requests->nextReqst;
   return req;
 }

inline int
VMS__isSemanticReqst( VMSReqst *req )
 {
   return ( req->reqType == semantic );
 }


inline void *
VMS__take_sem_reqst_from( VMSReqst *req )
 {
   return req->semReqData;
 }

inline int
VMS__isDissipateReqst( VMSReqst *req )
 {
   return ( req->reqType == dissipate );
 }

inline int
VMS__isCreateReqst( VMSReqst *req )
 {
   return ( req->reqType == regCreated );
 }

void
VMS__send_register_new_procr_request(VirtProcr *newPr, VirtProcr *reqstingPr)
 { VMSReqst *req;

   req                  = malloc( sizeof(VMSReqst) );
   req->reqType         = regCreated;
   req->semReqData      = newPr;
   req->nextReqst       = reqstingPr->requests;
   reqstingPr->requests = req;

   VMS__suspend_procr( reqstingPr );
 }


/*The semantic layer figures out when the work is done ( perhaps by a call
 * in the application to "work all done", or perhaps all the virtual
 * processors have dissipated.. a.s.o. )
 *
 *The semantic layer is responsible for making sure all work has fully
 * completed before using this to shutdown the VMS system.
 *
 *After the semantic layer has determined it wants to shut down, the
 * next time the Master Loop calls the scheduler plug-in, the scheduler
 * then calls this function and returns the virtual processor it gets back.
 *
 *When the shut-down processor runs, it first frees all locations malloc'd to
 * the VMS system (that wasn't
 * specified as return-locations).  Then it creates one core-loop shut-down
 * processor for each core loop and puts them all into the workQ.  When a
 * core loop animates a core loop shut-down processor, it causes exit-thread
 * to run, and when all core loop threads have exited, then the "wait for
 * work to finish" in the main thread is woken, and the function-call that
 * started all the work returns.
 *
 *The function animated by this processor performs the shut-down work.
 */
VirtProcr *
VMS__create_the_shutdown_procr()
 {
   return VMS__create_procr( &shutdownFn, NULL );
 }


/*This must be called by the request handler plugin -- it cannot be called
 * from the semantic library "dissipate processor" function -- instead, the
 * semantic layer has to generate a request for the plug-in to call this
 * function.
 *The reason is that this frees the virtual processor's stack -- which is
 * still in use inside semantic library calls!
 *
 *This frees or recycles all the state owned by and comprising the VMS
 * portion of the animating virtual procr.  The request handler must first
 * free any semantic data created for the processor that didn't use the
 * VMS_malloc mechanism.  Then it calls this, which first asks the malloc
 * system to disown any state that did use VMS_malloc, and then frees the
 * statck and the processor-struct itself.
 *If the dissipated processor is the sole (remaining) owner of VMS__malloc'd
 * state, then that state gets freed (or sent to recycling) as a side-effect
 * of dis-owning it.
 */
void
VMS__free_procr_locs( VirtProcr *animatingPr )
 {
      //dis-own all locations owned by this processor, causing to be freed
      // any locations that it is (was) sole owner of
   //TODO: implement VMS__malloc system, including "give up ownership"

      //The dissipate request might still be attached, so remove and free it
   VMS__remove_and_free_top_request( animatingPr );
   free( animatingPr->startOfStack );

      //NOTE: initialData was given to the processor, so should either have
      // been alloc'd with VMS__malloc, or freed by the level above animPr.
      //So, all that's left to free here is the stack and the VirtProcr struc
      // itself
   free( animatingPr->startOfStack );
   free( animatingPr );
 }



/*This is the function run by the special "shut-down" processor
 * 
 *The _VMSMasterEnv is needed by this shut down function, so the "wait"
 * function run in the main loop has to free it, and the thread-related
 * locations (coreLoopThdParams a.s.o.).
 *However, the semantic environment and all data malloc'd to VMS can be
 * freed here.
 *
 *NOTE: the semantic plug-in is expected to use VMS__malloc to get all the
 * locations it needs -- they will be automatically freed by the standard
 * "free all owned locations"
 *
 *Free any locations malloc'd to the VMS system (that weren't
 * specified as return-locations).
 *Then create one core-loop shut-down processor for each core loop and puts
 * them all into the workQ.
 */
void
shutdownFn( void *dummy, VirtProcr *animatingPr )
 { int coreIdx;
   VirtProcr *shutDownPr;
   CASQueueStruc *workQ = _VMSWorkQ;

      //free all the locations owned within the VMS system
   //TODO: write VMS__malloc and free.. -- take the DKU malloc as starting pt

      //make the core loop shut-down processors and put them into the workQ
   for( coreIdx=0; coreIdx < NUM_CORES; coreIdx++ )
    {
      shutDownPr = VMS__create_procr( NULL, NULL );
      shutDownPr->nextInstrPt = _VMSMasterEnv->coreLoopShutDownPt;
      writeCASQ( shutDownPr, workQ );
    }

      //This is an issue: the animating processor of this function may not
      // get its request handled before all the cores have shutdown.
      //TODO: after all the threads stop, clean out the MasterEnv, the
      // SemanticEnv, and the workQ before returning.
   VMS__dissipate_procr( animatingPr );  //will never come back from this
 }


/*This has to free anything allocated during VMS_init, and any other alloc'd
 * locations that might be left over.
 */
void
VMS__shutdown()
 { int i;
 
   free( _VMSWorkQ );
   free( _VMSMasterEnv->filledSlots );
   for( i = 0; i < NUM_SCHED_SLOTS; i++ )
    {
      free( _VMSMasterEnv->schedSlots[i] );
    }

   free( _VMSMasterEnv->schedSlots);
   VMS__free_procr_locs( _VMSMasterEnv->masterVirtPr );
   
   free( _VMSMasterEnv );
 }


//===========================================================================

inline TSCount getTSCount()
 { unsigned int low, high;
   TSCount  out;

   saveTimeStampCountInto( low, high );
   out = high;
   out = (out << 32) + low;
   return out;
 }

