#include <time.h>
#include <errno.h>
#include <sys/lock.h>
#include "mapping_memory.h"
#include "sim2os.h"
#include "service_clock.h"

unsigned int service_clock ()
{
  unsigned int * addr   = (unsigned int *)(SIM2OS_BASE);
  unsigned int   result = -1;

  __lock_init    (service_lock);
  
  __lock_acquire (service_lock);

  *(addr+0) = (unsigned int)SERVICE_CLOCK;
 
  // memory synchronisation
  // (else read (with an address that depend not of store address) can be lunch before a store)
  asm("l.msync;");

  result    = (clock_t) *(addr+1);
 
  if (result == (clock_t)-1)
    errno = (int) *(addr+2);

  __lock_release (service_lock);

  return result;
}
