kern_time.c revision 40648
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.58 1998/06/09 13:10:53 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	int s;
83
84	s = splclock();
85	microtime(&tv1);
86	delta = *tv;
87	timevalsub(&delta, &tv1);
88
89	/*
90	 * If the system is secure, we do not allow the time to be
91	 * set to an earlier value (it may be slowed using adjtime,
92	 * but not set back). This feature prevent interlopers from
93	 * setting arbitrary time stamps on files.
94	 */
95	if (delta.tv_sec < 0 && securelevel > 1) {
96		splx(s);
97		return (EPERM);
98	}
99
100	ts.tv_sec = tv->tv_sec;
101	ts.tv_nsec = tv->tv_usec * 1000;
102	set_timecounter(&ts);
103	(void) splsoftclock();
104	lease_updatetime(delta.tv_sec);
105	splx(s);
106	resettodr();
107	return (0);
108}
109
110#ifndef _SYS_SYSPROTO_H_
111struct clock_gettime_args {
112	clockid_t clock_id;
113	struct	timespec *tp;
114};
115#endif
116
117/* ARGSUSED */
118int
119clock_gettime(p, uap)
120	struct proc *p;
121	struct clock_gettime_args *uap;
122{
123	struct timespec ats;
124
125	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
126		return (EINVAL);
127	nanotime(&ats);
128	return (copyout(&ats, SCARG(uap, tp), sizeof(ats)));
129}
130
131#ifndef _SYS_SYSPROTO_H_
132struct clock_settime_args {
133	clockid_t clock_id;
134	const struct	timespec *tp;
135};
136#endif
137
138/* ARGSUSED */
139int
140clock_settime(p, uap)
141	struct proc *p;
142	struct clock_settime_args *uap;
143{
144	struct timeval atv;
145	struct timespec ats;
146	int error;
147
148	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
149		return (error);
150	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
151		return (EINVAL);
152	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
153		return (error);
154	if (ats.tv_nsec < 0 || ats.tv_nsec >= 1000000000)
155		return (EINVAL);
156	/* XXX Don't convert nsec->usec and back */
157	TIMESPEC_TO_TIMEVAL(&atv, &ats);
158	if ((error = settime(&atv)))
159		return (error);
160	return (0);
161}
162
163#ifndef _SYS_SYSPROTO_H_
164struct clock_getres_args {
165	clockid_t clock_id;
166	struct	timespec *tp;
167};
168#endif
169
170int
171clock_getres(p, uap)
172	struct proc *p;
173	struct clock_getres_args *uap;
174{
175	struct timespec ts;
176	int error;
177
178	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
179		return (EINVAL);
180	error = 0;
181	if (SCARG(uap, tp)) {
182		ts.tv_sec = 0;
183		ts.tv_nsec = 1000000000 / timecounter->tc_frequency;
184		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
185	}
186	return (error);
187}
188
189static int nanowait;
190
191static int
192nanosleep1(p, rqt, rmt)
193	struct proc *p;
194	struct timespec *rqt, *rmt;
195{
196	struct timespec ts, ts2, ts3;
197	struct timeval tv;
198	int error;
199
200	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
201		return (EINVAL);
202	if (rqt->tv_sec < 0 || rqt->tv_sec == 0 && rqt->tv_nsec == 0)
203		return (0);
204	getnanouptime(&ts);
205	timespecadd(&ts, rqt);
206	TIMESPEC_TO_TIMEVAL(&tv, rqt);
207	for (;;) {
208		error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
209		    tvtohz(&tv));
210		getnanouptime(&ts2);
211		if (error != EWOULDBLOCK) {
212			if (error == ERESTART)
213				error = EINTR;
214			if (rmt != NULL) {
215				timespecsub(&ts, &ts2);
216				if (ts.tv_sec < 0)
217					timespecclear(&ts);
218				*rmt = ts;
219			}
220			return (error);
221		}
222		if (timespeccmp(&ts2, &ts, >=))
223			return (0);
224		ts3 = ts;
225		timespecsub(&ts3, &ts2);
226		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
227	}
228}
229
230#ifndef _SYS_SYSPROTO_H_
231struct nanosleep_args {
232	struct	timespec *rqtp;
233	struct	timespec *rmtp;
234};
235#endif
236
237/* ARGSUSED */
238int
239nanosleep(p, uap)
240	struct proc *p;
241	struct nanosleep_args *uap;
242{
243	struct timespec rmt, rqt;
244	int error, error2;
245
246	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(rqt));
247	if (error)
248		return (error);
249	if (SCARG(uap, rmtp))
250		if (!useracc((caddr_t)SCARG(uap, rmtp), sizeof(rmt), B_WRITE))
251			return (EFAULT);
252	error = nanosleep1(p, &rqt, &rmt);
253	if (error && SCARG(uap, rmtp)) {
254		error2 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
255		if (error2)	/* XXX shouldn't happen, did useracc() above */
256			return (error2);
257	}
258	return (error);
259}
260
261#ifndef _SYS_SYSPROTO_H_
262struct gettimeofday_args {
263	struct	timeval *tp;
264	struct	timezone *tzp;
265};
266#endif
267/* ARGSUSED */
268int
269gettimeofday(p, uap)
270	struct proc *p;
271	register struct gettimeofday_args *uap;
272{
273	struct timeval atv;
274	int error = 0;
275
276	if (uap->tp) {
277		microtime(&atv);
278		if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
279		    sizeof (atv))))
280			return (error);
281	}
282	if (uap->tzp)
283		error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
284		    sizeof (tz));
285	return (error);
286}
287
288#ifndef _SYS_SYSPROTO_H_
289struct settimeofday_args {
290	struct	timeval *tv;
291	struct	timezone *tzp;
292};
293#endif
294/* ARGSUSED */
295int
296settimeofday(p, uap)
297	struct proc *p;
298	struct settimeofday_args *uap;
299{
300	struct timeval atv;
301	struct timezone atz;
302	int error;
303
304	if ((error = suser(p->p_ucred, &p->p_acflag)))
305		return (error);
306	/* Verify all parameters before changing time. */
307	if (uap->tv) {
308		if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
309		    sizeof(atv))))
310			return (error);
311		if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
312			return (EINVAL);
313	}
314	if (uap->tzp &&
315	    (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
316		return (error);
317	if (uap->tv && (error = settime(&atv)))
318		return (error);
319	if (uap->tzp)
320		tz = atz;
321	return (0);
322}
323
324int	tickdelta;			/* current clock skew, us. per tick */
325long	timedelta;			/* unapplied time correction, us. */
326static long	bigadj = 1000000;	/* use 10x skew above bigadj us. */
327
328#ifndef _SYS_SYSPROTO_H_
329struct adjtime_args {
330	struct timeval *delta;
331	struct timeval *olddelta;
332};
333#endif
334/* ARGSUSED */
335int
336adjtime(p, uap)
337	struct proc *p;
338	register struct adjtime_args *uap;
339{
340	struct timeval atv;
341	register long ndelta, ntickdelta, odelta;
342	int s, error;
343
344	if ((error = suser(p->p_ucred, &p->p_acflag)))
345		return (error);
346	if ((error =
347	    copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
348		return (error);
349
350	/*
351	 * Compute the total correction and the rate at which to apply it.
352	 * Round the adjustment down to a whole multiple of the per-tick
353	 * delta, so that after some number of incremental changes in
354	 * hardclock(), tickdelta will become zero, lest the correction
355	 * overshoot and start taking us away from the desired final time.
356	 */
357	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
358	if (ndelta > bigadj || ndelta < -bigadj)
359		ntickdelta = 10 * tickadj;
360	else
361		ntickdelta = tickadj;
362	if (ndelta % ntickdelta)
363		ndelta = ndelta / ntickdelta * ntickdelta;
364
365	/*
366	 * To make hardclock()'s job easier, make the per-tick delta negative
367	 * if we want time to run slower; then hardclock can simply compute
368	 * tick + tickdelta, and subtract tickdelta from timedelta.
369	 */
370	if (ndelta < 0)
371		ntickdelta = -ntickdelta;
372	s = splclock();
373	odelta = timedelta;
374	timedelta = ndelta;
375	tickdelta = ntickdelta;
376	splx(s);
377
378	if (uap->olddelta) {
379		atv.tv_sec = odelta / 1000000;
380		atv.tv_usec = odelta % 1000000;
381		(void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
382		    sizeof(struct timeval));
383	}
384	return (0);
385}
386
387/*
388 * Get value of an interval timer.  The process virtual and
389 * profiling virtual time timers are kept in the p_stats area, since
390 * they can be swapped out.  These are kept internally in the
391 * way they are specified externally: in time until they expire.
392 *
393 * The real time interval timer is kept in the process table slot
394 * for the process, and its value (it_value) is kept as an
395 * absolute time rather than as a delta, so that it is easy to keep
396 * periodic real-time signals from drifting.
397 *
398 * Virtual time timers are processed in the hardclock() routine of
399 * kern_clock.c.  The real time timer is processed by a timeout
400 * routine, called from the softclock() routine.  Since a callout
401 * may be delayed in real time due to interrupt processing in the system,
402 * it is possible for the real time timeout routine (realitexpire, given below),
403 * to be delayed in real time past when it is supposed to occur.  It
404 * does not suffice, therefore, to reload the real timer .it_value from the
405 * real time timers .it_interval.  Rather, we compute the next time in
406 * absolute time the timer should go off.
407 */
408#ifndef _SYS_SYSPROTO_H_
409struct getitimer_args {
410	u_int	which;
411	struct	itimerval *itv;
412};
413#endif
414/* ARGSUSED */
415int
416getitimer(p, uap)
417	struct proc *p;
418	register struct getitimer_args *uap;
419{
420	struct timeval ctv;
421	struct itimerval aitv;
422	int s;
423
424	if (uap->which > ITIMER_PROF)
425		return (EINVAL);
426	s = splclock(); /* XXX still needed ? */
427	if (uap->which == ITIMER_REAL) {
428		/*
429		 * Convert from absolute to relative time in .it_value
430		 * part of real time timer.  If time for real time timer
431		 * has passed return 0, else return difference between
432		 * current time and time for the timer to go off.
433		 */
434		aitv = p->p_realtimer;
435		if (timevalisset(&aitv.it_value)) {
436			getmicrouptime(&ctv);
437			if (timevalcmp(&aitv.it_value, &ctv, <))
438				timevalclear(&aitv.it_value);
439			else
440				timevalsub(&aitv.it_value, &ctv);
441		}
442	} else
443		aitv = p->p_stats->p_timer[uap->which];
444	splx(s);
445	return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
446	    sizeof (struct itimerval)));
447}
448
449#ifndef _SYS_SYSPROTO_H_
450struct setitimer_args {
451	u_int	which;
452	struct	itimerval *itv, *oitv;
453};
454#endif
455/* ARGSUSED */
456int
457setitimer(p, uap)
458	struct proc *p;
459	register struct setitimer_args *uap;
460{
461	struct itimerval aitv;
462	struct timeval ctv;
463	register struct itimerval *itvp;
464	int s, error;
465
466	if (uap->which > ITIMER_PROF)
467		return (EINVAL);
468	itvp = uap->itv;
469	if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
470	    sizeof(struct itimerval))))
471		return (error);
472	if ((uap->itv = uap->oitv) &&
473	    (error = getitimer(p, (struct getitimer_args *)uap)))
474		return (error);
475	if (itvp == 0)
476		return (0);
477	if (itimerfix(&aitv.it_value))
478		return (EINVAL);
479	if (!timevalisset(&aitv.it_value))
480		timevalclear(&aitv.it_interval);
481	else if (itimerfix(&aitv.it_interval))
482		return (EINVAL);
483	s = splclock(); /* XXX: still needed ? */
484	if (uap->which == ITIMER_REAL) {
485		if (timevalisset(&p->p_realtimer.it_value))
486			untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
487		if (timevalisset(&aitv.it_value))
488			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
489						tvtohz(&aitv.it_value));
490		getmicrouptime(&ctv);
491		timevaladd(&aitv.it_value, &ctv);
492		p->p_realtimer = aitv;
493	} else
494		p->p_stats->p_timer[uap->which] = aitv;
495	splx(s);
496	return (0);
497}
498
499/*
500 * Real interval timer expired:
501 * send process whose timer expired an alarm signal.
502 * If time is not set up to reload, then just return.
503 * Else compute next time timer should go off which is > current time.
504 * This is where delay in processing this timeout causes multiple
505 * SIGALRM calls to be compressed into one.
506 * tvtohz() always adds 1 to allow for the time until the next clock
507 * interrupt being strictly less than 1 clock tick, but we don't want
508 * that here since we want to appear to be in sync with the clock
509 * interrupt even when we're delayed.
510 */
511void
512realitexpire(arg)
513	void *arg;
514{
515	register struct proc *p;
516	struct timeval ctv, ntv;
517	int s;
518
519	p = (struct proc *)arg;
520	psignal(p, SIGALRM);
521	if (!timevalisset(&p->p_realtimer.it_interval)) {
522		timevalclear(&p->p_realtimer.it_value);
523		return;
524	}
525	for (;;) {
526		s = splclock(); /* XXX: still neeeded ? */
527		timevaladd(&p->p_realtimer.it_value,
528		    &p->p_realtimer.it_interval);
529		getmicrouptime(&ctv);
530		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
531			ntv = p->p_realtimer.it_value;
532			timevalsub(&ntv, &ctv);
533			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
534			    tvtohz(&ntv) - 1);
535			splx(s);
536			return;
537		}
538		splx(s);
539	}
540}
541
542/*
543 * Check that a proposed value to load into the .it_value or
544 * .it_interval part of an interval timer is acceptable, and
545 * fix it to have at least minimal value (i.e. if it is less
546 * than the resolution of the clock, round it up.)
547 */
548int
549itimerfix(tv)
550	struct timeval *tv;
551{
552
553	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
554	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
555		return (EINVAL);
556	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
557		tv->tv_usec = tick;
558	return (0);
559}
560
561/*
562 * Decrement an interval timer by a specified number
563 * of microseconds, which must be less than a second,
564 * i.e. < 1000000.  If the timer expires, then reload
565 * it.  In this case, carry over (usec - old value) to
566 * reduce the value reloaded into the timer so that
567 * the timer does not drift.  This routine assumes
568 * that it is called in a context where the timers
569 * on which it is operating cannot change in value.
570 */
571int
572itimerdecr(itp, usec)
573	register struct itimerval *itp;
574	int usec;
575{
576
577	if (itp->it_value.tv_usec < usec) {
578		if (itp->it_value.tv_sec == 0) {
579			/* expired, and already in next interval */
580			usec -= itp->it_value.tv_usec;
581			goto expire;
582		}
583		itp->it_value.tv_usec += 1000000;
584		itp->it_value.tv_sec--;
585	}
586	itp->it_value.tv_usec -= usec;
587	usec = 0;
588	if (timevalisset(&itp->it_value))
589		return (1);
590	/* expired, exactly at end of interval */
591expire:
592	if (timevalisset(&itp->it_interval)) {
593		itp->it_value = itp->it_interval;
594		itp->it_value.tv_usec -= usec;
595		if (itp->it_value.tv_usec < 0) {
596			itp->it_value.tv_usec += 1000000;
597			itp->it_value.tv_sec--;
598		}
599	} else
600		itp->it_value.tv_usec = 0;		/* sec is already 0 */
601	return (0);
602}
603
604/*
605 * Add and subtract routines for timevals.
606 * N.B.: subtract routine doesn't deal with
607 * results which are before the beginning,
608 * it just gets very confused in this case.
609 * Caveat emptor.
610 */
611void
612timevaladd(t1, t2)
613	struct timeval *t1, *t2;
614{
615
616	t1->tv_sec += t2->tv_sec;
617	t1->tv_usec += t2->tv_usec;
618	timevalfix(t1);
619}
620
621void
622timevalsub(t1, t2)
623	struct timeval *t1, *t2;
624{
625
626	t1->tv_sec -= t2->tv_sec;
627	t1->tv_usec -= t2->tv_usec;
628	timevalfix(t1);
629}
630
631static void
632timevalfix(t1)
633	struct timeval *t1;
634{
635
636	if (t1->tv_usec < 0) {
637		t1->tv_sec--;
638		t1->tv_usec += 1000000;
639	}
640	if (t1->tv_usec >= 1000000) {
641		t1->tv_sec++;
642		t1->tv_usec -= 1000000;
643	}
644}
645