/*-=-=-=-=-=-=-=-=-=-=-=- RCCL/RCI Notice of Copyright -=-=-=-=-=-=-=-=-=-=-*
 *									    *
 *	Copyright (C) 1991 by John E. Lloyd.				    *
 *									    *
 *	Information on copyright permissions, as well as a complete	    *
 *	disclaimer of warranty, is given in the file COPYRIGHT.		    *
 *									    *
 *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#ifdef VXWORKS_CFG

/* routines called by the vxw system code at interrupt level, and so
   must not use the FPU. */

#include <vxWorks.h>
#include <semLib.h>
#include <sigLib.h>

#include "../h/cdefs.h"
#include "../rci/vxwCtrlTask.h"

static itimerInterval;
static itimerValue;

extern SEM_ID *rciCtrlSem;
extern EXEC_REQ clockExr;
extern EXEC_REQ timerExr;
extern int clockReqCount;
extern int clockReqPeriod;
extern int timerReqCount;
extern int rciClockCount;

setItimerValues(interval, value)
int interval;
int value;
{
	itimerInterval = interval;
	itimerValue = value;
}

getItimerValues(interval, value)
int *interval;
int *value;
{
	*interval = itimerInterval;
	*value = itimerValue;
}

rciClockTick()
{
	/* Called once every system clock tick. */

	extern int rciPlanTaskId;
	int s;

	s = intLock();
	if (itimerValue)
	 { if (--itimerValue == 0 && rciPlanTaskId)
	    { kill (rciPlanTaskId, SIGALRM);
	      if (itimerInterval)
	       { itimerValue = itimerInterval;
	       }
	    }
	 }
	rciClockCount++;
	if (clockReqCount != UNDEF && clockReqCount <= rciClockCount)
	 { clockReqCount += clockReqPeriod;	/* reschedule */
	   if (clockReqCount < rciClockCount) /* still?? */
	    { clockReqCount = rciClockCount + clockReqPeriod;
	      logMsg("what? clockReqCount very far behind rciClockCount\n");
	    }
	   placeExecuteRequest(&clockExr);
	 }
	if (timerReqCount != UNDEF)
	 { if (timerReqCount <= rciClockCount)
	    { timerReqCount = UNDEF;		/* clear */
	      placeExecuteRequest(&timerExr);
	    }
	 }
	intUnlock(s);
}

rciInterruptHandler(arg)
int arg;
{
	IntrDevDesc *d = (IntrDevDesc*)arg;

	(*d->intr.intrHandler)(&d->intr);	
	if (d->attached)
	 { placeExecuteRequest(&d->exr);
	 }
}

placeExecuteRequest(exr)
EXEC_REQ *exr;
{
	if (rciCtrlSem)		/* paranoid */
	 { exr->request = 1;
	   semGive(rciCtrlSem);
	 }
	else
	 { logMsg("OUCH, rciCtrlSem is zero in placeExecuteRequest\n");
	 }
}

#endif
