/*
 * RTL architecture-independent clock support
 *
 * 1999 Michael Barabanov <baraban@fsmlabs.com>
 *
 * Copyright (C) VJY Associates 1999
 */

#include <rtl_conf.h>
#include <errno.h>
#include <rtl_time.h>
#include <linux/time.h>

/* This is not really the right place but...*/
#ifndef CONFIG_RTL_ERRNO_THREADSAFE
int errno;
#endif

int rtl_setclockhandler (clockid_t h, clock_irq_handler_t fn)
{
	if (h -> handler != RTL_CLOCK_DEFAULTS.handler) {
		return -EBUSY;
	}
	h->handler = fn;
	return 0;
}

int rtl_unsetclockhandler (clockid_t h)
{
	if (h->handler == RTL_CLOCK_DEFAULTS.handler) {
		return -EINVAL;
	}
	h-> handler = RTL_CLOCK_DEFAULTS.handler;
	return 0;
}

static int definit (struct rtl_clock *c) { return 0; }
static void defuninit (struct rtl_clock *c) { return; }
static hrtime_t defgethrtime (struct rtl_clock *c) { return (hrtime_t) -1; }

static int defsethrtime(struct rtl_clock *c, hrtime_t t) {
	return -EINVAL;
}
static int defsettimer(struct rtl_clock *c, hrtime_t interval) { return -1; }
static int defsettimermode (struct rtl_clock *c, int mode) { return -1; }

static void default_handler( struct pt_regs *regs) { }


#define RTL_CLOCK_INITIALIZER { \
	definit, \
	defuninit, \
	defgethrtime, \
	defsethrtime, \
	defsettimer, \
	defsettimermode, \
	default_handler, \
	RTL_CLOCK_MODE_UNINITIALIZED, \
	0, \
	0, \
	0, \
	RTL_CLOCK_ARCH_INITIALIZER};


struct rtl_clock RTL_CLOCK_DEFAULTS = RTL_CLOCK_INITIALIZER;

struct rtl_clock clock_ust = RTL_CLOCK_INITIALIZER;
struct rtl_clock clock_realtime = RTL_CLOCK_INITIALIZER;

hrtime_t ust_gethrtime(struct rtl_clock *c)
{
	return gethrtime();
}

/* TODO make it SMP-safe */
hrtime_t realtime_gethrtime(struct rtl_clock *c)
{
	return gethrtime() + c->delta;
}

#include <rtl_debug.h>
#include <rtl_core.h>

/* TODO make it SMP-safe */
int rtl_clockadjust (clockid_t clock_id, hrtime_t delta)
{
	clock_id->delta = ((clock_id->delta << 3) - clock_id->delta + delta) >> 3;
/* 	do_every(1000) { */
/* 		rtl_printf("%d ", (int) clock_id->delta); */
/* 	} end_do_every; */

	return 0;
}

clockid_t CLOCK_UST = &clock_ust;
clockid_t CLOCK_REALTIME = &clock_realtime;
static int clock_rt_irq;

static void clock_irq_handler (int irq, void *dev_id, struct pt_regs *p)
{
	struct timeval tv;
	hrtime_t now = clock_gethrtime(CLOCK_REALTIME);
	do_gettimeofday(&tv);
	rtl_clockadjust(CLOCK_REALTIME, tv.tv_sec * (long long) NSECS_PER_SEC + tv.tv_usec * 1000 - now);
}

int rtl_init_standard_clocks(void)
{
	clock_ust.gethrtime = &ust_gethrtime;
	clock_ust.resolution = gethrtimeres();
	clock_realtime.gethrtime = &realtime_gethrtime;
	clock_realtime.resolution = gethrtimeres();
	clock_rt_irq = rtl_get_soft_irq (clock_irq_handler, "RTL-clock");
	return 0;
}

void rtl_cleanup_standard_clocks(void)
{
	rtl_free_soft_irq (clock_rt_irq);
}
