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