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 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)kern_time.c 8.1 (Berkeley) 6/10/93
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
38 #include <sys/systm.h>
40 #include <sys/mutex.h>
41 #include <sys/sysproto.h>
42 #include <sys/resourcevar.h>
43 #include <sys/signalvar.h>
44 #include <sys/kernel.h>
46 #include <sys/syscallsubr.h>
47 #include <sys/sysent.h>
50 #include <sys/timetc.h>
51 #include <sys/vnode.h>
54 #include <vm/vm_extern.h>
60 * Time of day and interval timer support.
62 * These routines provide the kernel entry points to get and set
63 * the time-of-day and per-process interval timers. Subroutines
64 * here provide support for adding and subtracting timeval structures
65 * and decrementing interval timers, optionally reloading the interval
66 * timers when they expire.
69 static int settime(struct thread *, 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;
82 settime(struct thread *td, struct timeval *tv)
84 struct timeval delta, tv1, tv2;
85 static struct timeval maxtime, laststep;
92 timevalsub(&delta, &tv1);
95 * If the system is secure, we do not allow the time to be
96 * set to a value earlier than 1 second less than the highest
97 * time we have yet seen. The worst a miscreant can do in
98 * this circumstance is "freeze" time. He couldn't go
101 * We similarly do not allow the clock to be stepped more
102 * than one second, nor more than once per second. This allows
103 * a miscreant to make the clock march double-time, but no worse.
105 if (securelevel_gt(td->td_ucred, 1) != 0) {
106 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
108 * Update maxtime to latest time we've seen.
110 if (tv1.tv_sec > maxtime.tv_sec)
113 timevalsub(&tv2, &maxtime);
114 if (tv2.tv_sec < -1) {
115 tv->tv_sec = maxtime.tv_sec - 1;
116 printf("Time adjustment clamped to -1 second\n");
119 if (tv1.tv_sec == laststep.tv_sec) {
123 if (delta.tv_sec > 1) {
124 tv->tv_sec = tv1.tv_sec + 1;
125 printf("Time adjustment clamped to +1 second\n");
131 ts.tv_sec = tv->tv_sec;
132 ts.tv_nsec = tv->tv_usec * 1000;
135 (void) splsoftclock();
136 lease_updatetime(delta.tv_sec);
143 #ifndef _SYS_SYSPROTO_H_
144 struct clock_gettime_args {
155 clock_gettime(struct thread *td, struct clock_gettime_args *uap)
160 error = kern_clock_gettime(td, uap->clock_id, &ats);
162 error = copyout(&ats, uap->tp, sizeof(ats));
168 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
170 struct timeval sys, user;
180 calcru(p, &user, &sys);
182 TIMEVAL_TO_TIMESPEC(&user, ats);
186 calcru(p, &user, &sys);
188 timevaladd(&user, &sys);
189 TIMEVAL_TO_TIMESPEC(&user, ats);
191 case CLOCK_MONOTONIC:
200 #ifndef _SYS_SYSPROTO_H_
201 struct clock_settime_args {
203 const struct timespec *tp;
212 clock_settime(struct thread *td, struct clock_settime_args *uap)
217 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
219 return (kern_clock_settime(td, uap->clock_id, &ats));
223 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
229 error = mac_check_system_settime(td->td_ucred);
233 if ((error = suser(td)) != 0)
235 if (clock_id != CLOCK_REALTIME)
237 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
239 /* XXX Don't convert nsec->usec and back */
240 TIMESPEC_TO_TIMEVAL(&atv, ats);
241 error = settime(td, &atv);
245 #ifndef _SYS_SYSPROTO_H_
246 struct clock_getres_args {
253 clock_getres(struct thread *td, struct clock_getres_args *uap)
261 error = kern_clock_getres(td, uap->clock_id, &ts);
263 error = copyout(&ts, uap->tp, sizeof(ts));
268 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
274 case CLOCK_MONOTONIC:
276 * Round up the result of the division cheaply by adding 1.
277 * Rounding up is especially important if rounding down
278 * would give 0. Perfect rounding is unimportant.
280 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
284 /* Accurately round up here because we can do so cheaply. */
285 ts->tv_nsec = (1000000000 + hz - 1) / hz;
296 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
298 struct timespec ts, ts2, ts3;
302 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
304 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
307 timespecadd(&ts, rqt);
308 TIMESPEC_TO_TIMEVAL(&tv, rqt);
310 error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
313 if (error != EWOULDBLOCK) {
314 if (error == ERESTART)
317 timespecsub(&ts, &ts2);
324 if (timespeccmp(&ts2, &ts, >=))
327 timespecsub(&ts3, &ts2);
328 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
332 #ifndef _SYS_SYSPROTO_H_
333 struct nanosleep_args {
334 struct timespec *rqtp;
335 struct timespec *rmtp;
344 nanosleep(struct thread *td, struct nanosleep_args *uap)
346 struct timespec rmt, rqt;
349 error = copyin(uap->rqtp, &rqt, sizeof(rqt));
354 !useracc((caddr_t)uap->rmtp, sizeof(rmt), VM_PROT_WRITE))
356 error = kern_nanosleep(td, &rqt, &rmt);
357 if (error && uap->rmtp) {
360 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
367 #ifndef _SYS_SYSPROTO_H_
368 struct gettimeofday_args {
370 struct timezone *tzp;
378 gettimeofday(struct thread *td, struct gettimeofday_args *uap)
386 error = copyout(&atv, uap->tp, sizeof (atv));
388 if (error == 0 && uap->tzp != NULL) {
389 rtz.tz_minuteswest = tz_minuteswest;
390 rtz.tz_dsttime = tz_dsttime;
391 error = copyout(&rtz, uap->tzp, sizeof (rtz));
396 #ifndef _SYS_SYSPROTO_H_
397 struct settimeofday_args {
399 struct timezone *tzp;
407 settimeofday(struct thread *td, struct settimeofday_args *uap)
409 struct timeval atv, *tvp;
410 struct timezone atz, *tzp;
414 error = copyin(uap->tv, &atv, sizeof(atv));
421 error = copyin(uap->tzp, &atz, sizeof(atz));
427 return (kern_settimeofday(td, tvp, tzp));
431 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
436 error = mac_check_system_settime(td->td_ucred);
443 /* Verify all parameters before changing time. */
445 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
447 error = settime(td, tv);
449 if (tzp && error == 0) {
450 tz_minuteswest = tzp->tz_minuteswest;
451 tz_dsttime = tzp->tz_dsttime;
457 * Get value of an interval timer. The process virtual and
458 * profiling virtual time timers are kept in the p_stats area, since
459 * they can be swapped out. These are kept internally in the
460 * way they are specified externally: in time until they expire.
462 * The real time interval timer is kept in the process table slot
463 * for the process, and its value (it_value) is kept as an
464 * absolute time rather than as a delta, so that it is easy to keep
465 * periodic real-time signals from drifting.
467 * Virtual time timers are processed in the hardclock() routine of
468 * kern_clock.c. The real time timer is processed by a timeout
469 * routine, called from the softclock() routine. Since a callout
470 * may be delayed in real time due to interrupt processing in the system,
471 * it is possible for the real time timeout routine (realitexpire, given below),
472 * to be delayed in real time past when it is supposed to occur. It
473 * does not suffice, therefore, to reload the real timer .it_value from the
474 * real time timers .it_interval. Rather, we compute the next time in
475 * absolute time the timer should go off.
477 #ifndef _SYS_SYSPROTO_H_
478 struct getitimer_args {
480 struct itimerval *itv;
487 getitimer(struct thread *td, struct getitimer_args *uap)
489 struct itimerval aitv;
492 error = kern_getitimer(td, uap->which, &aitv);
495 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
499 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
501 struct proc *p = td->td_proc;
504 if (which > ITIMER_PROF)
507 if (which == ITIMER_REAL) {
509 * Convert from absolute to relative time in .it_value
510 * part of real time timer. If time for real time timer
511 * has passed return 0, else return difference between
512 * current time and time for the timer to go off.
515 *aitv = p->p_realtimer;
517 if (timevalisset(&aitv->it_value)) {
518 getmicrouptime(&ctv);
519 if (timevalcmp(&aitv->it_value, &ctv, <))
520 timevalclear(&aitv->it_value);
522 timevalsub(&aitv->it_value, &ctv);
525 mtx_lock_spin(&sched_lock);
526 *aitv = p->p_stats->p_timer[which];
527 mtx_unlock_spin(&sched_lock);
532 #ifndef _SYS_SYSPROTO_H_
533 struct setitimer_args {
535 struct itimerval *itv, *oitv;
543 setitimer(struct thread *td, struct setitimer_args *uap)
545 struct itimerval aitv, oitv;
548 if (uap->itv == NULL) {
549 uap->itv = uap->oitv;
550 return (getitimer(td, (struct getitimer_args *)uap));
553 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
555 error = kern_setitimer(td, uap->which, &aitv, &oitv);
556 if (error != 0 || uap->oitv == NULL)
558 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
562 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
563 struct itimerval *oitv)
565 struct proc *p = td->td_proc;
569 return (kern_getitimer(td, which, oitv));
571 if (which > ITIMER_PROF)
573 if (itimerfix(&aitv->it_value))
575 if (!timevalisset(&aitv->it_value))
576 timevalclear(&aitv->it_interval);
577 else if (itimerfix(&aitv->it_interval))
580 if (which == ITIMER_REAL) {
582 if (timevalisset(&p->p_realtimer.it_value))
583 callout_stop(&p->p_itcallout);
584 getmicrouptime(&ctv);
585 if (timevalisset(&aitv->it_value)) {
586 callout_reset(&p->p_itcallout, tvtohz(&aitv->it_value),
588 timevaladd(&aitv->it_value, &ctv);
590 *oitv = p->p_realtimer;
591 p->p_realtimer = *aitv;
593 if (timevalisset(&oitv->it_value)) {
594 if (timevalcmp(&oitv->it_value, &ctv, <))
595 timevalclear(&oitv->it_value);
597 timevalsub(&oitv->it_value, &ctv);
600 mtx_lock_spin(&sched_lock);
601 *oitv = p->p_stats->p_timer[which];
602 p->p_stats->p_timer[which] = *aitv;
603 mtx_unlock_spin(&sched_lock);
609 * Real interval timer expired:
610 * send process whose timer expired an alarm signal.
611 * If time is not set up to reload, then just return.
612 * Else compute next time timer should go off which is > current time.
613 * This is where delay in processing this timeout causes multiple
614 * SIGALRM calls to be compressed into one.
615 * tvtohz() always adds 1 to allow for the time until the next clock
616 * interrupt being strictly less than 1 clock tick, but we don't want
617 * that here since we want to appear to be in sync with the clock
618 * interrupt even when we're delayed.
621 realitexpire(void *arg)
624 struct timeval ctv, ntv;
626 p = (struct proc *)arg;
629 if (!timevalisset(&p->p_realtimer.it_interval)) {
630 timevalclear(&p->p_realtimer.it_value);
631 if (p->p_flag & P_WEXIT)
632 wakeup(&p->p_itcallout);
637 timevaladd(&p->p_realtimer.it_value,
638 &p->p_realtimer.it_interval);
639 getmicrouptime(&ctv);
640 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
641 ntv = p->p_realtimer.it_value;
642 timevalsub(&ntv, &ctv);
643 callout_reset(&p->p_itcallout, tvtohz(&ntv) - 1,
653 * Check that a proposed value to load into the .it_value or
654 * .it_interval part of an interval timer is acceptable, and
655 * fix it to have at least minimal value (i.e. if it is less
656 * than the resolution of the clock, round it up.)
659 itimerfix(struct timeval *tv)
662 if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
663 tv->tv_usec < 0 || tv->tv_usec >= 1000000)
665 if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
671 * Decrement an interval timer by a specified number
672 * of microseconds, which must be less than a second,
673 * i.e. < 1000000. If the timer expires, then reload
674 * it. In this case, carry over (usec - old value) to
675 * reduce the value reloaded into the timer so that
676 * the timer does not drift. This routine assumes
677 * that it is called in a context where the timers
678 * on which it is operating cannot change in value.
681 itimerdecr(struct itimerval *itp, int usec)
684 if (itp->it_value.tv_usec < usec) {
685 if (itp->it_value.tv_sec == 0) {
686 /* expired, and already in next interval */
687 usec -= itp->it_value.tv_usec;
690 itp->it_value.tv_usec += 1000000;
691 itp->it_value.tv_sec--;
693 itp->it_value.tv_usec -= usec;
695 if (timevalisset(&itp->it_value))
697 /* expired, exactly at end of interval */
699 if (timevalisset(&itp->it_interval)) {
700 itp->it_value = itp->it_interval;
701 itp->it_value.tv_usec -= usec;
702 if (itp->it_value.tv_usec < 0) {
703 itp->it_value.tv_usec += 1000000;
704 itp->it_value.tv_sec--;
707 itp->it_value.tv_usec = 0; /* sec is already 0 */
712 * Add and subtract routines for timevals.
713 * N.B.: subtract routine doesn't deal with
714 * results which are before the beginning,
715 * it just gets very confused in this case.
719 timevaladd(struct timeval *t1, const struct timeval *t2)
722 t1->tv_sec += t2->tv_sec;
723 t1->tv_usec += t2->tv_usec;
728 timevalsub(struct timeval *t1, const struct timeval *t2)
731 t1->tv_sec -= t2->tv_sec;
732 t1->tv_usec -= t2->tv_usec;
737 timevalfix(struct timeval *t1)
740 if (t1->tv_usec < 0) {
742 t1->tv_usec += 1000000;
744 if (t1->tv_usec >= 1000000) {
746 t1->tv_usec -= 1000000;
751 * ratecheck(): simple time-based rate-limit checking.
754 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
756 struct timeval tv, delta;
759 getmicrouptime(&tv); /* NB: 10ms precision */
761 timevalsub(&delta, lasttime);
764 * check for 0,0 is so that the message will be seen at least once,
765 * even if interval is huge.
767 if (timevalcmp(&delta, mininterval, >=) ||
768 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
777 * ppsratecheck(): packets (or events) per second limitation.
779 * Return 0 if the limit is to be enforced (e.g. the caller
780 * should drop a packet because of the rate limitation).
782 * maxpps of 0 always causes zero to be returned. maxpps of -1
783 * always causes 1 to be returned; this effectively defeats rate
786 * Note that we maintain the struct timeval for compatibility
787 * with other bsd systems. We reuse the storage and just monitor
788 * clock ticks for minimal overhead.
791 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
796 * Reset the last time and counter if this is the first call
797 * or more than a second has passed since the last update of
801 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
802 lasttime->tv_sec = now;
804 return (maxpps != 0);
806 (*curpps)++; /* NB: ignore potential overflow */
807 return (maxpps < 0 || *curpps < maxpps);