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