#include <sched.h>
#include "ezt_submodule.h"
#include "eztrace_sampling.h"

static int __ezt_use_getcpu = 0;

struct cpu_info {
  int last_cpu;
};

int ezt_getcpu_callback(struct ezt_sampling_callback_instance *instance) {
  struct cpu_info* p = NULL;

  if(!instance->plugin_data) {
    /* first time this thread calls this callback.
     * Let's allocate data
     */
    p = malloc(sizeof(struct cpu_info));
    p->last_cpu = -1;
    instance->plugin_data = p;
  }

  p = instance->plugin_data;

  /* todo: use getcpu instead (getcpu also returns NUMA-related information) */
  int cur_cpu = sched_getcpu();
  if(cur_cpu != p->last_cpu) {
    EZTRACE_EVENT1(EZT_GETCPU, cur_cpu);
  }
  p->last_cpu = cur_cpu;
  return 0;
}


/* initialize the ezt_getcpu module */
void ezt_getcpu_init() {
  static int initialized = 0;
  if(initialized)
    return;

  initialized = 1;

  char* str = getenv("EZTRACE_USE_GETCPU");
  if(str) {
    if(strcmp(str, "0")) {
      char* str2 = getenv("EZTRACE_GETCPU_INTERVAL");
      int interval = 10000;

      if(str2) {
	interval = atoi(str2);
      }
      __ezt_use_getcpu = 1;

      printf("[EZTrace] module getcpu enabled (sampling every %d us)\n", interval);
      ezt_sampling_register_callback(ezt_getcpu_callback, interval);
    }
  }
}
