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