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.40 2008/04/02 14:16:16 sephe 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>
51 #include <sys/vnode.h>
52 #include <sys/sysctl.h>
53 #include <sys/kern_syscall.h>
55 #include <vm/vm_extern.h>
57 #include <sys/msgport2.h>
58 #include <sys/thread2.h>
59 #include <sys/mplock2.h>
64 * Time of day and interval timer support.
66 * These routines provide the kernel entry points to get and set
67 * the time-of-day and per-process interval timers. Subroutines
68 * here provide support for adding and subtracting timeval structures
69 * and decrementing interval timers, optionally reloading the interval
70 * timers when they expire.
73 int nanosleep1(struct timespec *rqt, struct timespec *rmt);
74 static int settime(struct timeval *);
75 static void timevalfix(struct timeval *);
77 static int sleep_hard_us = 100;
78 SYSCTL_INT(_kern, OID_AUTO, sleep_hard_us, CTLFLAG_RW, &sleep_hard_us, 0, "")
81 settime(struct timeval *tv)
83 struct timeval delta, tv1, tv2;
84 static struct timeval maxtime, laststep;
88 if ((origcpu = mycpu->gd_cpuid) != 0)
89 lwkt_setcpu_self(globaldata_find(0));
94 timevalsub(&delta, &tv1);
97 * If the system is secure, we do not allow the time to be
98 * set to a value earlier than 1 second less than the highest
99 * time we have yet seen. The worst a miscreant can do in
100 * this circumstance is "freeze" time. He couldn't go
103 * We similarly do not allow the clock to be stepped more
104 * than one second, nor more than once per second. This allows
105 * a miscreant to make the clock march double-time, but no worse.
107 if (securelevel > 1) {
108 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
110 * Update maxtime to latest time we've seen.
112 if (tv1.tv_sec > maxtime.tv_sec)
115 timevalsub(&tv2, &maxtime);
116 if (tv2.tv_sec < -1) {
117 tv->tv_sec = maxtime.tv_sec - 1;
118 kprintf("Time adjustment clamped to -1 second\n");
121 if (tv1.tv_sec == laststep.tv_sec) {
125 if (delta.tv_sec > 1) {
126 tv->tv_sec = tv1.tv_sec + 1;
127 kprintf("Time adjustment clamped to +1 second\n");
133 ts.tv_sec = tv->tv_sec;
134 ts.tv_nsec = tv->tv_usec * 1000;
139 lwkt_setcpu_self(globaldata_find(origcpu));
149 kern_clock_gettime(clockid_t clock_id, struct timespec *ats)
157 case CLOCK_MONOTONIC:
171 sys_clock_gettime(struct clock_gettime_args *uap)
176 error = kern_clock_gettime(uap->clock_id, &ats);
178 error = copyout(&ats, uap->tp, sizeof(ats));
184 kern_clock_settime(clockid_t clock_id, struct timespec *ats)
186 struct thread *td = curthread;
190 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
192 if (clock_id != CLOCK_REALTIME)
194 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
197 TIMESPEC_TO_TIMEVAL(&atv, ats);
198 error = settime(&atv);
206 sys_clock_settime(struct clock_settime_args *uap)
211 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
215 error = kern_clock_settime(uap->clock_id, &ats);
224 kern_clock_getres(clockid_t clock_id, struct timespec *ts)
230 case CLOCK_MONOTONIC:
232 * Round up the result of the division cheaply
233 * by adding 1. Rounding up is especially important
234 * if rounding down would give 0. Perfect rounding
238 ts->tv_nsec = 1000000000 / sys_cputimer->freq + 1;
253 sys_clock_getres(struct clock_getres_args *uap)
258 error = kern_clock_getres(uap->clock_id, &ts);
260 error = copyout(&ts, uap->tp, sizeof(ts));
268 * This is a general helper function for nanosleep() (aka sleep() aka
271 * If there is less then one tick's worth of time left and
272 * we haven't done a yield, or the remaining microseconds is
273 * ridiculously low, do a yield. This avoids having
274 * to deal with systimer overheads when the system is under
275 * heavy loads. If we have done a yield already then use
276 * a systimer and an uninterruptable thread wait.
278 * If there is more then a tick's worth of time left,
279 * calculate the baseline ticks and use an interruptable
280 * tsleep, then handle the fine-grained delay on the next
281 * loop. This usually results in two sleeps occuring, a long one
287 ns1_systimer(systimer_t info, int in_ipi __unused,
288 struct intrframe *frame __unused)
290 lwkt_schedule(info->data);
294 nanosleep1(struct timespec *rqt, struct timespec *rmt)
297 struct timespec ts, ts2, ts3;
301 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
303 /* XXX: imho this should return EINVAL at least for tv_sec < 0 */
304 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
307 timespecadd(&ts, rqt); /* ts = target timestamp compare */
308 TIMESPEC_TO_TIMEVAL(&tv, rqt); /* tv = sleep interval */
312 struct systimer info;
314 ticks = tv.tv_usec / ustick; /* approximate */
316 if (tv.tv_sec == 0 && ticks == 0) {
317 thread_t td = curthread;
318 if (tv.tv_usec < sleep_hard_us) {
321 crit_enter_quick(td);
322 systimer_init_oneshot(&info, ns1_systimer,
324 lwkt_deschedule_self(td);
327 systimer_del(&info); /* make sure it's gone */
329 error = iscaught(td->td_lwp);
330 } else if (tv.tv_sec == 0) {
331 error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
333 ticks = tvtohz_low(&tv); /* also handles overflow */
334 error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
337 if (error && error != EWOULDBLOCK) {
338 if (error == ERESTART)
341 timespecsub(&ts, &ts2);
348 if (timespeccmp(&ts2, &ts, >=))
351 timespecsub(&ts3, &ts2);
352 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
360 sys_nanosleep(struct nanosleep_args *uap)
366 error = copyin(uap->rqtp, &rqt, sizeof(rqt));
370 error = nanosleep1(&rqt, &rmt);
373 * copyout the residual if nanosleep was interrupted.
375 if (error && uap->rmtp) {
378 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
389 sys_gettimeofday(struct gettimeofday_args *uap)
396 if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
401 error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
410 sys_settimeofday(struct settimeofday_args *uap)
412 struct thread *td = curthread;
417 if ((error = priv_check(td, PRIV_SETTIMEOFDAY)))
419 /* Verify all parameters before changing time. */
421 if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
424 if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
428 (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
432 if (uap->tv && (error = settime(&atv))) {
443 kern_adjtime_common(void)
445 if ((ntp_delta >= 0 && ntp_delta < ntp_default_tick_delta) ||
446 (ntp_delta < 0 && ntp_delta > -ntp_default_tick_delta))
447 ntp_tick_delta = ntp_delta;
448 else if (ntp_delta > ntp_big_delta)
449 ntp_tick_delta = 10 * ntp_default_tick_delta;
450 else if (ntp_delta < -ntp_big_delta)
451 ntp_tick_delta = -10 * ntp_default_tick_delta;
452 else if (ntp_delta > 0)
453 ntp_tick_delta = ntp_default_tick_delta;
455 ntp_tick_delta = -ntp_default_tick_delta;
459 kern_adjtime(int64_t delta, int64_t *odelta)
463 if ((origcpu = mycpu->gd_cpuid) != 0)
464 lwkt_setcpu_self(globaldata_find(0));
469 kern_adjtime_common();
473 lwkt_setcpu_self(globaldata_find(origcpu));
477 kern_get_ntp_delta(int64_t *delta)
481 if ((origcpu = mycpu->gd_cpuid) != 0)
482 lwkt_setcpu_self(globaldata_find(0));
489 lwkt_setcpu_self(globaldata_find(origcpu));
493 kern_reladjtime(int64_t delta)
497 if ((origcpu = mycpu->gd_cpuid) != 0)
498 lwkt_setcpu_self(globaldata_find(0));
502 kern_adjtime_common();
506 lwkt_setcpu_self(globaldata_find(origcpu));
510 kern_adjfreq(int64_t rate)
514 if ((origcpu = mycpu->gd_cpuid) != 0)
515 lwkt_setcpu_self(globaldata_find(0));
518 ntp_tick_permanent = rate;
522 lwkt_setcpu_self(globaldata_find(origcpu));
529 sys_adjtime(struct adjtime_args *uap)
531 struct thread *td = curthread;
533 int64_t ndelta, odelta;
536 if ((error = priv_check(td, PRIV_ADJTIME)))
538 error = copyin(uap->delta, &atv, sizeof(struct timeval));
543 * Compute the total correction and the rate at which to apply it.
544 * Round the adjustment down to a whole multiple of the per-tick
545 * delta, so that after some number of incremental changes in
546 * hardclock(), tickdelta will become zero, lest the correction
547 * overshoot and start taking us away from the desired final time.
549 ndelta = (int64_t)atv.tv_sec * 1000000000 + atv.tv_usec * 1000;
551 kern_adjtime(ndelta, &odelta);
555 atv.tv_sec = odelta / 1000000000;
556 atv.tv_usec = odelta % 1000000000 / 1000;
557 copyout(&atv, uap->olddelta, sizeof(struct timeval));
563 sysctl_adjtime(SYSCTL_HANDLER_ARGS)
568 if (req->newptr != NULL) {
569 if (priv_check(curthread, PRIV_ROOT))
571 error = SYSCTL_IN(req, &delta, sizeof(delta));
574 kern_reladjtime(delta);
578 kern_get_ntp_delta(&delta);
579 error = SYSCTL_OUT(req, &delta, sizeof(delta));
584 * delta is in nanoseconds.
587 sysctl_delta(SYSCTL_HANDLER_ARGS)
589 int64_t delta, old_delta;
592 if (req->newptr != NULL) {
593 if (priv_check(curthread, PRIV_ROOT))
595 error = SYSCTL_IN(req, &delta, sizeof(delta));
598 kern_adjtime(delta, &old_delta);
601 if (req->oldptr != NULL)
602 kern_get_ntp_delta(&old_delta);
603 error = SYSCTL_OUT(req, &old_delta, sizeof(old_delta));
608 * frequency is in nanoseconds per second shifted left 32.
609 * kern_adjfreq() needs it in nanoseconds per tick shifted left 32.
612 sysctl_adjfreq(SYSCTL_HANDLER_ARGS)
617 if (req->newptr != NULL) {
618 if (priv_check(curthread, PRIV_ROOT))
620 error = SYSCTL_IN(req, &freqdelta, sizeof(freqdelta));
625 kern_adjfreq(freqdelta);
628 if (req->oldptr != NULL)
629 freqdelta = ntp_tick_permanent * hz;
630 error = SYSCTL_OUT(req, &freqdelta, sizeof(freqdelta));
637 SYSCTL_NODE(_kern, OID_AUTO, ntp, CTLFLAG_RW, 0, "NTP related controls");
638 SYSCTL_PROC(_kern_ntp, OID_AUTO, permanent,
639 CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
640 sysctl_adjfreq, "Q", "permanent correction per second");
641 SYSCTL_PROC(_kern_ntp, OID_AUTO, delta,
642 CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
643 sysctl_delta, "Q", "one-time delta");
644 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, big_delta, CTLFLAG_RD,
645 &ntp_big_delta, sizeof(ntp_big_delta), "Q",
646 "threshold for fast adjustment");
647 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, tick_delta, CTLFLAG_RD,
648 &ntp_tick_delta, sizeof(ntp_tick_delta), "LU",
649 "per-tick adjustment");
650 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, default_tick_delta, CTLFLAG_RD,
651 &ntp_default_tick_delta, sizeof(ntp_default_tick_delta), "LU",
652 "default per-tick adjustment");
653 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, next_leap_second, CTLFLAG_RW,
654 &ntp_leap_second, sizeof(ntp_leap_second), "LU",
656 SYSCTL_INT(_kern_ntp, OID_AUTO, insert_leap_second, CTLFLAG_RW,
657 &ntp_leap_insert, 0, "insert or remove leap second");
658 SYSCTL_PROC(_kern_ntp, OID_AUTO, adjust,
659 CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
660 sysctl_adjtime, "Q", "relative adjust for delta");
663 * Get value of an interval timer. The process virtual and
664 * profiling virtual time timers are kept in the p_stats area, since
665 * they can be swapped out. These are kept internally in the
666 * way they are specified externally: in time until they expire.
668 * The real time interval timer is kept in the process table slot
669 * for the process, and its value (it_value) is kept as an
670 * absolute time rather than as a delta, so that it is easy to keep
671 * periodic real-time signals from drifting.
673 * Virtual time timers are processed in the hardclock() routine of
674 * kern_clock.c. The real time timer is processed by a timeout
675 * routine, called from the softclock() routine. Since a callout
676 * may be delayed in real time due to interrupt processing in the system,
677 * it is possible for the real time timeout routine (realitexpire, given below),
678 * to be delayed in real time past when it is supposed to occur. It
679 * does not suffice, therefore, to reload the real timer .it_value from the
680 * real time timers .it_interval. Rather, we compute the next time in
681 * absolute time the timer should go off.
686 sys_getitimer(struct getitimer_args *uap)
688 struct proc *p = curproc;
690 struct itimerval aitv;
692 if (uap->which > ITIMER_PROF)
696 if (uap->which == ITIMER_REAL) {
698 * Convert from absolute to relative time in .it_value
699 * part of real time timer. If time for real time timer
700 * has passed return 0, else return difference between
701 * current time and time for the timer to go off.
703 aitv = p->p_realtimer;
704 if (timevalisset(&aitv.it_value)) {
705 getmicrouptime(&ctv);
706 if (timevalcmp(&aitv.it_value, &ctv, <))
707 timevalclear(&aitv.it_value);
709 timevalsub(&aitv.it_value, &ctv);
712 aitv = p->p_timer[uap->which];
716 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
723 sys_setitimer(struct setitimer_args *uap)
725 struct itimerval aitv;
727 struct itimerval *itvp;
728 struct proc *p = curproc;
731 if (uap->which > ITIMER_PROF)
734 if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
735 sizeof(struct itimerval))))
737 if ((uap->itv = uap->oitv) &&
738 (error = sys_getitimer((struct getitimer_args *)uap)))
742 if (itimerfix(&aitv.it_value))
744 if (!timevalisset(&aitv.it_value))
745 timevalclear(&aitv.it_interval);
746 else if (itimerfix(&aitv.it_interval))
750 if (uap->which == ITIMER_REAL) {
751 if (timevalisset(&p->p_realtimer.it_value))
752 callout_stop(&p->p_ithandle);
753 if (timevalisset(&aitv.it_value))
754 callout_reset(&p->p_ithandle,
755 tvtohz_high(&aitv.it_value), realitexpire, p);
756 getmicrouptime(&ctv);
757 timevaladd(&aitv.it_value, &ctv);
758 p->p_realtimer = aitv;
760 p->p_timer[uap->which] = aitv;
768 * Real interval timer expired:
769 * send process whose timer expired an alarm signal.
770 * If time is not set up to reload, then just return.
771 * Else compute next time timer should go off which is > current time.
772 * This is where delay in processing this timeout causes multiple
773 * SIGALRM calls to be compressed into one.
774 * tvtohz_high() always adds 1 to allow for the time until the next clock
775 * interrupt being strictly less than 1 clock tick, but we don't want
776 * that here since we want to appear to be in sync with the clock
777 * interrupt even when we're delayed.
780 realitexpire(void *arg)
783 struct timeval ctv, ntv;
785 p = (struct proc *)arg;
787 if (!timevalisset(&p->p_realtimer.it_interval)) {
788 timevalclear(&p->p_realtimer.it_value);
793 timevaladd(&p->p_realtimer.it_value,
794 &p->p_realtimer.it_interval);
795 getmicrouptime(&ctv);
796 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
797 ntv = p->p_realtimer.it_value;
798 timevalsub(&ntv, &ctv);
799 callout_reset(&p->p_ithandle, tvtohz_low(&ntv),
809 * Check that a proposed value to load into the .it_value or
810 * .it_interval part of an interval timer is acceptable, and
811 * fix it to have at least minimal value (i.e. if it is less
812 * than the resolution of the clock, round it up.)
817 itimerfix(struct timeval *tv)
820 if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
821 tv->tv_usec < 0 || tv->tv_usec >= 1000000)
823 if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < ustick)
824 tv->tv_usec = ustick;
829 * Decrement an interval timer by a specified number
830 * of microseconds, which must be less than a second,
831 * i.e. < 1000000. If the timer expires, then reload
832 * it. In this case, carry over (usec - old value) to
833 * reduce the value reloaded into the timer so that
834 * the timer does not drift. This routine assumes
835 * that it is called in a context where the timers
836 * on which it is operating cannot change in value.
839 itimerdecr(struct itimerval *itp, int usec)
842 if (itp->it_value.tv_usec < usec) {
843 if (itp->it_value.tv_sec == 0) {
844 /* expired, and already in next interval */
845 usec -= itp->it_value.tv_usec;
848 itp->it_value.tv_usec += 1000000;
849 itp->it_value.tv_sec--;
851 itp->it_value.tv_usec -= usec;
853 if (timevalisset(&itp->it_value))
855 /* expired, exactly at end of interval */
857 if (timevalisset(&itp->it_interval)) {
858 itp->it_value = itp->it_interval;
859 itp->it_value.tv_usec -= usec;
860 if (itp->it_value.tv_usec < 0) {
861 itp->it_value.tv_usec += 1000000;
862 itp->it_value.tv_sec--;
865 itp->it_value.tv_usec = 0; /* sec is already 0 */
870 * Add and subtract routines for timevals.
871 * N.B.: subtract routine doesn't deal with
872 * results which are before the beginning,
873 * it just gets very confused in this case.
877 timevaladd(struct timeval *t1, const struct timeval *t2)
880 t1->tv_sec += t2->tv_sec;
881 t1->tv_usec += t2->tv_usec;
886 timevalsub(struct timeval *t1, const struct timeval *t2)
889 t1->tv_sec -= t2->tv_sec;
890 t1->tv_usec -= t2->tv_usec;
895 timevalfix(struct timeval *t1)
898 if (t1->tv_usec < 0) {
900 t1->tv_usec += 1000000;
902 if (t1->tv_usec >= 1000000) {
904 t1->tv_usec -= 1000000;
909 * ratecheck(): simple time-based rate-limit checking.
912 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
914 struct timeval tv, delta;
917 getmicrouptime(&tv); /* NB: 10ms precision */
919 timevalsub(&delta, lasttime);
922 * check for 0,0 is so that the message will be seen at least once,
923 * even if interval is huge.
925 if (timevalcmp(&delta, mininterval, >=) ||
926 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
935 * ppsratecheck(): packets (or events) per second limitation.
937 * Return 0 if the limit is to be enforced (e.g. the caller
938 * should drop a packet because of the rate limitation).
940 * maxpps of 0 always causes zero to be returned. maxpps of -1
941 * always causes 1 to be returned; this effectively defeats rate
944 * Note that we maintain the struct timeval for compatibility
945 * with other bsd systems. We reuse the storage and just monitor
946 * clock ticks for minimal overhead.
949 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
954 * Reset the last time and counter if this is the first call
955 * or more than a second has passed since the last update of
959 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
960 lasttime->tv_sec = now;
962 return (maxpps != 0);
964 (*curpps)++; /* NB: ignore potential overflow */
965 return (maxpps < 0 || *curpps < maxpps);