kern_time.c revision 36127
1/*
2 * Copyright (c) 1982, 1986, 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	@(#)kern_time.c	8.1 (Berkeley) 6/10/93
34 * $Id: kern_time.c,v 1.55 1998/05/17 11:52:48 phk Exp $
35 */
36
37#include <sys/param.h>
38#include <sys/sysproto.h>
39#include <sys/resourcevar.h>
40#include <sys/signalvar.h>
41#include <sys/kernel.h>
42#include <sys/systm.h>
43#include <sys/sysent.h>
44#include <sys/proc.h>
45#include <sys/time.h>
46#include <sys/vnode.h>
47#include <vm/vm.h>
48#include <vm/vm_extern.h>
49
50struct timezone tz;
51
52/*
53 * Time of day and interval timer support.
54 *
55 * These routines provide the kernel entry points to get and set
56 * the time-of-day and per-process interval timers.  Subroutines
57 * here provide support for adding and subtracting timeval structures
58 * and decrementing interval timers, optionally reloading the interval
59 * timers when they expire.
60 */
61
62static int	nanosleep1 __P((struct proc *p, struct timespec *rqt,
63		    struct timespec *rmt));
64static int	settime __P((struct timeval *));
65static void	timevalfix __P((struct timeval *));
66static void	no_lease_updatetime __P((int));
67
68static void
69no_lease_updatetime(deltat)
70	int deltat;
71{
72}
73
74void (*lease_updatetime) __P((int))  = no_lease_updatetime;
75
76static int
77settime(tv)
78	struct timeval *tv;
79{
80	struct timeval delta, tv1;
81	struct timespec ts;
82	struct proc *p;
83	int s;
84
85	s = splclock();
86	microtime(&tv1);
87	delta = *tv;
88	timevalsub(&delta, &tv1);
89
90	/*
91	 * If the system is secure, we do not allow the time to be
92	 * set to an earlier value (it may be slowed using adjtime,
93	 * but not set back). This feature prevent interlopers from
94	 * setting arbitrary time stamps on files.
95	 */
96	if (delta.tv_sec < 0 && securelevel > 1) {
97		splx(s);
98		return (EPERM);
99	}
100
101	ts.tv_sec = tv->tv_sec;
102	ts.tv_nsec = tv->tv_usec * 1000;
103	set_timecounter(&ts);
104	(void) splsoftclock();
105	lease_updatetime(delta.tv_sec);
106	splx(s);
107	resettodr();
108	return (0);
109}
110
111#ifndef _SYS_SYSPROTO_H_
112struct clock_gettime_args {
113	clockid_t clock_id;
114	struct	timespec *tp;
115};
116#endif
117
118/* ARGSUSED */
119int
120clock_gettime(p, uap)
121	struct proc *p;
122	struct clock_gettime_args *uap;
123{
124	struct timespec ats;
125
126	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
127		return (EINVAL);
128	nanotime(&ats);
129	return (copyout(&ats, SCARG(uap, tp), sizeof(ats)));
130}
131
132#ifndef _SYS_SYSPROTO_H_
133struct clock_settime_args {
134	clockid_t clock_id;
135	const struct	timespec *tp;
136};
137#endif
138
139/* ARGSUSED */
140int
141clock_settime(p, uap)
142	struct proc *p;
143	struct clock_settime_args *uap;
144{
145	struct timeval atv;
146	struct timespec ats;
147	int error;
148
149	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
150		return (error);
151	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
152		return (EINVAL);
153	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
154		return (error);
155	if (ats.tv_nsec < 0 || ats.tv_nsec >= 1000000000)
156		return (EINVAL);
157	/* XXX Don't convert nsec->usec and back */
158	TIMESPEC_TO_TIMEVAL(&atv, &ats);
159	if ((error = settime(&atv)))
160		return (error);
161	return (0);
162}
163
164#ifndef _SYS_SYSPROTO_H_
165struct clock_getres_args {
166	clockid_t clock_id;
167	struct	timespec *tp;
168};
169#endif
170
171int
172clock_getres(p, uap)
173	struct proc *p;
174	struct clock_getres_args *uap;
175{
176	struct timespec ts;
177	int error;
178
179	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
180		return (EINVAL);
181	error = 0;
182	if (SCARG(uap, tp)) {
183		ts.tv_sec = 0;
184		ts.tv_nsec = 1000000000 / timecounter->frequency;
185		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
186	}
187	return (error);
188}
189
190static int nanowait;
191
192static int
193nanosleep1(p, rqt, rmt)
194	struct proc *p;
195	struct timespec *rqt, *rmt;
196{
197	struct timespec ts, ts2, ts3;
198	struct timeval tv;
199	int error;
200
201	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
202		return (EINVAL);
203	if (rqt->tv_sec < 0 || rqt->tv_sec == 0 && rqt->tv_nsec == 0)
204		return (0);
205	getnanouptime(&ts);
206	timespecadd(&ts, rqt);
207	TIMESPEC_TO_TIMEVAL(&tv, rqt);
208	for (;;) {
209		error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
210		    tvtohz(&tv));
211		getnanouptime(&ts2);
212		if (error != EWOULDBLOCK) {
213			if (error == ERESTART)
214				error = EINTR;
215			if (rmt != NULL) {
216				timespecsub(&ts, &ts2);
217				if (ts.tv_sec < 0)
218					timespecclear(&ts);
219				*rmt = ts;
220			}
221			return (error);
222		}
223		if (timespeccmp(&ts2, &ts, >=))
224			return (0);
225		ts3 = ts;
226		timespecsub(&ts3, &ts2);
227		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
228	}
229}
230
231#ifndef _SYS_SYSPROTO_H_
232struct nanosleep_args {
233	struct	timespec *rqtp;
234	struct	timespec *rmtp;
235};
236#endif
237
238/* ARGSUSED */
239int
240nanosleep(p, uap)
241	struct proc *p;
242	struct nanosleep_args *uap;
243{
244	struct timespec rmt, rqt;
245	int error, error2;
246
247	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(rqt));
248	if (error)
249		return (error);
250	if (SCARG(uap, rmtp))
251		if (!useracc((caddr_t)SCARG(uap, rmtp), sizeof(rmt), B_WRITE))
252			return (EFAULT);
253	error = nanosleep1(p, &rqt, &rmt);
254	if (error && SCARG(uap, rmtp)) {
255		error2 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
256		if (error2)	/* XXX shouldn't happen, did useracc() above */
257			return (error2);
258	}
259	return (error);
260}
261
262#ifndef _SYS_SYSPROTO_H_
263struct gettimeofday_args {
264	struct	timeval *tp;
265	struct	timezone *tzp;
266};
267#endif
268/* ARGSUSED */
269int
270gettimeofday(p, uap)
271	struct proc *p;
272	register struct gettimeofday_args *uap;
273{
274	struct timeval atv;
275	int error = 0;
276
277	if (uap->tp) {
278		microtime(&atv);
279		if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
280		    sizeof (atv))))
281			return (error);
282	}
283	if (uap->tzp)
284		error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
285		    sizeof (tz));
286	return (error);
287}
288
289#ifndef _SYS_SYSPROTO_H_
290struct settimeofday_args {
291	struct	timeval *tv;
292	struct	timezone *tzp;
293};
294#endif
295/* ARGSUSED */
296int
297settimeofday(p, uap)
298	struct proc *p;
299	struct settimeofday_args *uap;
300{
301	struct timeval atv;
302	struct timezone atz;
303	int error;
304
305	if ((error = suser(p->p_ucred, &p->p_acflag)))
306		return (error);
307	/* Verify all parameters before changing time. */
308	if (uap->tv) {
309		if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
310		    sizeof(atv))))
311			return (error);
312		if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
313			return (EINVAL);
314	}
315	if (uap->tzp &&
316	    (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
317		return (error);
318	if (uap->tv && (error = settime(&atv)))
319		return (error);
320	if (uap->tzp)
321		tz = atz;
322	return (0);
323}
324
325int	tickdelta;			/* current clock skew, us. per tick */
326long	timedelta;			/* unapplied time correction, us. */
327static long	bigadj = 1000000;	/* use 10x skew above bigadj us. */
328
329#ifndef _SYS_SYSPROTO_H_
330struct adjtime_args {
331	struct timeval *delta;
332	struct timeval *olddelta;
333};
334#endif
335/* ARGSUSED */
336int
337adjtime(p, uap)
338	struct proc *p;
339	register struct adjtime_args *uap;
340{
341	struct timeval atv;
342	register long ndelta, ntickdelta, odelta;
343	int s, error;
344
345	if ((error = suser(p->p_ucred, &p->p_acflag)))
346		return (error);
347	if ((error =
348	    copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
349		return (error);
350
351	/*
352	 * Compute the total correction and the rate at which to apply it.
353	 * Round the adjustment down to a whole multiple of the per-tick
354	 * delta, so that after some number of incremental changes in
355	 * hardclock(), tickdelta will become zero, lest the correction
356	 * overshoot and start taking us away from the desired final time.
357	 */
358	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
359	if (ndelta > bigadj || ndelta < -bigadj)
360		ntickdelta = 10 * tickadj;
361	else
362		ntickdelta = tickadj;
363	if (ndelta % ntickdelta)
364		ndelta = ndelta / ntickdelta * ntickdelta;
365
366	/*
367	 * To make hardclock()'s job easier, make the per-tick delta negative
368	 * if we want time to run slower; then hardclock can simply compute
369	 * tick + tickdelta, and subtract tickdelta from timedelta.
370	 */
371	if (ndelta < 0)
372		ntickdelta = -ntickdelta;
373	s = splclock();
374	odelta = timedelta;
375	timedelta = ndelta;
376	tickdelta = ntickdelta;
377	splx(s);
378
379	if (uap->olddelta) {
380		atv.tv_sec = odelta / 1000000;
381		atv.tv_usec = odelta % 1000000;
382		(void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
383		    sizeof(struct timeval));
384	}
385	return (0);
386}
387
388/*
389 * Get value of an interval timer.  The process virtual and
390 * profiling virtual time timers are kept in the p_stats area, since
391 * they can be swapped out.  These are kept internally in the
392 * way they are specified externally: in time until they expire.
393 *
394 * The real time interval timer is kept in the process table slot
395 * for the process, and its value (it_value) is kept as an
396 * absolute time rather than as a delta, so that it is easy to keep
397 * periodic real-time signals from drifting.
398 *
399 * Virtual time timers are processed in the hardclock() routine of
400 * kern_clock.c.  The real time timer is processed by a timeout
401 * routine, called from the softclock() routine.  Since a callout
402 * may be delayed in real time due to interrupt processing in the system,
403 * it is possible for the real time timeout routine (realitexpire, given below),
404 * to be delayed in real time past when it is supposed to occur.  It
405 * does not suffice, therefore, to reload the real timer .it_value from the
406 * real time timers .it_interval.  Rather, we compute the next time in
407 * absolute time the timer should go off.
408 */
409#ifndef _SYS_SYSPROTO_H_
410struct getitimer_args {
411	u_int	which;
412	struct	itimerval *itv;
413};
414#endif
415/* ARGSUSED */
416int
417getitimer(p, uap)
418	struct proc *p;
419	register struct getitimer_args *uap;
420{
421	struct timeval ctv;
422	struct itimerval aitv;
423	int s;
424
425	if (uap->which > ITIMER_PROF)
426		return (EINVAL);
427	s = splclock(); /* XXX still needed ? */
428	if (uap->which == ITIMER_REAL) {
429		/*
430		 * Convert from absoulte to relative time in .it_value
431		 * part of real time timer.  If time for real time timer
432		 * has passed return 0, else return difference between
433		 * current time and time for the timer to go off.
434		 */
435		aitv = p->p_realtimer;
436		if (timevalisset(&aitv.it_value)) {
437			getmicrouptime(&ctv);
438			if (timevalcmp(&aitv.it_value, &ctv, <))
439				timevalclear(&aitv.it_value);
440			else
441				timevalsub(&aitv.it_value, &ctv);
442		}
443	} else
444		aitv = p->p_stats->p_timer[uap->which];
445	splx(s);
446	return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
447	    sizeof (struct itimerval)));
448}
449
450#ifndef _SYS_SYSPROTO_H_
451struct setitimer_args {
452	u_int	which;
453	struct	itimerval *itv, *oitv;
454};
455#endif
456/* ARGSUSED */
457int
458setitimer(p, uap)
459	struct proc *p;
460	register struct setitimer_args *uap;
461{
462	struct itimerval aitv;
463	struct timeval ctv;
464	register struct itimerval *itvp;
465	int s, error;
466
467	if (uap->which > ITIMER_PROF)
468		return (EINVAL);
469	itvp = uap->itv;
470	if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
471	    sizeof(struct itimerval))))
472		return (error);
473	if ((uap->itv = uap->oitv) &&
474	    (error = getitimer(p, (struct getitimer_args *)uap)))
475		return (error);
476	if (itvp == 0)
477		return (0);
478	if (itimerfix(&aitv.it_value))
479		return (EINVAL);
480	if (!timevalisset(&aitv.it_value))
481		timevalclear(&aitv.it_interval);
482	else if (itimerfix(&aitv.it_interval))
483		return (EINVAL);
484	s = splclock(); /* XXX: still needed ? */
485	if (uap->which == ITIMER_REAL) {
486		if (timevalisset(&p->p_realtimer.it_value))
487			untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
488		if (timevalisset(&aitv.it_value))
489			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
490						tvtohz(&aitv.it_value));
491		getmicrouptime(&ctv);
492		timevaladd(&aitv.it_value, &ctv);
493		p->p_realtimer = aitv;
494	} else
495		p->p_stats->p_timer[uap->which] = aitv;
496	splx(s);
497	return (0);
498}
499
500/*
501 * Real interval timer expired:
502 * send process whose timer expired an alarm signal.
503 * If time is not set up to reload, then just return.
504 * Else compute next time timer should go off which is > current time.
505 * This is where delay in processing this timeout causes multiple
506 * SIGALRM calls to be compressed into one.
507 * tvtohz() always adds 1 to allow for the time until the next clock
508 * interrupt being strictly less than 1 clock tick, but we don't want
509 * that here since we want to appear to be in sync with the clock
510 * interrupt even when we're delayed.
511 */
512void
513realitexpire(arg)
514	void *arg;
515{
516	register struct proc *p;
517	struct timeval ctv, ntv;
518	int s;
519
520	p = (struct proc *)arg;
521	psignal(p, SIGALRM);
522	if (!timevalisset(&p->p_realtimer.it_interval)) {
523		timevalclear(&p->p_realtimer.it_value);
524		return;
525	}
526	for (;;) {
527		s = splclock(); /* XXX: still neeeded ? */
528		timevaladd(&p->p_realtimer.it_value,
529		    &p->p_realtimer.it_interval);
530		getmicrouptime(&ctv);
531		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
532			ntv = p->p_realtimer.it_value;
533			timevalsub(&ntv, &ctv);
534			p->p_ithandle =
535			    timeout(realitexpire, (caddr_t)p, tvtohz(&ntv));
536			splx(s);
537			return;
538		}
539		splx(s);
540	}
541}
542
543/*
544 * Check that a proposed value to load into the .it_value or
545 * .it_interval part of an interval timer is acceptable, and
546 * fix it to have at least minimal value (i.e. if it is less
547 * than the resolution of the clock, round it up.)
548 */
549int
550itimerfix(tv)
551	struct timeval *tv;
552{
553
554	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
555	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
556		return (EINVAL);
557	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
558		tv->tv_usec = tick;
559	return (0);
560}
561
562/*
563 * Decrement an interval timer by a specified number
564 * of microseconds, which must be less than a second,
565 * i.e. < 1000000.  If the timer expires, then reload
566 * it.  In this case, carry over (usec - old value) to
567 * reduce the value reloaded into the timer so that
568 * the timer does not drift.  This routine assumes
569 * that it is called in a context where the timers
570 * on which it is operating cannot change in value.
571 */
572int
573itimerdecr(itp, usec)
574	register struct itimerval *itp;
575	int usec;
576{
577
578	if (itp->it_value.tv_usec < usec) {
579		if (itp->it_value.tv_sec == 0) {
580			/* expired, and already in next interval */
581			usec -= itp->it_value.tv_usec;
582			goto expire;
583		}
584		itp->it_value.tv_usec += 1000000;
585		itp->it_value.tv_sec--;
586	}
587	itp->it_value.tv_usec -= usec;
588	usec = 0;
589	if (timevalisset(&itp->it_value))
590		return (1);
591	/* expired, exactly at end of interval */
592expire:
593	if (timevalisset(&itp->it_interval)) {
594		itp->it_value = itp->it_interval;
595		itp->it_value.tv_usec -= usec;
596		if (itp->it_value.tv_usec < 0) {
597			itp->it_value.tv_usec += 1000000;
598			itp->it_value.tv_sec--;
599		}
600	} else
601		itp->it_value.tv_usec = 0;		/* sec is already 0 */
602	return (0);
603}
604
605/*
606 * Add and subtract routines for timevals.
607 * N.B.: subtract routine doesn't deal with
608 * results which are before the beginning,
609 * it just gets very confused in this case.
610 * Caveat emptor.
611 */
612void
613timevaladd(t1, t2)
614	struct timeval *t1, *t2;
615{
616
617	t1->tv_sec += t2->tv_sec;
618	t1->tv_usec += t2->tv_usec;
619	timevalfix(t1);
620}
621
622void
623timevalsub(t1, t2)
624	struct timeval *t1, *t2;
625{
626
627	t1->tv_sec -= t2->tv_sec;
628	t1->tv_usec -= t2->tv_usec;
629	timevalfix(t1);
630}
631
632static void
633timevalfix(t1)
634	struct timeval *t1;
635{
636
637	if (t1->tv_usec < 0) {
638		t1->tv_sec--;
639		t1->tv_usec += 1000000;
640	}
641	if (t1->tv_usec >= 1000000) {
642		t1->tv_sec++;
643		t1->tv_usec -= 1000000;
644	}
645}
646