/* Tasking for language L8 (Ada 2022's Jorvik profile, plan T27): library-level tasks as
 * POSIX threads, activated together once library elaboration is over; protected objects as a
 * mutex and a condition variable each (a protected action holds the mutex, an entry waits on
 * the condition until its barrier is open, and every action that may open a barrier wakes the
 * waiters); `delay until` on the monotonic clock. macOS gives user programs no real-time
 * priorities, so priorities and ceilings order nothing here, as with GNAT there. */
/* glibc hides POSIX's functions under -std=c11 unless asked (macOS ignores this) */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE
#endif
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "veradart.h"

/* Tasks and protected objects are as many as the program declares (D185): each table is
 * blocks of 64, 128, 256, ... entries, made as they are needed and never moved (a thread may
 * use one entry while another is made), found by their number. */
#define BLOCKS 48

/* the block and the place in it of entry i: block b holds entries 64 (2**b - 1) on */
static int block_of(int64_t i, int64_t *place) {
  int b = 63 - __builtin_clzll((uint64_t)(i / 64 + 1));
  *place = i - 64 * (((int64_t)1 << b) - 1);
  return b;
}

/* entry i of a table of blocks of entries of `size` bytes, made (zeroed) when it is new */
static void *entry(void **blocks, int64_t i, size_t size) {
  int64_t place;
  int b = block_of(i, &place);
  if (b >= BLOCKS) {
    verada_rt_storage_error("no memory for another task or protected object");
  }
  if (blocks[b] == NULL) {
    blocks[b] = calloc((size_t)64 << b, size);
    if (blocks[b] == NULL) {
      verada_rt_storage_error("no memory for another task or protected object");
    }
  }
  return (char *)blocks[b] + (size_t)place * size;
}

static void *task_blocks[BLOCKS];
static int64_t task_count = 0;

static pthread_t *task_at(int64_t i) { return entry(task_blocks, i, sizeof(pthread_t)); }
static pthread_mutex_t activation = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t activated = PTHREAD_COND_INITIALIZER;
static bool active = false;

/* Stop: set once every task is to end. A task ends at a cancellation point (a delay, an entry
 * or suspension wait) and, so that one that computes without ever reaching one ends too, at
 * every loop iteration (verada_rt_stop_point, which the code calls at each loop's back edge
 * when the program has tasks), unless it is inside a protected action: it ends there with the
 * object's lock free, so that the main subprogram can still use the object. Asynchronous
 * cancellation would end a task anywhere, holding a lock or inside malloc. */
static volatile bool stopping = false;
static _Thread_local bool in_task = false;
static _Thread_local int locks_held = 0;

/* a protected object's lock, and a suspension object's state (Ada.Synchronous_Task_Control:
 * the object itself may be copied, as an `in out` record is, so its state lives here) */
struct lock {
  pthread_mutex_t mutex;
  pthread_cond_t change;
  bool suspended;
};

static void *lock_blocks[BLOCKS];
static int64_t lock_count = 0;

static struct lock *lock_at(int64_t i) { return entry(lock_blocks, i, sizeof(struct lock)); }

/* A task's thread: it waits for activation, then runs its body (which does not end, in
 * Jorvik). */
static void *run_task(void *argument) {
  void (*body)(void) = (void (*)(void))argument;
  pthread_mutex_lock(&activation);
  while (!active) {
    pthread_cond_wait(&activated, &activation);
  }
  pthread_mutex_unlock(&activation);
  in_task = true;
  body();
  return NULL;
}

/* At each loop iteration of a program with tasks: a task ends here once Stop was called. */
void verada_rt_stop_point(void) {
  if (stopping && in_task && locks_held == 0) {
    pthread_exit(NULL);
  }
}

/* Called by the elaboration of the package body that holds the task's body. */
void verada_rt_task_start(void (*body)(void)) {
  if (pthread_create(task_at(task_count), NULL, run_task, (void *)body) != 0) {
    verada_rt_storage_error("a task's thread could not be made");
  }
  task_count++;
}

/* After library elaboration, before the main subprogram: every task begins. */
void verada_rt_tasks_activate(void) {
  stopping = false;
  pthread_mutex_lock(&activation);
  active = true;
  pthread_cond_broadcast(&activated);
  pthread_mutex_unlock(&activation);
}

/* Interrupt handlers (Ada.Interrupts, G8): an interrupt is a POSIX signal; its handler's
 * thread waits, after activation, for the signal handler to say it occurred (through a pipe,
 * which a signal handler may write), and calls the protected procedure, which takes its lock.
 * The program does not wait for these threads: they end with it. */
/* (one handler for each signal at most: POSIX numbers them below 64) */
#define MAX_HANDLERS 64
static pthread_t handler_threads[MAX_HANDLERS];
static int handler_signals[MAX_HANDLERS];
static int handler_count = 0;
static int signal_pipes[64][2];

/* Verada's interrupt numbers are POSIX's, but for SIGUSR1 and SIGUSR2, 30 and 31 (macOS's). */
static int native_signal(int64_t interrupt) {
  switch (interrupt) {
  case 30:
    return SIGUSR1;
  case 31:
    return SIGUSR2;
  default:
    return interrupt > 0 && interrupt < 64 ? (int)interrupt : -1;
  }
}

static void on_signal(int sig) {
  if (sig > 0 && sig < 64) {
    char c = 0;
    ssize_t written = write(signal_pipes[sig][1], &c, 1);
    (void)written;
  }
}

struct handler_job {
  int sig;
  void (*handler)(void);
};

static void *run_handler(void *argument) {
  struct handler_job job = *(struct handler_job *)argument;
  free(argument);
  pthread_mutex_lock(&activation);
  while (!active) {
    pthread_cond_wait(&activated, &activation);
  }
  pthread_mutex_unlock(&activation);
  for (;;) {
    char c;
    if (read(signal_pipes[job.sig][0], &c, 1) == 1) {
      job.handler();
    }
  }
  return NULL;
}

bool verada_rt_attach_handler(int64_t interrupt, void (*handler)(void)) {
  int sig = native_signal(interrupt);
  if (sig <= 0 || sig >= 64 || handler_count == MAX_HANDLERS) {
    verada_rt_storage_error("an interrupt handler could not be attached");
  }
  if (pipe(signal_pipes[sig]) != 0) {
    verada_rt_storage_error("an interrupt handler could not be attached");
  }
  struct handler_job *job = malloc(sizeof *job);
  if (job == NULL) {
    verada_rt_storage_error("an interrupt handler could not be attached");
  }
  job->sig = sig;
  job->handler = handler;
  struct sigaction action;
  memset(&action, 0, sizeof action);
  action.sa_handler = on_signal;
  sigemptyset(&action.sa_mask);
  action.sa_flags = SA_RESTART;
  sigaction(sig, &action, NULL);
  if (pthread_create(&handler_threads[handler_count], NULL, run_handler, job) != 0) {
    verada_rt_storage_error("an interrupt handler's thread could not be made");
  }
  handler_signals[handler_count] = sig;
  handler_count++;
  return true;
}

/* The interrupt handlers end with the program: their threads stop, their signals are reset. */
static void detach_handlers(void) {
  for (int i = 0; i < handler_count; i++) {
    pthread_cancel(handler_threads[i]);
    pthread_join(handler_threads[i], NULL);
    signal(handler_signals[i], SIG_DFL);
    close(signal_pipes[handler_signals[i]][0]);
    close(signal_pipes[handler_signals[i]][1]);
  }
  handler_count = 0;
}

/* After the main subprogram: the program goes on as long as its tasks do (RM 10.2(25)). */
void verada_rt_tasks_await(void) {
  for (int64_t i = 0; i < task_count; i++) {
    if (!pthread_equal(*task_at(i), pthread_self())) {
      pthread_join(*task_at(i), NULL);
    }
  }
  task_count = 0;
  detach_handlers();
  active = false;
}

/* Verada.Tasking.Stop: every other task ends, and so does the calling one (when it is a task),
 * so the program ends once its main subprogram has returned. */
void verada_rt_tasks_stop(void) {
  stopping = true;
  bool calling_task = false;
  for (int64_t i = 0; i < task_count; i++) {
    if (pthread_equal(*task_at(i), pthread_self())) {
      calling_task = true;
    } else {
      pthread_cancel(*task_at(i));
    }
  }
  if (!calling_task) {
    detach_handlers();
  }
  if (calling_task) {
    pthread_exit(NULL);
  }
}

/* A protected object's lock (a mutex and a condition variable), made at its elaboration. */
int64_t verada_rt_lock_new(void) {
  struct lock *l = lock_at(lock_count);
  pthread_mutex_init(&l->mutex, NULL);
  pthread_cond_init(&l->change, NULL);
  return lock_count++;
}

void verada_rt_lock(int64_t lock) {
  pthread_mutex_lock(&lock_at(lock)->mutex);
  locks_held++;
}

void verada_rt_unlock(int64_t lock) {
  locks_held--;
  pthread_mutex_unlock(&lock_at(lock)->mutex);
}

static void unlock_on_cancel(void *lock) { pthread_mutex_unlock((pthread_mutex_t *)lock); }

/* An entry whose barrier is closed waits, without the lock, until an action changes the
 * object (a task stopped while waiting gives the lock back). */
void verada_rt_lock_wait(int64_t lock) {
  pthread_cleanup_push(unlock_on_cancel, &lock_at(lock)->mutex);
  pthread_cond_wait(&lock_at(lock)->change, &lock_at(lock)->mutex);
  pthread_cleanup_pop(0);
}


void verada_rt_suspension_set(int64_t lock, bool state) {
  pthread_mutex_lock(&lock_at(lock)->mutex);
  lock_at(lock)->suspended = state;
  pthread_cond_broadcast(&lock_at(lock)->change);
  pthread_mutex_unlock(&lock_at(lock)->mutex);
}

bool verada_rt_suspension_state(int64_t lock) {
  pthread_mutex_lock(&lock_at(lock)->mutex);
  bool state = lock_at(lock)->suspended;
  pthread_mutex_unlock(&lock_at(lock)->mutex);
  return state;
}

void verada_rt_suspension_wait(int64_t lock) {
  pthread_mutex_lock(&lock_at(lock)->mutex);
  pthread_cleanup_push(unlock_on_cancel, &lock_at(lock)->mutex);
  while (!lock_at(lock)->suspended) {
    pthread_cond_wait(&lock_at(lock)->change, &lock_at(lock)->mutex);
  }
  lock_at(lock)->suspended = false;
  pthread_cleanup_pop(0);
  pthread_mutex_unlock(&lock_at(lock)->mutex);
}

/* At the end of every protected procedure and entry: the barriers may have opened. */
void verada_rt_lock_notify(int64_t lock) { pthread_cond_broadcast(&lock_at(lock)->change); }

/* Ada.Real_Time.Clock: nanoseconds on the monotonic clock. */
int64_t verada_rt_clock(void) {
  struct timespec now;
  clock_gettime(CLOCK_MONOTONIC, &now);
  return (int64_t)now.tv_sec * 1000000000 + now.tv_nsec;
}

static void sleep_for(int64_t nanoseconds) {
  if (nanoseconds <= 0) {
    return;
  }
  struct timespec span = {.tv_sec = nanoseconds / 1000000000, .tv_nsec = nanoseconds % 1000000000};
  while (nanosleep(&span, &span) == -1 && errno == EINTR) {
  }
}

/* `delay until T`: until the monotonic clock reaches T (nanoseconds). */
void verada_rt_delay_until(int64_t time) { sleep_for(time - verada_rt_clock()); }

/* `delay D`: for D (nanoseconds). */
void verada_rt_delay_for(int64_t nanoseconds) { sleep_for(nanoseconds); }
