2 * Copyright (c) 1982, 1986, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
33 * @(#)kern_time.c 8.1 (Berkeley) 6/10/93
34 * $FreeBSD: src/sys/kern/kern_time.c,v 1.68.2.1 2002/10/01 08:00:41 bde Exp $
35 * $DragonFly: src/sys/kern/kern_time.c,v 1.11 2003/11/20 06:05:30 dillon Exp $
38 #include <sys/param.h>
39 #include <sys/systm.h>
41 #include <sys/sysproto.h>
42 #include <sys/resourcevar.h>
43 #include <sys/signalvar.h>
44 #include <sys/kernel.h>
45 #include <sys/systm.h>
46 #include <sys/sysent.h>
47 #include <sys/sysunion.h>
50 #include <sys/vnode.h>
52 #include <vm/vm_extern.h>
53 #include <sys/msgport2.h>
58 * Time of day and interval timer support.
60 * These routines provide the kernel entry points to get and set
61 * the time-of-day and per-process interval timers. Subroutines
62 * here provide support for adding and subtracting timeval structures
63 * and decrementing interval timers, optionally reloading the interval
64 * timers when they expire.
67 static int nanosleep1 (struct timespec *rqt,
68 struct timespec *rmt);
69 static int settime (struct timeval *);
70 static void timevalfix (struct timeval *);
71 static void no_lease_updatetime (int);
74 no_lease_updatetime(deltat)
79 void (*lease_updatetime) (int) = no_lease_updatetime;
85 struct timeval delta, tv1, tv2;
86 static struct timeval maxtime, laststep;
93 timevalsub(&delta, &tv1);
96 * If the system is secure, we do not allow the time to be
97 * set to a value earlier than 1 second less than the highest
98 * time we have yet seen. The worst a miscreant can do in
99 * this circumstance is "freeze" time. He couldn't go
102 * We similarly do not allow the clock to be stepped more
103 * than one second, nor more than once per second. This allows
104 * a miscreant to make the clock march double-time, but no worse.
106 if (securelevel > 1) {
107 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
109 * Update maxtime to latest time we've seen.
111 if (tv1.tv_sec > maxtime.tv_sec)
114 timevalsub(&tv2, &maxtime);
115 if (tv2.tv_sec < -1) {
116 tv->tv_sec = maxtime.tv_sec - 1;
117 printf("Time adjustment clamped to -1 second\n");
120 if (tv1.tv_sec == laststep.tv_sec) {
124 if (delta.tv_sec > 1) {
125 tv->tv_sec = tv1.tv_sec + 1;
126 printf("Time adjustment clamped to +1 second\n");
132 ts.tv_sec = tv->tv_sec;
133 ts.tv_nsec = tv->tv_usec * 1000;
134 set_timecounter(&ts);
135 (void) splsoftclock();
136 lease_updatetime(delta.tv_sec);
144 clock_gettime(struct clock_gettime_args *uap)
148 if (SCARG(uap, clock_id) != CLOCK_REALTIME)
151 return (copyout(&ats, SCARG(uap, tp), sizeof(ats)));
156 clock_settime(struct clock_settime_args *uap)
158 struct thread *td = curthread;
163 if ((error = suser(td)) != 0)
165 if (SCARG(uap, clock_id) != CLOCK_REALTIME)
167 if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
169 if (ats.tv_nsec < 0 || ats.tv_nsec >= 1000000000)
171 /* XXX Don't convert nsec->usec and back */
172 TIMESPEC_TO_TIMEVAL(&atv, &ats);
173 if ((error = settime(&atv)))
179 clock_getres(struct clock_getres_args *uap)
184 if (SCARG(uap, clock_id) != CLOCK_REALTIME)
187 if (SCARG(uap, tp)) {
190 * Round up the result of the division cheaply by adding 1.
191 * Rounding up is especially important if rounding down
192 * would give 0. Perfect rounding is unimportant.
194 ts.tv_nsec = 1000000000 / timecounter->tc_frequency + 1;
195 error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
203 nanosleep1(struct timespec *rqt, struct timespec *rmt)
205 struct timespec ts, ts2, ts3;
209 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
211 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
214 timespecadd(&ts, rqt);
215 TIMESPEC_TO_TIMEVAL(&tv, rqt);
217 error = tsleep(&nanowait, PCATCH, "nanslp",
220 if (error != EWOULDBLOCK) {
221 if (error == ERESTART)
224 timespecsub(&ts, &ts2);
231 if (timespeccmp(&ts2, &ts, >=))
234 timespecsub(&ts3, &ts2);
235 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
239 static void nanosleep_done(void *arg);
240 static void nanosleep_copyout(union sysunion *sysun);
244 nanosleep(struct nanosleep_args *uap)
247 struct sysmsg_sleep *smsleep = &uap->sysmsg.sm.sleep;
249 error = copyin(uap->rqtp, &smsleep->rqt, sizeof(smsleep->rqt));
253 * YYY clean this up to always use the callout, note that an abort
254 * implementation should record the residual in the async case.
256 if (uap->sysmsg.lmsg.ms_flags & MSGF_ASYNC) {
259 ticks = (quad_t)smsleep->rqt.tv_nsec * hz / 1000000000LL;
260 if (smsleep->rqt.tv_sec)
261 ticks += (quad_t)smsleep->rqt.tv_sec * hz;
268 uap->sysmsg.copyout = nanosleep_copyout;
269 callout_init(&smsleep->timer);
270 callout_reset(&smsleep->timer, ticks, nanosleep_done, uap);
275 * Old synchronous sleep code, copyout the residual if
276 * nanosleep was interrupted.
278 error = nanosleep1(&smsleep->rqt, &smsleep->rmt);
279 if (error && SCARG(uap, rmtp))
280 error = copyout(&smsleep->rmt, SCARG(uap, rmtp), sizeof(smsleep->rmt));
286 * Asynch completion for the nanosleep() syscall. This function may be
287 * called from any context and cannot legally access the originating
288 * thread, proc, or its user space.
290 * YYY change the callout interface API so we can simply assign the replymsg
291 * function to it directly.
294 nanosleep_done(void *arg)
296 struct nanosleep_args *uap = arg;
298 lwkt_replymsg(&uap->sysmsg.lmsg, 0);
302 * Asynch return for the nanosleep() syscall, called in the context of the
303 * originating thread when it pulls the message off the reply port. This
304 * function is responsible for any copyouts to userland. Kernel threads
305 * which do their own internal system calls will not usually call the return
309 nanosleep_copyout(union sysunion *sysun)
311 struct nanosleep_args *uap = &sysun->nanosleep;
312 struct sysmsg_sleep *smsleep = &uap->sysmsg.sm.sleep;
314 if (sysun->lmsg.ms_error && uap->rmtp) {
315 sysun->lmsg.ms_error =
316 copyout(&smsleep->rmt, uap->rmtp, sizeof(smsleep->rmt));
322 gettimeofday(struct gettimeofday_args *uap)
329 if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
334 error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
341 settimeofday(struct settimeofday_args *uap)
343 struct thread *td = curthread;
348 if ((error = suser(td)))
350 /* Verify all parameters before changing time. */
352 if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
355 if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
359 (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
361 if (uap->tv && (error = settime(&atv)))
368 int tickdelta; /* current clock skew, us. per tick */
369 long timedelta; /* unapplied time correction, us. */
370 static long bigadj = 1000000; /* use 10x skew above bigadj us. */
374 adjtime(struct adjtime_args *uap)
376 struct thread *td = curthread;
378 long ndelta, ntickdelta, odelta;
381 if ((error = suser(td)))
384 copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
388 * Compute the total correction and the rate at which to apply it.
389 * Round the adjustment down to a whole multiple of the per-tick
390 * delta, so that after some number of incremental changes in
391 * hardclock(), tickdelta will become zero, lest the correction
392 * overshoot and start taking us away from the desired final time.
394 ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
395 if (ndelta > bigadj || ndelta < -bigadj)
396 ntickdelta = 10 * tickadj;
398 ntickdelta = tickadj;
399 if (ndelta % ntickdelta)
400 ndelta = ndelta / ntickdelta * ntickdelta;
403 * To make hardclock()'s job easier, make the per-tick delta negative
404 * if we want time to run slower; then hardclock can simply compute
405 * tick + tickdelta, and subtract tickdelta from timedelta.
408 ntickdelta = -ntickdelta;
412 tickdelta = ntickdelta;
416 atv.tv_sec = odelta / 1000000;
417 atv.tv_usec = odelta % 1000000;
418 (void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
419 sizeof(struct timeval));
425 * Get value of an interval timer. The process virtual and
426 * profiling virtual time timers are kept in the p_stats area, since
427 * they can be swapped out. These are kept internally in the
428 * way they are specified externally: in time until they expire.
430 * The real time interval timer is kept in the process table slot
431 * for the process, and its value (it_value) is kept as an
432 * absolute time rather than as a delta, so that it is easy to keep
433 * periodic real-time signals from drifting.
435 * Virtual time timers are processed in the hardclock() routine of
436 * kern_clock.c. The real time timer is processed by a timeout
437 * routine, called from the softclock() routine. Since a callout
438 * may be delayed in real time due to interrupt processing in the system,
439 * it is possible for the real time timeout routine (realitexpire, given below),
440 * to be delayed in real time past when it is supposed to occur. It
441 * does not suffice, therefore, to reload the real timer .it_value from the
442 * real time timers .it_interval. Rather, we compute the next time in
443 * absolute time the timer should go off.
447 getitimer(struct getitimer_args *uap)
449 struct proc *p = curproc;
451 struct itimerval aitv;
454 if (uap->which > ITIMER_PROF)
456 s = splclock(); /* XXX still needed ? */
457 if (uap->which == ITIMER_REAL) {
459 * Convert from absolute to relative time in .it_value
460 * part of real time timer. If time for real time timer
461 * has passed return 0, else return difference between
462 * current time and time for the timer to go off.
464 aitv = p->p_realtimer;
465 if (timevalisset(&aitv.it_value)) {
466 getmicrouptime(&ctv);
467 if (timevalcmp(&aitv.it_value, &ctv, <))
468 timevalclear(&aitv.it_value);
470 timevalsub(&aitv.it_value, &ctv);
473 aitv = p->p_stats->p_timer[uap->which];
475 return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
476 sizeof (struct itimerval)));
481 setitimer(struct setitimer_args *uap)
483 struct itimerval aitv;
485 struct itimerval *itvp;
486 struct proc *p = curproc;
489 if (uap->which > ITIMER_PROF)
492 if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
493 sizeof(struct itimerval))))
495 if ((uap->itv = uap->oitv) &&
496 (error = getitimer((struct getitimer_args *)uap)))
500 if (itimerfix(&aitv.it_value))
502 if (!timevalisset(&aitv.it_value))
503 timevalclear(&aitv.it_interval);
504 else if (itimerfix(&aitv.it_interval))
506 s = splclock(); /* XXX: still needed ? */
507 if (uap->which == ITIMER_REAL) {
508 if (timevalisset(&p->p_realtimer.it_value))
509 untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
510 if (timevalisset(&aitv.it_value))
511 p->p_ithandle = timeout(realitexpire, (caddr_t)p,
512 tvtohz(&aitv.it_value));
513 getmicrouptime(&ctv);
514 timevaladd(&aitv.it_value, &ctv);
515 p->p_realtimer = aitv;
517 p->p_stats->p_timer[uap->which] = aitv;
523 * Real interval timer expired:
524 * send process whose timer expired an alarm signal.
525 * If time is not set up to reload, then just return.
526 * Else compute next time timer should go off which is > current time.
527 * This is where delay in processing this timeout causes multiple
528 * SIGALRM calls to be compressed into one.
529 * tvtohz() always adds 1 to allow for the time until the next clock
530 * interrupt being strictly less than 1 clock tick, but we don't want
531 * that here since we want to appear to be in sync with the clock
532 * interrupt even when we're delayed.
539 struct timeval ctv, ntv;
542 p = (struct proc *)arg;
544 if (!timevalisset(&p->p_realtimer.it_interval)) {
545 timevalclear(&p->p_realtimer.it_value);
549 s = splclock(); /* XXX: still neeeded ? */
550 timevaladd(&p->p_realtimer.it_value,
551 &p->p_realtimer.it_interval);
552 getmicrouptime(&ctv);
553 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
554 ntv = p->p_realtimer.it_value;
555 timevalsub(&ntv, &ctv);
556 p->p_ithandle = timeout(realitexpire, (caddr_t)p,
566 * Check that a proposed value to load into the .it_value or
567 * .it_interval part of an interval timer is acceptable, and
568 * fix it to have at least minimal value (i.e. if it is less
569 * than the resolution of the clock, round it up.)
576 if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
577 tv->tv_usec < 0 || tv->tv_usec >= 1000000)
579 if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
585 * Decrement an interval timer by a specified number
586 * of microseconds, which must be less than a second,
587 * i.e. < 1000000. If the timer expires, then reload
588 * it. In this case, carry over (usec - old value) to
589 * reduce the value reloaded into the timer so that
590 * the timer does not drift. This routine assumes
591 * that it is called in a context where the timers
592 * on which it is operating cannot change in value.
595 itimerdecr(itp, usec)
596 struct itimerval *itp;
600 if (itp->it_value.tv_usec < usec) {
601 if (itp->it_value.tv_sec == 0) {
602 /* expired, and already in next interval */
603 usec -= itp->it_value.tv_usec;
606 itp->it_value.tv_usec += 1000000;
607 itp->it_value.tv_sec--;
609 itp->it_value.tv_usec -= usec;
611 if (timevalisset(&itp->it_value))
613 /* expired, exactly at end of interval */
615 if (timevalisset(&itp->it_interval)) {
616 itp->it_value = itp->it_interval;
617 itp->it_value.tv_usec -= usec;
618 if (itp->it_value.tv_usec < 0) {
619 itp->it_value.tv_usec += 1000000;
620 itp->it_value.tv_sec--;
623 itp->it_value.tv_usec = 0; /* sec is already 0 */
628 * Add and subtract routines for timevals.
629 * N.B.: subtract routine doesn't deal with
630 * results which are before the beginning,
631 * it just gets very confused in this case.
636 struct timeval *t1, *t2;
639 t1->tv_sec += t2->tv_sec;
640 t1->tv_usec += t2->tv_usec;
646 struct timeval *t1, *t2;
649 t1->tv_sec -= t2->tv_sec;
650 t1->tv_usec -= t2->tv_usec;
659 if (t1->tv_usec < 0) {
661 t1->tv_usec += 1000000;
663 if (t1->tv_usec >= 1000000) {
665 t1->tv_usec -= 1000000;
670 * ratecheck(): simple time-based rate-limit checking.
673 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
675 struct timeval tv, delta;
678 getmicrouptime(&tv); /* NB: 10ms precision */
680 timevalsub(&delta, lasttime);
683 * check for 0,0 is so that the message will be seen at least once,
684 * even if interval is huge.
686 if (timevalcmp(&delta, mininterval, >=) ||
687 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
696 * ppsratecheck(): packets (or events) per second limitation.
698 * Return 0 if the limit is to be enforced (e.g. the caller
699 * should drop a packet because of the rate limitation).
701 * maxpps of 0 always causes zero to be returned. maxpps of -1
702 * always causes 1 to be returned; this effectively defeats rate
705 * Note that we maintain the struct timeval for compatibility
706 * with other bsd systems. We reuse the storage and just monitor
707 * clock ticks for minimal overhead.
710 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
715 * Reset the last time and counter if this is the first call
716 * or more than a second has passed since the last update of
720 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
721 lasttime->tv_sec = now;
723 return (maxpps != 0);
725 (*curpps)++; /* NB: ignore potential overflow */
726 return (maxpps < 0 || *curpps < maxpps);