/*
Copyright 2003/2004, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.
Contributors: Thomas Pietsch, Bjoern Lichtblau

For documentation and questions please use the web site
http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

#include "ScatterWeb.System.h"
#include "ScatterWeb.Threading.h"

#define T_DESTROYED   (0)       ///< Initial state of whole task table and after return of a task, task is not valid!
#define T_ELIGIBLE    (1)       ///< Task is eligible to run. Initial state after adding a new task, a ::scos_yield or an expired ::scos_wait.
#define T_WAITING     (2)       ///< Task is waiting for a timeout with a scos_wait.
#define T_RECV        (3)       ///< Task is waiting for a packet.
#define T_RECVP       (4)       ///< Task is waiting for a packet in promiscous mode.
#define T_SEND        (5)       ///< Task is sending a packet blocking.
#define T_AWAIT       (6)       ///< Task is awaiting a specific state.
#define T_TRECV       (7)       ///< Task is waiting for a packet with timeout.
#define T_TRECVP      (8)
#define NAKEDFUNC __attribute__((naked))

volatile UINT16 nextTask;    ///< Used by scos_heartbeat to go round robin over all tasks (except sending & receiving).
volatile UINT16 currentTask; ///< Always set to currentTask by ::scos_call.
volatile UINT16 savedSP;     ///< Saved stack pointer in ::scos_call.
volatile UINT16 Threading_currentThread;

typedef struct {
  UINT16 address;   ///< Next address to continue for this task, initialized with function address of a new task.
  UINT16 stackSize;
  UINT16 state;     ///< Current state of the task.
  struct {
    UINT8* adr;
    UINT8 value;
  } AWAIT;
} Task; ///< Task table struct.

volatile Task Tasks[MAX_TASKS];    ///< Task table.

#define UPDATE_TT(newstate) \
  if(savedSP==0){ \
    Comm_print("Invalied call to OS_* function from %x\r\n", (*(((UINT16*)frame_adr))) - 4); \
    return 0; \
  } \
  Tasks[currentTask].address = *(((UINT16*)frame_adr)); \
  Tasks[currentTask].state = newstate; \
  Tasks[currentTask].stackSize = (savedSP - frame_adr) - 4;

void _destroy_task() {
  Tasks[currentTask].address = 0x0000;
  Tasks[currentTask].state = T_DESTROYED;
  savedSP = 0;  // clear saved stack pointer
}

NAKEDFUNC void scos_prolog(UINT16 value, UINT16 address, UINT16 stackoffset) {
  // Subtract stack space of the task from the stack.
  __asm__ __volatile__("sub %0, r1":: "r" (stackoffset));
  // Fake set return value for function, not needed as value lands in here on r15 as first argument.
  //__asm__ __volatile__("mov %0, r15":: "r" (value): "r15");
  // Now do a branch to that location
  __asm__ __volatile__("br %0":: "r" (address)); // save stack pointer  
}

NAKEDFUNC void scos_call(UINT16 task, UINT16 value) {
  __asm__ __volatile__("mov r1, &savedSP"::: "memory"); // save stack pointer
  currentTask = task;
  Threading_currentThread = task;
  scos_prolog(value, Tasks[currentTask].address, Tasks[currentTask].stackSize);
  // If this call returns to the scheduler this task has ended with a return.
  _destroy_task();
  __asm__ __volatile__("ret"::);
}

NAKEDFUNC void scos_return(void) {
  __asm__ __volatile__("mov &savedSP, r1"::); // restore stack pointer
  savedSP = 0;  // clear saved stack pointer
  __asm__ __volatile__("ret"::);              // Looks now like the return in scos_call.
}

COMMAND(sco, SERIALONLY) {
  UINT16 i;
  Comm_print("Nr\tAdr\tState\tStack\r\n");
  for(i=0; i<MAX_TASKS; i++){
    if(Tasks[i].address != 0) Comm_print("%i\t%x\t%i\t%i\r\n", i, Tasks[i].address, Tasks[i].state, Tasks[i].stackSize);
    else                      Comm_print("%i\t ---\r\n", i);
  }
}

void _scos_wait_timeout(UINT16 data) {
  Tasks[data].state = T_ELIGIBLE;
  runModule |= MF_SCOS;
}

bool Threading_init() {
  UINT16 i;
  for(i=0; i<MAX_TASKS; i++){
    Tasks[i].address = 0x0000;
    Tasks[i].state = T_DESTROYED;
    Tasks[i].stackSize = 0;
  }
  currentTask = 0;
  nextTask = 0;
  savedSP = 0;
  return True;
}

bool Threading_add(void* address) {
    UINT16 i;
    for(i=0; i<MAX_TASKS; i++) if(Tasks[i].state == T_DESTROYED) break;
    if(i<MAX_TASKS){ // found an empty place
      Tasks[i].address = (UINT16) address;
      Tasks[i].state = T_ELIGIBLE;
      Tasks[i].stackSize = 0;
      runModule |= MF_SCOS;
      return True;
    }
    else return False; 
}

bool Threading_eventHandler() {
  UINT16 i;
  // search from nextTask+1 to end.
  for(i=nextTask+1; i<MAX_TASKS; i++) {
    if(Tasks[i].state == T_ELIGIBLE ||
       (Tasks[i].state == T_AWAIT && (*(Tasks[i].AWAIT.adr) == Tasks[i].AWAIT.value))
    ){
      nextTask = i;
      goto found;
    }
  }
  // search from 0 to nextTask
  for(i=0; i<=nextTask; i++) {
    if(Tasks[i].state == T_ELIGIBLE ||
       (Tasks[i].state == T_AWAIT && (*(Tasks[i].AWAIT.adr) == Tasks[i].AWAIT.value))
    ){
      nextTask = i;
      goto found;
    }
  }
  goto exit;  // If none was found exit routine.
  // Execute at given addres of the task. Casting that address to
  // a function with an uint argument does imitate a return value
  // of tasks previous call to a scos_ function.
  found:  
  scos_call(nextTask, 1); 
  return True;  
  exit:   
  runModule &= ~ MF_SCOS;
  return True;
}

bool Threading_doEvents() {
  UINT16 frame_adr = GET_FRAME_ADDR(Threading_doEvents);
  UPDATE_TT(T_ELIGIBLE);   // Nothing more to do here, Tasks stays T_ELIGIBLE.
  runModule |= MF_SCOS;
  scos_return();
  return True;
}

bool Threading_sleep(UINT16 ticks) {
  UINT16 frame_adr = GET_FRAME_ADDR(Threading_sleep);
  UPDATE_TT(T_WAITING);
  Timers_add(ticks, _scos_wait_timeout, currentTask);
  scos_return();
  return True;
}

bool Threading_wait(UINT8* adr, UINT8 value) {
  UINT16 frame_adr = GET_FRAME_ADDR(Threading_wait);
  UPDATE_TT(T_AWAIT);
  Tasks[currentTask].AWAIT.adr = (UINT8*) adr;
  Tasks[currentTask].AWAIT.value = value;
  scos_return();
  return True;
}
