/* stack.c */

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

#define ERR (~0)			/* error exit status */

/* Each stack is identified by a pointer that points to a structure that
 * contains its state.  The initial stack, on which exection is occurring
 * when the program begins, is an exception:  Although its state is also
 * kept in the same type of structure, its identifier is null.
 */
static struct stk_ stk0 /* = null */;	/* state of initial stack */
static Stack currstk = (Stack) Null;	/* currently executing stack id */
static int stkcnt = 1;			/* current number of stacks */

#if defined(CRAY)
/* On Unicos systems stacks are provided using the multitasking facility
 * (see "Multitasking Programmer's Manual").  Using Unicos tasks to provide
 * stacks is not the same as using them directly to provide tasking:  The
 * Unicos multitasking scheduler is constrained to run a single task chosen
 * by the Pads tasking module, and true parallelism is lost.  The reasons
 * that such is the current implementation include: (1) It is consistent
 * with the implementation on non-Unicos systems (as discussed below), and
 * (2) the Unicos library is not "parallelly safe".  The reason that setjmp/
 * longjmp is not used as it is on other systems is that Unicos stack
 * management is too complex; in particular, stacks may consist of many
 * discontiguous strands of "spaghetti".  However, setjmp/longjmp is used
 * to go to the bottom of a stack so that it can self-destruct by returning.
 */

static int exval;			/* exit value */
#undef _exit

/* Effect exit successfully.
 */
    void
exit_ (val)
    int val;				/* exit value */
{
    Stack stack;			/* stack id */

    /* Record exit value; switch to original stack. */
    exval = val;
    stk0.proc = exit_;
    Swistk((Stack) Null);
}

/* Begin execution on a new stack.
 */
    static void
newstk ()
{
    Stack stack;			/* stack id (ptr to state) */

    /* Get ptr to stack state; wait until scheduled for first time. */
    TSKVALUE((int *) &stack);
    EVWAIT(&stack->event);

    /* If not prematurely terminated, save state and run on new stack. */
    if (stack->proc)
	if (!setjmp(stack->jb)) {
	    (*stack->proc)(currstk = stack);

	    /* Main procedure of stack returned, contrary to specs. */
	    perror("Ending stack");
	    exit(ERR);
	}

    /* Later, destroy stack */
    return;
}

#else /* defined(CRAY) */
/* On non-Unicos systems stacks are multiplexed using the setjmp/longjmp
 * facility (see setjmp(3)).  Switching from stack to stack is accomplished
 * by saving the state of the current stack using setjmp and then restoring
 * the state of the next stack using longjmp.  This latter state is that
 * saved in an earlier stack switch or, in the case of a newly created stack
 * being switched to for the first time, is as initialized when the stack
 * was created.  Such initialization is effected by using setjmp to save
 * the state of the current stack in the jmp buffer to be associated with
 * the new stack and then appropriately modifying a few items in that buffer
 * (mainly the frame pointer and stack pointer) to refer to the new stack;
 * initial execution on the new stack begins following the setjmp.  The
 * appropriate modifications of the jmp buffer are system and machine
 * dependent and have been implemented for a number of systems and machines;
 * other systems and machines are limited to a single stack (and cannot
 * multitask).
*/

/* Modify the jmp buffer associated with a new stack so that the stack pointer
 * points to the bottom of that stack and the frame pointer is clear.  The
 * jmp buffer is an element of the structure pointed to by the stack id;
 * the stack itself follows that structure in memory, and its bottom is at
 * the end of that memory, word-aligned as necessary, since a stack grows
 * toward lower memory addresses.
 */
/*  macro statement
nullJ(stack, size)
    Stack stack;			   stack id (ptr to state)
    unsigned long size;			   size of stack */

#if defined(uts)
#   define nullJ(stack, size) { \
	(stack)->jb[10] = 0; \
	(stack)->jb[11] = (int) ((int *) ((Ptr) (stack) + ((size) & ~3))-17); \
    }
#else /* defined(uts) */
#endif /* defined(uts) */

#if defined(ultrix)
#if defined(mips)
#   define nullJ(stack, size) { \
	(stack)->jb[31] = 0; \
	(stack)->jb[32] = (int) ((int *) ((Ptr) (stack) + ((size) & ~3))-2); \
    }

#else /* defined(mips) */
#   define nullJ(stack, size) { \
	(stack)->jb[4] = 0; \
	(stack)->jb[2] &= ~0xE0000000; \
	(stack)->jb[0] = (int) ((int *) ((Ptr) (stack) + ((size) & ~3))-16); \
    }
#endif /* defined(mips) */
#else /* defined(ultrix) */
#endif /* defined(ultrix) */

#if defined(sun)
#if defined(sparc)
#   define nullJ(stack, size) { \
	(stack)->jb[_JBLEN] = 0; \
	(stack)->jb[2] = (int) ((int *) ((Ptr) (stack) + ((size) & ~7))-24); \
	memset((stack)->jb[2], 0, 23*sizeof(int)); \
    }

#else /* defined(sparc) */
#if defined(SUNOLD)
    /* Jmp buffers in version 4 of the Sun OS differ from those in earlier
     * versions.  No symbol is known that can be used to distinguish the
     * versions and select the correct macro; therefore the symbol chosen here,
     * SUNOLD, must be defined by the user for older versions.
     */
#   define nullJ(stack, size) { \
	(stack)->jb[13] = 0; \
	(stack)->jb[14] = (int) ((int *) ((Ptr) (stack) + ((size) & ~3))-2); \
    }

#else /* defined(SUNOLD) */
#   define nullJ(stack, size) { \
	(stack)->jb[15] = 0; \
	(stack)->jb[2] = (int) ((int *) ((Ptr) (stack) + ((size) & ~3))-2); \
    }
#endif /* defined(SUNOLD) */
#endif /* defined(sparc) */
#else /* defined(sun) */
#endif /* defined(sun) */

#if defined(THINK_C)
#   define nullJ(stack, size) { \
	(stack)->jb[9] = 0; \
	(stack)->jb[10] = (long) ((long *) ((Ptr) (stack) + ((size) & ~3))-2); \
    }
#else /* defined(THINK_C) */
#endif /* defined(THINK_C) */

/* Save the current state in the jmp buffer associated with a stack.  This
 * macro is essentially the same as setjmp but provides for certain system
 * and machine differences.
/*  macro int				   returns false, then later true
setJ(stack)
    Stack stack;			   stack id (ptr to state) */

#if defined(uts) || defined(THINK_C)
#if defined(THINK_C)
#else /* defined(THINK_C) */
    extern int setjmp();
#endif /* defined(THINK_C) */
#   define setJ(stack) setjmp((stack)->jb)

#else /* defined(uts) || defined(THINK_C) */
    extern int _setjmp();

#if defined(sparc)
    /* Experience has shown that on sparc systems setjmp/longjmp, as they are
     * used here, damage a word on the stack on unpredictable infrequent
     * occasions that are probably associated with some event (interrupt,
     * page fault, time slice?) occurring at a particular point in their
     * execution.  This macro, which uses "comma" expressions and other
     * less popular locutions in order that it be syntactically an expression,
     * compensates for such failures on the assumption that the first longjmp
     * of the program does no damage.  It relies on the observation that the
     * damaged word always differs from another, undamaged word by a constant
     * offset.
     */
    static int Jofs = -1;		/* frame ptr offset */
#   define setJ(stack) \
    (_setjmp((stack)->jb) \
	? Jofs >= 0 || (Jofs = \
	    (stk0.jb[_JBLEN] = ((unsigned int *) stk0.jb[2])[14]) \
		- stk0.jb[2], 1) \
	: ((stack)->jb[_JBLEN] = (stack)->jb[2] + Jofs, 0))

#else /* defined(sparc) */
#   define setJ(stack) _setjmp((stack)->jb)
#endif /* defined(sparc) */
#endif /* defined(uts) || defined(THINK_C) */

/* Restore the state saved in the jmp buffer associated with a stack.  This
 * macro is essentially the same as longjmp but provides for certain system
 * and machine differences.
/*  macro void				   never returns
longJ(stack)
    Stack stack;			   stack id (ptr to state) */

#if defined(uts) || defined(THINK_C)
#if defined(THINK_C)
#else /* defined(THINK_C) */
    extern void longjmp();
#endif /* defined(THINK_C) */
#   define longJ(stack) longjmp((stack)->jb, 1)

#else /* defined(uts) || defined(THINK_C) */
    extern void _longjmp();

#if defined(sparc)
    /* This macro repairs a possibly damaged word, as explained above in
     * regard to setjmp.
     */
#   define longJ(stack) \
    (((unsigned int *) (stack)->jb[2])[14] = (stack)->jb[_JBLEN], \
    _longjmp((stack)->jb, 1))

#else /* defined(sparc) */
#   define longJ(stack) _longjmp((stack)->jb, 1)
#endif /* defined(sparc) */
#endif /* defined(uts) || defined(THINK_C) */
#endif /* defined(CRAY) */

#if defined(THINK_C) || !defined(CRAY) && defined(Noheap) && Noheap
/* New stacks are normally allocated from the heap (i. e., using malloc and
 * free); such is always the case for Unicos, is never the case for
 * Macintoshes, and is otherwise optional.  The alternative is to allocate
 * new stacks from the end of the original stack by using the following
 * substitutes for malloc and free.  For the alternative all stacks are of the
 * same size, namely that requested for the first new stack.
 */

static Ptr stkmax = Null;		/* most extreme stack ptr */
static unsigned long stksiz;		/* stack size */
static Ptr stkfree = Null;		/* ptr to list of unused stacks */

/* Allocate a new block of stack memory.
 */
    static Ptr				/* returns stack memory ptr */
malloc (size)
    unsigned long size;			/* size to be allocated */
{
    Ptr stack;				/* allocated memory ptr */

    /* If first allocation, init. */
    if (!stkmax)
	stkmax = (Ptr) &stack - (stksiz = size & ~3);

    /* If unused stack available, use it. */
    if (stack = stkfree)
	stkfree = * (Ptr *) stack;

    /* Otherwise extend stack memory and use new extension. */
    else
	stack = stkmax -= stksiz;
    return stack;
}

/* Release a block of stack memory.
 */
    static void
free (memory)
    Ptr memory;				/* memory ptr */
{

    /* Put released block onto list of unused stacks. */
    * (Ptr *) memory = stkfree;
    stkfree = memory;
    return;
}
#else /* defined(THINK_C) || !defined(CRAY) && defined(Noheap) && Noheap */
#endif /* defined(THINK_C) || !defined(CRAY) && defined(Noheap) && Noheap */

/* Create a new stack.
 */
    Stack				/* returns id of new stack or null */
Crestk (proc, size)
    void (*proc)();			/* main stack procedure */
    unsigned long size;			/* stack size */
{
#if defined(CRAY)
    Stack stack;			/* new stack id (ptr to state) */

    /* If first stack creation, initialize state of original stack. */
    if (stk0.ctrl[0] == 0) {
	TSKTUNE("MAXCPU", &stkcnt);
	stk0.ctrl[0] = 3;
	EVASGN(&stk0.event);
	stk0.fp = stk0.bp = &stk0;
    }

    /* Allocate memory for and init state of new stack; count it; start it. */
    if (stack = (Stack) malloc(sizeof *stack)) {
	stack->ctrl[0] = 3;
	stack->ctrl[2] = (int) stack;
	EVASGN(&stack->event);
	(stack->bp = stk0.bp)->fp = stack,
	    (stack->fp = &stk0)->bp = stack;
	stack->proc = proc;
	stkcnt++;
	TSKSTART(stack, newstk);
    }

    /* Return new stack id or, if failure, null */
    return stack;

#else /* defined(CRAY) */
#if defined(nullJ)
    Stack stack;			/* new stack id (ptr to state) */

    /* Allocate memory for new stack and its state; init its state; count it. */
    if (size > sizeof *stack
	    && (stack = (Stack) malloc(size)))
	if (!setJ(stack)) {
	    nullJ(stack, size)
	    stack->proc = proc;
            stkcnt++;

	/* Later, execute on new stack.  */
	} else {
	    (*currstk->proc)(currstk);

	    /* Main procedure of stack returned, contrary to specs. */
	    perror("Ending stack");
	    exit(ERR);
	}

    /* Return new stack id or, if failure, null */
    return stack;

#else /* defined(nullJ) */

    /* New stacks not allowed:  Return null. */
    return (Stack) Null;
#endif /* defined(nullJ) */
#endif /* defined(CRAY) */
}

/* Switch control to another stack, returning later, when control is
 * switched back to the current stack.
 */
    Stack				/* returns current stack id */
Swistk (stack)
    Stack stack;			/* next stack id */
{
#if defined(CRAY)
    Stack savstk;			/* current stack id */

    /* If change in stack, block current stack and release next stack. */
    if (stack != (savstk = currstk)) {
	EVCLEAR(&(savstk ? savstk : &stk0)->event);
	EVPOST(&(stack ? stack : &stk0)->event);
	EVWAIT(&(savstk ? savstk : &stk0)->event);

	/* Later, if so indicated, go to bottom of stack to self-destruct. */
	if (savstk && !savstk->proc)
	    longjmp(savstk->jb, 1);
    }

    /* Exit if so indicated. */
    if (!(currstk = savstk) && stk0.proc) {
	while ((stack = stk0.fp) && stack != &stk0)
	    Dststk(stack);
	_exit(exval);
    }

    /* Return current stack id */
    return currstk;

#else /* defined(CRAY) */
#if defined(nullJ)
    Byte moat[4];			/* Prevents damage by signals
					   on some systems */

    /* If change in stack, save state of current stack. */
    if (stack != currstk
	    && !(currstk ? setJ(currstk) : setJ(&stk0)))

	/* Restore state of next stack. */
	if (currstk = stack)
	    longJ(currstk);
	else
	    longJ(&stk0);

    /* Later, return current stack id */
    return currstk;

#else /* defined(nullJ) */

    /* Trouble if next or current stack not the one and only stack. */
    if (stack || currstk) {
	perror("Switching stacks");
	exit(ERR);
    }

    /* Return current stack id */
    return (Stack) Null;
#endif /* defined(nullJ) */
#endif /* defined(CRAY) */
}

/* Destroy a stack.
 */
    Stack				/* returns null */
Dststk (stack)
    Stack stack;			/* next stack id */
{
#if defined(CRAY)

    /* Trouble if destroying current stack. */
    if (stack == currstk || stkcnt <= 1) {
	perror("Destroying stack");
	exit(ERR);
    }

    /* Signal, wait for self-destruction; release state; reduce stack count. */
    if (stack) {
	stack->proc = (void (*)()) Null;
	EVPOST(&stack->event);
	TSKWAIT(&stack->ctrl);
	EVREL(&stack->event);
	stack->fp->bp = stack->bp, stack->bp->fp = stack->fp;
	free((Ptr) stack);
    } else
	stk0.proc = exit_;
    stkcnt--;

    /* Return null */
    return (Stack) Null;

#else /* defined(CRAY) */
#if defined(nullJ)

    /* Trouble if destroying current stack. */
    if (stack == currstk || stkcnt <= 1) {
	perror("Destroying stack");
	exit(ERR);
    }

    /* Release stack and state; reduce stack count. */
    if (stack)
	free((Ptr) stack);
    else
	memset(&stk0, 0, sizeof stk0);
    stkcnt--;

    /* Return null */
    return (Stack) Null;

#else /* defined(nullJ) */

    /* Trouble if destroying one and only stack. */
    perror("Destroying stack");
    exit(ERR);
#endif /* defined(nullJ) */
#endif /* defined(CRAY) */
}

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

 * 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.
 */
