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