/*
        JView
        Frank Lyonnet 1993
        Module my_thread
*/

#include "kernel.h"
#include <stdlib.h>
#include <string.h>
#include "CRegs.h"
#include "Erreur.h"
#include "MyThread.h"

#define STACKCHUNKSIZE (4*1024)
#define STACK_MAGIC 0xf60690ff
#define STACK_LIMIT_OFFSET 560
#define STACK_FOOTER_SIZE 48

extern _kernel_registerset CallerCtx, CalledCtx;

my_thread my_thread_init(void *Fonction, void *Parm1, void *Parm2)
{
_kernel_stack_chunk *TheStack;

   if ((TheStack = malloc(STACKCHUNKSIZE)) == NULL)
      return (NULL);

   memcpy(TheStack, _kernel_current_stack_chunk(), STACK_FOOTER_SIZE);

   TheStack->sc_mark = STACK_MAGIC;
   TheStack->sc_next = NULL;
   TheStack->sc_prev = NULL;
   TheStack->sc_size = STACKCHUNKSIZE;
   TheStack->sc_deallocate = (int (*) ()) free;

   CalledCtx.regs[_a1] = (int) Parm1;
   CalledCtx.regs[_a2] = (int) Parm2;
   CalledCtx.regs[_sl] = (int) (((char *) TheStack) + STACK_LIMIT_OFFSET);
   CalledCtx.regs[_fp] = (int) NULL;
   CalledCtx.regs[_sp] = (int) (((char *) TheStack) + STACKCHUNKSIZE);
   CalledCtx.regs[_pc] = (int) Fonction;

   return (TheStack);
}

void my_thread_destroy(my_thread Thread)
{
_kernel_stack_chunk Old, *Stack;

   Stack = Thread;
   Old = *Stack;
   while (Stack != NULL)
   {
      Old.sc_deallocate(Stack);
      Stack = Old.sc_next;
      Old = *Stack;
   };
}
