/* task.c */

#if defined(THINK_C)
#include <stdlib.h>
#include <time.h>
#include <string.h>
#else /* defined(THINK_C) */
#endif /* defined(THINK_C) */

#include "stack.h"			/* stack package */
#include "task.h"			/* Read first */

#define Etern ((unsigned long) ~0)	/* eternity (most future time) */
#define ERR (~0)			/* error exit status */

static struct taskdesc_ task0 = {
    (Stack) Null,
    (void (*)()) Sleep,
    Null,
    Etern,
    &task0,
    &task0
};					/* state of initial task */
static int taskcnt = 1;			/* current number of active tasks */

Task ego_ = &task0;			/* current task id */

/* Scan for external events, returning on such an event or on timeout.
 */
    extern void
Hwait ();				/*
    unsigned long timlim		   latest time to return */
	
/* Find a task to run, waiting if necessary; then turn off its alarm and run it.
 * Also, destroy any inactive tasks encountered while searching, and make
 * certain that external events are scanned at least once.  An inactive task
 * is one that has returned from its main routine.
 */
    unsigned long			/* returns current (resumption) time */
Sleep ()
{
    Task sch = ego_;			/* task executing scheduler */
    Task dst;				/* task being destroyed */
    static unsigned long clock;		/* current time */
    unsigned long alarm;		/* earliest alarm time */
    Stack stack;			/* stack id */
    int scan;				/* true iff events have been scanned */

    /* Loop until a task is scheduled. */
    for (scan = 0; ; scan = 1) {

	/* Get current time; init earliest alarm time. */
	clock = time(0);
	alarm = Etern;

	/* Loop thru all the tasks or until one to run is found. */
	for (; ; )

	    /* If task is inactive, destroy it. */
	    if (!(ego_ = ego_->fp)->proc)

		/* Destroy stack; remove taskfrom list; discard its state. */
		if (ego_ != sch) {
		    Dststk((dst = ego_)->stk);
		    (ego_ = dst->bp)->fp = dst->fp;
		    dst->fp->bp = ego_;
		    free(dst);

		/* Defer destruction of current task, the last in the loop. */
		} else
		    break;

	    /* If task is awake, run it. */
	    else if (ego_->alarm < alarm
		    && (alarm = ego_->alarm) <= clock) {

		/* If external events not yet scanned, do so. */
		if (!scan)
		    Hwait(clock);

		/* Turn off task's alarm; switch to its stack. */
		ego_->alarm = Etern;
		stack = Swistk(ego_->stk);

		/* Later, trouble if wrong task or wrong stack resumed. */
		if (ego_ != sch
			|| stack != ego_->stk) {
		    perror("Scheduling tasks");
		    exit(ERR);
		}

		/* If only active task, pause to destroy any inactive tasks. */
		if (taskcnt <= 1
			&& ego_->fp != ego_) {
		    ego_->alarm = 0;
		    alarm = Etern;
		}

		/* Resume execution of reawakened task, returning time. */
		else
		    return clock;

	    /* End loop if all tasks examined. */
	    } else if (ego_ == sch)
		break;

	/* Wait for external event or earliest alarm time. */
	Hwait(alarm);
    }
}

/* Begin execution of a new task.  When the new task returns from its main
 * routine, it is marked as inactive by nulling its main procedure pointer.
 * It will later be destroyed by Sleep, as noted above; it cannot be destroyed
 * immediately because a task cannot discard its own stack.
 */
    static void				/* never returns */
stkbase (stack)
    Stack stack;			/*  current stack */
{

    /* Trouble if wrong stack. */
    if (stack != ego_->stk) {
	perror("Starting task");
	exit(ERR);
    }

    /* Execute main routine of task. */
    (*ego_->proc)(time(0));

    /* Task done:  Mark as inactive; decrement count; wait for destruction. */
    ego_->proc = (void (*)()) Null;
    taskcnt--;
    Sleep();

    /* Trouble if inactive task resumed. */
    perror("Destroying task");
    exit(ERR);
}

 unsigned long Stksize = 10000;		/* stack size */

/* Create a new task.
 */
    Task				/* returns new task id or null */
Newtask (proc, varb)
    void (*proc)();			/* main task procedure ptr */
    Ptr varb;				/* initial task variable value */
{
    Task task;				/* new task id (ptr to state) */

    /* Allocate memory for state of new task, */
    if (task = !proc ? (Task) Null : (Task) malloc(sizeof *task))

	/* Get it a stack; init its state; put it in list; count it. */
	if (task->stk = Crestk(stkbase, Stksize)) {
	    task->proc = proc;
	    task->varb = varb;
	    task->alarm = 0;
	    (task->bp = ego_->bp)->fp = task;
	    (task->fp = ego_)->bp = task;
	    taskcnt++;

	/* No stack:  Discard task state. */
	} else {
	    free(task);
	    task = (Task) Null;
	}

    /* Return new task id or, if failure, null. */
    return task;
}

/*
     *    * * *  *      * * *  * * *    *    *   *  * * *  * *          *     *
   * *    *      *      *        *    *   *  *   *  *      *   *      *     *
 * * * *  * *    *      * *      *    *      * * *  * *    * *    * * * * *
   * *    *      *      *        *    *   *  *   *  *      *   *      *     *
     *    *      * * *  * * *    *      *    *   *  * * *  *   *        *     *

 * Programmed by John G. Fletcher, who makes it available without any warranty
 * and maintains it on the basis of best effort, time as available.  No
 * organization or other person has any responsibility for it.

 * (C) Copyright 1992, the Regents of the University of California.  All Rights
 * Reserved.  This work was produced under the sponsorship of the U.S.
 * Department of Energy.  The Government retains certain rights therein.
 */
