#include "common.h"
#include "stdio.h"
#include "system.h"
#include "stdio.h"

#ifdef SIMHELPER_BASE
#include "soclib/simhelper.h"
#endif

static uint32_t lock;
static uint32_t nb_thread;

void system_start (void)
{
  lock_lock(&lock);
  nb_thread ++;
  lock_unlock(&lock);

  printf("CPU %d\n",procnum());
}

void system_stop (char* file, int line, int x)
{
  printf("Exit(%d) in file \"%s\", line %d\n",x,file,line);

  lock_lock(&lock);
  uint32_t num_thread = --nb_thread;
  lock_unlock(&lock);

  // Last thread ?
  if (num_thread == 0)
    {
#ifdef SIMHELPER_BASE
      soclib_io_set
        (base(SIMHELPER),
         SIMHELPER_SC_STOP,
         0);
#else
# warning "No simhelper, exit will do a trap and an infinite loop"
#endif
    }

  while(1);
}

