xref: /freebsd/sys/kern/kern_time.c (revision 4a0f765fbf09711e612e86fce8bb09ec43f482d9)
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$
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/proc.h>
44 #include <sys/vnode.h>
45 
46 struct timezone tz;
47 
48 /*
49  * Time of day and interval timer support.
50  *
51  * These routines provide the kernel entry points to get and set
52  * the time-of-day and per-process interval timers.  Subroutines
53  * here provide support for adding and subtracting timeval structures
54  * and decrementing interval timers, optionally reloading the interval
55  * timers when they expire.
56  */
57 
58 static void	timevalfix __P((struct timeval *));
59 
60 #ifndef _SYS_SYSPROTO_H_
61 struct gettimeofday_args {
62 	struct	timeval *tp;
63 	struct	timezone *tzp;
64 };
65 #endif
66 /* ARGSUSED */
67 int
68 gettimeofday(p, uap, retval)
69 	struct proc *p;
70 	register struct gettimeofday_args *uap;
71 	int *retval;
72 {
73 	struct timeval atv;
74 	int error = 0;
75 
76 	if (uap->tp) {
77 		microtime(&atv);
78 		if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
79 		    sizeof (atv))))
80 			return (error);
81 	}
82 	if (uap->tzp)
83 		error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
84 		    sizeof (tz));
85 	return (error);
86 }
87 
88 #ifndef _SYS_SYSPROTO_H_
89 struct settimeofday_args {
90 	struct	timeval *tv;
91 	struct	timezone *tzp;
92 };
93 #endif
94 /* ARGSUSED */
95 int
96 settimeofday(p, uap, retval)
97 	struct proc *p;
98 	struct settimeofday_args *uap;
99 	int *retval;
100 {
101 	struct timeval atv, delta;
102 	struct timezone atz;
103 	int error, s;
104 
105 	if ((error = suser(p->p_ucred, &p->p_acflag)))
106 		return (error);
107 	/* Verify all parameters before changing time. */
108 	if (uap->tv &&
109 	    (error = copyin((caddr_t)uap->tv, (caddr_t)&atv, sizeof(atv))))
110 		return (error);
111 	if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
112 		return (EINVAL);
113 	if (uap->tzp &&
114 	    (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
115 		return (error);
116 	if (uap->tv) {
117 		s = splclock();
118 		/*
119 		 * Calculate delta directly to minimize clock interrupt
120 		 * latency.  Fix it after the ipl has been lowered.
121 		 */
122 		delta.tv_sec = atv.tv_sec - time.tv_sec;
123 		delta.tv_usec = atv.tv_usec - time.tv_usec;
124 		time = atv;
125 		/*
126 		 * XXX should arrange for microtime() to agree with atv if
127 		 * it is called now.  As it is, it may add up to about
128 		 * `tick' unwanted usec.
129 		 * Another problem is that clock interrupts may occur at
130 		 * other than multiples of `tick'.  It's not worth fixing
131 		 * this here, since the problem is also caused by tick
132 		 * adjustments.
133 		 */
134 		(void) splsoftclock();
135 		timevalfix(&delta);
136 		timevaladd(&boottime, &delta);
137 		timevaladd(&runtime, &delta);
138 		/* re-use 'p' */
139 		for (p = allproc.lh_first; p != 0; p = p->p_list.le_next)
140 			if (timerisset(&p->p_realtimer.it_value))
141 				timevaladd(&p->p_realtimer.it_value, &delta);
142 #		ifdef NFS
143 			lease_updatetime(delta.tv_sec);
144 #		endif
145 		splx(s);
146 		resettodr();
147 	}
148 	if (uap->tzp)
149 		tz = atz;
150 	return (0);
151 }
152 
153 extern	int tickadj;			/* "standard" clock skew, us./tick */
154 int	tickdelta;			/* current clock skew, us. per tick */
155 long	timedelta;			/* unapplied time correction, us. */
156 static long	bigadj = 1000000;	/* use 10x skew above bigadj us. */
157 
158 #ifndef _SYS_SYSPROTO_H_
159 struct adjtime_args {
160 	struct timeval *delta;
161 	struct timeval *olddelta;
162 };
163 #endif
164 /* ARGSUSED */
165 int
166 adjtime(p, uap, retval)
167 	struct proc *p;
168 	register struct adjtime_args *uap;
169 	int *retval;
170 {
171 	struct timeval atv;
172 	register long ndelta, ntickdelta, odelta;
173 	int s, error;
174 
175 	if ((error = suser(p->p_ucred, &p->p_acflag)))
176 		return (error);
177 	if ((error =
178 	    copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
179 		return (error);
180 
181 	/*
182 	 * Compute the total correction and the rate at which to apply it.
183 	 * Round the adjustment down to a whole multiple of the per-tick
184 	 * delta, so that after some number of incremental changes in
185 	 * hardclock(), tickdelta will become zero, lest the correction
186 	 * overshoot and start taking us away from the desired final time.
187 	 */
188 	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
189 	if (ndelta > bigadj || ndelta < -bigadj)
190 		ntickdelta = 10 * tickadj;
191 	else
192 		ntickdelta = tickadj;
193 	if (ndelta % ntickdelta)
194 		ndelta = ndelta / ntickdelta * ntickdelta;
195 
196 	/*
197 	 * To make hardclock()'s job easier, make the per-tick delta negative
198 	 * if we want time to run slower; then hardclock can simply compute
199 	 * tick + tickdelta, and subtract tickdelta from timedelta.
200 	 */
201 	if (ndelta < 0)
202 		ntickdelta = -ntickdelta;
203 	s = splclock();
204 	odelta = timedelta;
205 	timedelta = ndelta;
206 	tickdelta = ntickdelta;
207 	splx(s);
208 
209 	if (uap->olddelta) {
210 		atv.tv_sec = odelta / 1000000;
211 		atv.tv_usec = odelta % 1000000;
212 		(void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
213 		    sizeof(struct timeval));
214 	}
215 	return (0);
216 }
217 
218 /*
219  * Get value of an interval timer.  The process virtual and
220  * profiling virtual time timers are kept in the p_stats area, since
221  * they can be swapped out.  These are kept internally in the
222  * way they are specified externally: in time until they expire.
223  *
224  * The real time interval timer is kept in the process table slot
225  * for the process, and its value (it_value) is kept as an
226  * absolute time rather than as a delta, so that it is easy to keep
227  * periodic real-time signals from drifting.
228  *
229  * Virtual time timers are processed in the hardclock() routine of
230  * kern_clock.c.  The real time timer is processed by a timeout
231  * routine, called from the softclock() routine.  Since a callout
232  * may be delayed in real time due to interrupt processing in the system,
233  * it is possible for the real time timeout routine (realitexpire, given below),
234  * to be delayed in real time past when it is supposed to occur.  It
235  * does not suffice, therefore, to reload the real timer .it_value from the
236  * real time timers .it_interval.  Rather, we compute the next time in
237  * absolute time the timer should go off.
238  */
239 #ifndef _SYS_SYSPROTO_H_
240 struct getitimer_args {
241 	u_int	which;
242 	struct	itimerval *itv;
243 };
244 #endif
245 /* ARGSUSED */
246 int
247 getitimer(p, uap, retval)
248 	struct proc *p;
249 	register struct getitimer_args *uap;
250 	int *retval;
251 {
252 	struct itimerval aitv;
253 	int s;
254 
255 	if (uap->which > ITIMER_PROF)
256 		return (EINVAL);
257 	s = splclock();
258 	if (uap->which == ITIMER_REAL) {
259 		/*
260 		 * Convert from absoulte to relative time in .it_value
261 		 * part of real time timer.  If time for real time timer
262 		 * has passed return 0, else return difference between
263 		 * current time and time for the timer to go off.
264 		 */
265 		aitv = p->p_realtimer;
266 		if (timerisset(&aitv.it_value))
267 			if (timercmp(&aitv.it_value, &time, <))
268 				timerclear(&aitv.it_value);
269 			else
270 				timevalsub(&aitv.it_value,
271 				    (struct timeval *)&time);
272 	} else
273 		aitv = p->p_stats->p_timer[uap->which];
274 	splx(s);
275 	return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
276 	    sizeof (struct itimerval)));
277 }
278 
279 #ifndef _SYS_SYSPROTO_H_
280 struct setitimer_args {
281 	u_int	which;
282 	struct	itimerval *itv, *oitv;
283 };
284 #endif
285 /* ARGSUSED */
286 int
287 setitimer(p, uap, retval)
288 	struct proc *p;
289 	register struct setitimer_args *uap;
290 	int *retval;
291 {
292 	struct itimerval aitv;
293 	register struct itimerval *itvp;
294 	int s, error;
295 
296 	if (uap->which > ITIMER_PROF)
297 		return (EINVAL);
298 	itvp = uap->itv;
299 	if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
300 	    sizeof(struct itimerval))))
301 		return (error);
302 	if ((uap->itv = uap->oitv) &&
303 	    (error = getitimer(p, (struct getitimer_args *)uap, retval)))
304 		return (error);
305 	if (itvp == 0)
306 		return (0);
307 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
308 		return (EINVAL);
309 	s = splclock();
310 	if (uap->which == ITIMER_REAL) {
311 		untimeout(realitexpire, (caddr_t)p);
312 		if (timerisset(&aitv.it_value)) {
313 			timevaladd(&aitv.it_value, (struct timeval *)&time);
314 			timeout(realitexpire, (caddr_t)p, hzto(&aitv.it_value));
315 		}
316 		p->p_realtimer = aitv;
317 	} else
318 		p->p_stats->p_timer[uap->which] = aitv;
319 	splx(s);
320 	return (0);
321 }
322 
323 /*
324  * Real interval timer expired:
325  * send process whose timer expired an alarm signal.
326  * If time is not set up to reload, then just return.
327  * Else compute next time timer should go off which is > current time.
328  * This is where delay in processing this timeout causes multiple
329  * SIGALRM calls to be compressed into one.
330  * hzto() always adds 1 to allow for the time until the next clock
331  * interrupt being strictly less than 1 clock tick, but we don't want
332  * that here since we want to appear to be in sync with the clock
333  * interrupt even when we're delayed.
334  */
335 void
336 realitexpire(arg)
337 	void *arg;
338 {
339 	register struct proc *p;
340 	int s;
341 
342 	p = (struct proc *)arg;
343 	psignal(p, SIGALRM);
344 	if (!timerisset(&p->p_realtimer.it_interval)) {
345 		timerclear(&p->p_realtimer.it_value);
346 		return;
347 	}
348 	for (;;) {
349 		s = splclock();
350 		timevaladd(&p->p_realtimer.it_value,
351 		    &p->p_realtimer.it_interval);
352 		if (timercmp(&p->p_realtimer.it_value, &time, >)) {
353 			timeout(realitexpire, (caddr_t)p,
354 			    hzto(&p->p_realtimer.it_value) - 1);
355 			splx(s);
356 			return;
357 		}
358 		splx(s);
359 	}
360 }
361 
362 /*
363  * Check that a proposed value to load into the .it_value or
364  * .it_interval part of an interval timer is acceptable, and
365  * fix it to have at least minimal value (i.e. if it is less
366  * than the resolution of the clock, round it up.)
367  */
368 int
369 itimerfix(tv)
370 	struct timeval *tv;
371 {
372 
373 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
374 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
375 		return (EINVAL);
376 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
377 		tv->tv_usec = tick;
378 	return (0);
379 }
380 
381 /*
382  * Decrement an interval timer by a specified number
383  * of microseconds, which must be less than a second,
384  * i.e. < 1000000.  If the timer expires, then reload
385  * it.  In this case, carry over (usec - old value) to
386  * reduce the value reloaded into the timer so that
387  * the timer does not drift.  This routine assumes
388  * that it is called in a context where the timers
389  * on which it is operating cannot change in value.
390  */
391 int
392 itimerdecr(itp, usec)
393 	register struct itimerval *itp;
394 	int usec;
395 {
396 
397 	if (itp->it_value.tv_usec < usec) {
398 		if (itp->it_value.tv_sec == 0) {
399 			/* expired, and already in next interval */
400 			usec -= itp->it_value.tv_usec;
401 			goto expire;
402 		}
403 		itp->it_value.tv_usec += 1000000;
404 		itp->it_value.tv_sec--;
405 	}
406 	itp->it_value.tv_usec -= usec;
407 	usec = 0;
408 	if (timerisset(&itp->it_value))
409 		return (1);
410 	/* expired, exactly at end of interval */
411 expire:
412 	if (timerisset(&itp->it_interval)) {
413 		itp->it_value = itp->it_interval;
414 		itp->it_value.tv_usec -= usec;
415 		if (itp->it_value.tv_usec < 0) {
416 			itp->it_value.tv_usec += 1000000;
417 			itp->it_value.tv_sec--;
418 		}
419 	} else
420 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
421 	return (0);
422 }
423 
424 /*
425  * Add and subtract routines for timevals.
426  * N.B.: subtract routine doesn't deal with
427  * results which are before the beginning,
428  * it just gets very confused in this case.
429  * Caveat emptor.
430  */
431 void
432 timevaladd(t1, t2)
433 	struct timeval *t1, *t2;
434 {
435 
436 	t1->tv_sec += t2->tv_sec;
437 	t1->tv_usec += t2->tv_usec;
438 	timevalfix(t1);
439 }
440 
441 void
442 timevalsub(t1, t2)
443 	struct timeval *t1, *t2;
444 {
445 
446 	t1->tv_sec -= t2->tv_sec;
447 	t1->tv_usec -= t2->tv_usec;
448 	timevalfix(t1);
449 }
450 
451 static void
452 timevalfix(t1)
453 	struct timeval *t1;
454 {
455 
456 	if (t1->tv_usec < 0) {
457 		t1->tv_sec--;
458 		t1->tv_usec += 1000000;
459 	}
460 	if (t1->tv_usec >= 1000000) {
461 		t1->tv_sec++;
462 		t1->tv_usec -= 1000000;
463 	}
464 }
465