/* $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred.
 */

#ident	"$Header: kern_time.c 1.35 90/05/03 $"

/*
 * kern_time.c
 *	Time of day and interval timer support.
 *
 * These routines provide the kernel entry points to get and set
 * the time-of-day and per-process interval timers.  Subroutines
 * here provide support for adding and subtracting timeval structures
 * and decrementing interval timers, optionally reloading the interval
 * timers when they expire.
 */

/* $Log:	kern_time.c,v $
 */


#include "sys/types.h"
#include "sys/devsw.h"
#include "sys/param.h"
#include "sys/debug.h"
#include "sys/reg.h"
#include "sys/signal.h"
#include "sys/systm.h"
#include "sys/mutex.h"
#include "sys/conf.h"
#include "sys/user.h"
#include "sys/errno.h"
#include "sys/timer.h"
#include "sys/proc.h"

#include "sys/intctl.h"
#include "sys/gate.h"

#include "sys/times.h"

#ifdef DEBUG
extern int	sig_debug;
#endif

/*
 * return time in seconds since epoch.
 */
gtime()
{
	extern unsigned sec0eaddr;

	u.u_r.r_time = time.tv_sec;

	/* Return # of users (value in R1 on return from gtime) */
	u.u_r.r_val2 = sec0eaddr;
}

/*
 * SVR3 times - return struct tms - 4 clock_t values.
 */
#define EX_TICKS(X)	((X.tv_sec*HZ)+(X.tv_usec*HZ/1000000))

times()
{
	register struct	a {
		clock_t	(*times)[4];
	} *uap;
	struct	tms 		tms;
	timeval_t		t_bolt;
	extern	timeval_t	time;
	extern	timeval_t	boottime;

	uap = (struct a *)u.u_ap;

	tms.tms_utime = EX_TICKS(u.u_pst.ps_utime);
	P_GATE(G_TIME);
	tms.tms_stime = EX_TICKS(u.u_pst.ps_stime);
	t_bolt = time;
	V_GATE(G_TIME);
	tms.tms_cutime = EX_TICKS(u.u_cpst.ps_utime);
	tms.tms_cstime = EX_TICKS(u.u_cpst.ps_stime);
	timevalsub(&t_bolt,&boottime);
#ifdef DEBUG
#ifdef notdef
printf("tms_cstime = %d,%d\n",u.u_cpst.ps_stime.tv_sec,u.u_cpst.ps_stime.tv_usec);
#endif
#endif /*DEBUG*/
	if (copyout((caddr_t)&tms, (caddr_t)uap->times, sizeof(*uap->times)))
		u.u_error = EFAULT;
	u.u_r.r_time = EX_TICKS(t_bolt);
}

stime()
{
	register struct a {
		time_t	time;
	} *uap = (struct a *)u.u_ap;
	timeval_t atv;

	atv.tv_sec = (time_t)uap->time;
	atv.tv_usec = (time_t)0;
	setthetime(&atv, 1);
}

/* called by stime (above) and sysi86(STIME) */
setthetime(tv, flag)
	timeval_t *tv;
	int	  flag;			/* update todr if flag is set */
{
	if (!suser())
		return;
/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
	boottime.tv_sec += tv->tv_sec - time.tv_sec;
	P_GATE(G_TIME); time = *tv; V_GATE(G_TIME);
	if (flag)
		FW_RESETTODR();
}


/*
 * Real interval timer expired:
 * send process whose timer expired an alarm signal.
 * If time is not set up to reload, then just return.
 * Else compute next time timer should go off which is > current time.
 * This is where delay in processing this timeout causes multiple
 * SIGALRM calls to be compressed into one.
 */
realitexpire(p)
	register struct proc *p;
{
	psignal(p, SIGALRM);
	if (!timerisset(&p->p_realtimer.it_interval)) {
		timerclear(&p->p_realtimer.it_value);
		return;
	}
	for (;;) {
		P_GATE(G_TIME);
		timevaladd(&p->p_realtimer.it_value,
		    &p->p_realtimer.it_interval);
		if (timercmp(&p->p_realtimer.it_value, &time, >)) {
			p->p_rtid = ltimeout(realitexpire, (caddr_t)p,
			    hzto(&p->p_realtimer.it_value));
			V_GATE(G_TIME);
			return;
		}
		V_GATE(G_TIME);
	}
}


/*
 * Add and subtract routines for timevals.
 * N.B.: subtract routine doesn't deal with
 * results which are before the beginning,
 * it just gets very confused in this case.
 * Caveat emptor.
 */
timevaladd(t1, t2)
	timeval_t *t1, *t2;
{

	t1->tv_sec += t2->tv_sec;
	t1->tv_usec += t2->tv_usec;
	timevalfix(t1);
}

timevalsub(t1, t2)
	timeval_t *t1, *t2;
{

	t1->tv_sec -= t2->tv_sec;
	t1->tv_usec -= t2->tv_usec;
	timevalfix(t1);
}

timevalfix(t1)
	timeval_t *t1;
{

	if (t1->tv_usec < 0) {
		t1->tv_sec--;
		t1->tv_usec += 1000000;
	}
	if (t1->tv_usec >= 1000000) {
		t1->tv_sec++;
		t1->tv_usec -= 1000000;
	}
}


/*
 * SVR3 Alarm system call
 */
alarm()
{
	register struct	a {
		int	deltat;
	} *uap;
	struct	itimerval 	aotv;
	struct	itimerval 	aitv;

	uap = (struct a *)u.u_ap;
	aitv.it_value.tv_sec = uap->deltat;
	aitv.it_value.tv_usec = 0;
	aitv.it_interval.tv_sec = 0;
	aitv.it_interval.tv_usec = 0;

	calarm(&aitv, &aotv);

	u.u_r.r_val1 = aotv.it_value.tv_sec;
	if (aotv.it_value.tv_usec)
		u.u_r.r_val1 += 1;
}

/*
 * Arrange for a wakeup "*itv" amount of time from now.
 * Return the time to the current unexpired wakeup (if any) in "*otv".
 */
calarm(itv, otv)
register struct itimerval *itv, *otv;
{
	register struct proc	*p = u.u_procp;
	bool_t	sigalrm = 0;			/* should post a SIGALRM? */
	int	s;
	extern	lock_t	time_lck;		/* see untimeout */

#ifdef	ns32000
	s = drp_lock(&time_lck);
#endif	/* ns32000  */
#ifdef	i386
	s = p_lock(&time_lck, SPLHI);
	VOID_P_GATE(G_TIME);
#endif	/* i386  */
	/*
	 * Get current value and save away.
	 */
	*otv = p->p_realtimer;

	/*
	 * convert absolute time back to a delta for the return value.
	 */
	if (timerisset(&otv->it_value)) {
		if (timercmp(&otv->it_value, &time, <))
			timerclear(&otv->it_value);
		else
			timevalsub(&otv->it_value, &time);
	}

	/*
	 * Handle race where setitimer occurs between todclock()
	 * and softclock(). That is, if the timer expires and
	 * the untimeout occurs before the timeout event sends
	 * the SIGALRM.
	 */
	if (luntimeout(p->p_rtid)) {
		if (otv->it_value.tv_sec==0 && otv->it_value.tv_usec==0)
			++sigalrm;
	}
	if (timerisset(&itv->it_value)) {
		timevaladd(&itv->it_value, &time);
		p->p_rtid = ltimeout(realitexpire,(caddr_t)p, hzto(&itv->it_value));
	}
	p->p_realtimer = *itv;
	V_GATE(G_TIME);
	v_lock(&time_lck, s);
	/*
	 * If needed, post a SIGALRM.  Done here to avoid nesting gates/locks.
	 */
	if (sigalrm)
		psignal(p, SIGALRM);
}

/*
 * Get value of an interval timer.  The process virtual and
 * profiling virtual time timers are kept in the u. area, since
 * they can be swapped out.  These are kept internally in the
 * way they are specified externally: in time until they expire.
 *
 * The real time interval timer is kept in the process table slot
 * for the process, and its value (it_value) is kept as an
 * absolute time rather than as a delta, so that it is easy to keep
 * periodic real-time signals from drifting.
 *
 * Virtual time timers are processed in the hardclock() routine of
 * kern_clock.c.  The real time timer is processed by a timeout
 * routine, called from the softclock() routine.  Since a callout
 * may be delayed in real time due to interrupt processing in the system,
 * it is possible for the real time timeout routine (realitexpire, given below),
 * to be delayed in real time past when it is supposed to occur.  It
 * does not suffice, therefore, to reload the real timer .it_value from the
 * real time timers .it_interval.  Rather, we compute the next time in
 * absolute time the timer should go off.
 *
 * The gate G_TIME synchronizes with the todclock.
 * The splhi synchronizes with the local hardclock in the 
 * virtual timer and profiling timer.
 */
getitimer()
{
	register struct a {
		uint	which;
		struct	itimerval *itv;
	} *uap = (struct a *)u.u_ap;
	struct itimerval aitv;
	spl_t s;

	if (uap->which > 2) {
		u.u_error = EINVAL;
		return;
	}
	if (uap->which == ITIMER_REAL) {
		/*
		 * Convert from absolute to relative time in .it_value
		 * part of real time timer.  If time for real time timer
		 * has passed return 0, else return difference between
		 * current time and time for the timer to go off.
		 */
		P_GATE(G_TIME);
		aitv = u.u_procp->p_realtimer;
		if (timerisset(&aitv.it_value)) {
			if (timercmp(&aitv.it_value, &time, <))
				timerclear(&aitv.it_value);
			else
				timevalsub(&aitv.it_value, &time);
		}
		V_GATE(G_TIME);
	} else {
		s = splhi();
		aitv = u.u_timer[uap->which];
		splx(s);
	}
	u.u_error = copyout((caddr_t)&aitv, (caddr_t)uap->itv,
	    sizeof (struct itimerval));
}

setitimer()
{
	register struct a {
		uint	which;
		struct	itimerval *itv, *oitv;
	} *uap = (struct a *)u.u_ap;
	int	s;
	struct	itimerval aitv, aotv;

	if (uap->which > 2) {
		u.u_error = EINVAL;
		return;
	}
	u.u_error = copyin((caddr_t)uap->itv, (caddr_t)&aitv,
						sizeof (struct itimerval));
	if (u.u_error)
		return;

	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval)) {
		u.u_error = EINVAL;
		return;
	}

	if (uap->which == ITIMER_REAL) {
		calarm(&aitv, &aotv);
	} else {
		s = splhi();
		if (uap->oitv) {
			aotv = u.u_timer[uap->which];
		}
		u.u_timer[uap->which] = aitv;
		splx(s);
	}

	/*
	 * Now copy out previous value.
	 */
	if (uap->oitv) {
		u.u_error = copyout((caddr_t)&aotv, (caddr_t)uap->oitv,
						sizeof (struct itimerval));
	}
}

/*
 * Check that a proposed value to load into the .it_value or
 * .it_interval part of an interval timer is acceptable, and
 * fix it to have at least minimal value (i.e. if it is less
 * than the resolution of the clock, round it up.)
 */
itimerfix(tv)
	timeval_t *tv;
{

	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
		return (EINVAL);
	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
		tv->tv_usec = tick;
	return (0);
}

/*
 * Decrement an interval timer by a specified number
 * of microseconds, which must be less than a second,
 * i.e. < 1000000.  If the timer expires, then reload
 * it.  In this case, carry over (usec - old value) to
 * reducint the value reloaded into the timer so that
 * the timer does not drift.  This routine assumes
 * that it is called in a context where the timers
 * on which it is operating cannot change in value.
 */
itimerdecr(itp, usec)
	register struct itimerval *itp;
	int usec;
{

	if (itp->it_value.tv_usec < usec) {
		if (itp->it_value.tv_sec == 0) {
			/* expired, and already in next interval */
			usec -= itp->it_value.tv_usec;
			goto expire;
		}
		itp->it_value.tv_usec += 1000000;
		itp->it_value.tv_sec--;
	}
	itp->it_value.tv_usec -= usec;
	usec = 0;
	if (timerisset(&itp->it_value))
		return (1);
	/* expired, exactly at end of interval */
expire:
	if (timerisset(&itp->it_interval)) {
		itp->it_value = itp->it_interval;
		itp->it_value.tv_usec -= usec;
		if (itp->it_value.tv_usec < 0) {
			itp->it_value.tv_usec += 1000000;
			itp->it_value.tv_sec--;
		}
	} else
		itp->it_value.tv_usec = 0;		/* sec is already 0 */
	return (0);
}

sema_t	paused;			/* sema on which sigpause sleeps */

/*
 * SVR3 pause system call.
 */
pause()
{
	/*
	 * Must be in loop since a stop signal might terminate sleep
	 */
	for (;;)
		(void)p_sema(&paused, PSLEP);
	/* not reached */
}


/*
 * adjtime(delta, olddelta)
 * timeval_t *delta, *olddelta;
 *
 * adjtime system call used to slow down or speed up the time
 * of day clock.  The time of day clock is slowly adjusted
 * to the new timedelta by tickdelta at each todclock() call.
 *
 * tickdelta is set to tickadj if the amount of change is
 * < |1 sec.| or to 10 X tickadj if the change is > |1 sec.|
 *
 * timedelta is set to be the closest multiple of tickdelta
 * for the time the user asked for.
 *
 */

int tickdelta;			/* current clock skew, us. per tick */
long timedelta;			/* unapplied time correction, us. */
static long bigadj = 1000000;	/* use 10x skew above bigadj us. */

adjtime()
{
	register struct a {
		struct timeval *delta;
		struct timeval *olddelta;
	} *uap = (struct a *)u.u_ap;
	register long new_timed;
	register int new_tickd;
	timeval_t atv, oatv;
	extern int tickadj;		/* "standard" clock skew, us./tick */

	if (!suser()) {
		return;
	}
	u.u_error = copyin((caddr_t)uap->delta, (caddr_t)&atv,
			sizeof (timeval_t));
	if (u.u_error) {
		return;
	}
	new_timed = atv.tv_sec * 1000000 + atv.tv_usec;
	if ((new_timed > bigadj) || (new_timed < -bigadj)) {
		new_tickd = 10 * tickadj;
	} else {
		new_tickd = tickadj;
	}
	if (new_timed % new_tickd) {
		new_timed = new_timed / new_tickd * new_tickd;
	}

	P_GATE(G_TIME);
	if (uap->olddelta) {
		oatv.tv_sec = timedelta / 1000000;
		oatv.tv_usec = timedelta % 1000000;
	}
	timedelta = new_timed;
	tickdelta = new_tickd;
	V_GATE(G_TIME);

	if (uap->olddelta) {
		u.u_error = copyout((caddr_t)&oatv, (caddr_t)uap->olddelta,
			sizeof (timeval_t));
	}
}
