2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)kern_time.c 8.1 (Berkeley) 6/10/93
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include "opt_ktrace.h"
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/limits.h>
42 #include <sys/clock.h>
44 #include <sys/mutex.h>
45 #include <sys/sysproto.h>
46 #include <sys/resourcevar.h>
47 #include <sys/signalvar.h>
48 #include <sys/kernel.h>
49 #include <sys/sleepqueue.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
55 #include <sys/posix4.h>
57 #include <sys/timers.h>
58 #include <sys/timetc.h>
59 #include <sys/vnode.h>
61 #include <sys/ktrace.h>
65 #include <vm/vm_extern.h>
67 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
68 #define CPUCLOCK_BIT 0x80000000
69 #define CPUCLOCK_PROCESS_BIT 0x40000000
70 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
71 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
72 #define MAKE_PROCESS_CPUCLOCK(pid) \
73 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
75 #define NS_PER_SEC 1000000000
77 static struct kclock posix_clocks[MAX_CLOCKS];
78 static uma_zone_t itimer_zone = NULL;
81 * Time of day and interval timer support.
83 * These routines provide the kernel entry points to get and set
84 * the time-of-day and per-process interval timers. Subroutines
85 * here provide support for adding and subtracting timeval structures
86 * and decrementing interval timers, optionally reloading the interval
87 * timers when they expire.
90 static int settime(struct thread *, struct timeval *);
91 static void timevalfix(struct timeval *);
92 static int user_clock_nanosleep(struct thread *td, clockid_t clock_id,
93 int flags, const struct timespec *ua_rqtp,
94 struct timespec *ua_rmtp);
96 static void itimer_start(void);
97 static int itimer_init(void *, int, int);
98 static void itimer_fini(void *, int);
99 static void itimer_enter(struct itimer *);
100 static void itimer_leave(struct itimer *);
101 static struct itimer *itimer_find(struct proc *, int);
102 static void itimers_alloc(struct proc *);
103 static int realtimer_create(struct itimer *);
104 static int realtimer_gettime(struct itimer *, struct itimerspec *);
105 static int realtimer_settime(struct itimer *, int,
106 struct itimerspec *, struct itimerspec *);
107 static int realtimer_delete(struct itimer *);
108 static void realtimer_clocktime(clockid_t, struct timespec *);
109 static void realtimer_expire(void *);
110 static void realtimer_expire_l(struct itimer *it, bool proc_locked);
112 static int register_posix_clock(int, const struct kclock *);
113 static void itimer_fire(struct itimer *it);
114 static int itimespecfix(struct timespec *ts);
116 #define CLOCK_CALL(clock, call, arglist) \
117 ((*posix_clocks[clock].call) arglist)
119 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
122 settime(struct thread *td, struct timeval *tv)
124 struct timeval delta, tv1, tv2;
125 static struct timeval maxtime, laststep;
130 timevalsub(&delta, &tv1);
133 * If the system is secure, we do not allow the time to be
134 * set to a value earlier than 1 second less than the highest
135 * time we have yet seen. The worst a miscreant can do in
136 * this circumstance is "freeze" time. He couldn't go
139 * We similarly do not allow the clock to be stepped more
140 * than one second, nor more than once per second. This allows
141 * a miscreant to make the clock march double-time, but no worse.
143 if (securelevel_gt(td->td_ucred, 1) != 0) {
144 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
146 * Update maxtime to latest time we've seen.
148 if (tv1.tv_sec > maxtime.tv_sec)
151 timevalsub(&tv2, &maxtime);
152 if (tv2.tv_sec < -1) {
153 tv->tv_sec = maxtime.tv_sec - 1;
154 printf("Time adjustment clamped to -1 second\n");
157 if (tv1.tv_sec == laststep.tv_sec)
159 if (delta.tv_sec > 1) {
160 tv->tv_sec = tv1.tv_sec + 1;
161 printf("Time adjustment clamped to +1 second\n");
167 ts.tv_sec = tv->tv_sec;
168 ts.tv_nsec = tv->tv_usec * 1000;
174 #ifndef _SYS_SYSPROTO_H_
175 struct clock_getcpuclockid2_args {
183 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
188 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
190 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
195 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
204 case CPUCLOCK_WHICH_PID:
206 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
212 pid = td->td_proc->p_pid;
214 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
216 case CPUCLOCK_WHICH_TID:
217 tid = id == 0 ? td->td_tid : id;
218 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
225 #ifndef _SYS_SYSPROTO_H_
226 struct clock_gettime_args {
233 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
238 error = kern_clock_gettime(td, uap->clock_id, &ats);
240 error = copyout(&ats, uap->tp, sizeof(ats));
246 cputick2timespec(uint64_t runtime, struct timespec *ats)
250 ats->tv_sec = runtime / tr;
251 ats->tv_nsec = ((runtime % tr) * 1000000000ULL) / tr;
255 kern_thread_cputime(struct thread *targettd, struct timespec *ats)
257 uint64_t runtime, curtime, switchtime;
259 if (targettd == NULL) { /* current thread */
261 switchtime = PCPU_GET(switchtime);
262 curtime = cpu_ticks();
263 runtime = curthread->td_runtime;
265 runtime += curtime - switchtime;
267 PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
268 thread_lock(targettd);
269 runtime = targettd->td_runtime;
270 thread_unlock(targettd);
272 cputick2timespec(runtime, ats);
276 kern_process_cputime(struct proc *targetp, struct timespec *ats)
281 PROC_LOCK_ASSERT(targetp, MA_OWNED);
282 PROC_STATLOCK(targetp);
283 rufetch(targetp, &ru);
284 runtime = targetp->p_rux.rux_runtime;
285 if (curthread->td_proc == targetp)
286 runtime += cpu_ticks() - PCPU_GET(switchtime);
287 PROC_STATUNLOCK(targetp);
288 cputick2timespec(runtime, ats);
292 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
301 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
302 tid = clock_id & CPUCLOCK_ID_MASK;
303 td2 = tdfind(tid, p->p_pid);
306 kern_thread_cputime(td2, ats);
307 PROC_UNLOCK(td2->td_proc);
309 pid = clock_id & CPUCLOCK_ID_MASK;
310 error = pget(pid, PGET_CANSEE, &p2);
313 kern_process_cputime(p2, ats);
320 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
322 struct timeval sys, user;
327 case CLOCK_REALTIME: /* Default to precise. */
328 case CLOCK_REALTIME_PRECISE:
331 case CLOCK_REALTIME_FAST:
337 calcru(p, &user, &sys);
340 TIMEVAL_TO_TIMESPEC(&user, ats);
345 calcru(p, &user, &sys);
348 timevaladd(&user, &sys);
349 TIMEVAL_TO_TIMESPEC(&user, ats);
351 case CLOCK_MONOTONIC: /* Default to precise. */
352 case CLOCK_MONOTONIC_PRECISE:
354 case CLOCK_UPTIME_PRECISE:
357 case CLOCK_UPTIME_FAST:
358 case CLOCK_MONOTONIC_FAST:
362 ats->tv_sec = time_second;
365 case CLOCK_THREAD_CPUTIME_ID:
366 kern_thread_cputime(NULL, ats);
368 case CLOCK_PROCESS_CPUTIME_ID:
370 kern_process_cputime(p, ats);
374 if ((int)clock_id >= 0)
376 return (get_cputime(td, clock_id, ats));
381 #ifndef _SYS_SYSPROTO_H_
382 struct clock_settime_args {
384 const struct timespec *tp;
389 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
394 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
396 return (kern_clock_settime(td, uap->clock_id, &ats));
399 static int allow_insane_settime = 0;
400 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
401 &allow_insane_settime, 0,
402 "do not perform possibly restrictive checks on settime(2) args");
405 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
410 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
412 if (clock_id != CLOCK_REALTIME)
414 if (ats->tv_nsec < 0 || ats->tv_nsec >= NS_PER_SEC || ats->tv_sec < 0)
416 if (!allow_insane_settime &&
417 (ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60 ||
418 ats->tv_sec < utc_offset()))
420 /* XXX Don't convert nsec->usec and back */
421 TIMESPEC_TO_TIMEVAL(&atv, ats);
422 error = settime(td, &atv);
426 #ifndef _SYS_SYSPROTO_H_
427 struct clock_getres_args {
433 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
441 error = kern_clock_getres(td, uap->clock_id, &ts);
443 error = copyout(&ts, uap->tp, sizeof(ts));
448 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
454 case CLOCK_REALTIME_FAST:
455 case CLOCK_REALTIME_PRECISE:
456 case CLOCK_MONOTONIC:
457 case CLOCK_MONOTONIC_FAST:
458 case CLOCK_MONOTONIC_PRECISE:
460 case CLOCK_UPTIME_FAST:
461 case CLOCK_UPTIME_PRECISE:
463 * Round up the result of the division cheaply by adding 1.
464 * Rounding up is especially important if rounding down
465 * would give 0. Perfect rounding is unimportant.
467 ts->tv_nsec = NS_PER_SEC / tc_getfrequency() + 1;
471 /* Accurately round up here because we can do so cheaply. */
472 ts->tv_nsec = howmany(NS_PER_SEC, hz);
478 case CLOCK_THREAD_CPUTIME_ID:
479 case CLOCK_PROCESS_CPUTIME_ID:
481 ts->tv_nsec = 1000000000 / cpu_tickrate() + 1;
484 if ((int)clock_id < 0)
492 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
495 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
499 static uint8_t nanowait[MAXCPU];
502 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
503 const struct timespec *rqt, struct timespec *rmt)
505 struct timespec ts, now;
506 sbintime_t sbt, sbtt, prec, tmp;
511 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= NS_PER_SEC)
513 if ((flags & ~TIMER_ABSTIME) != 0)
517 case CLOCK_REALTIME_PRECISE:
518 case CLOCK_REALTIME_FAST:
520 is_abs_real = (flags & TIMER_ABSTIME) != 0;
522 case CLOCK_MONOTONIC:
523 case CLOCK_MONOTONIC_PRECISE:
524 case CLOCK_MONOTONIC_FAST:
526 case CLOCK_UPTIME_PRECISE:
527 case CLOCK_UPTIME_FAST:
532 case CLOCK_PROCESS_CPUTIME_ID:
534 case CLOCK_THREAD_CPUTIME_ID:
540 if ((flags & TIMER_ABSTIME) != 0) {
543 atomic_load_acq_int(&rtc_generation);
544 error = kern_clock_gettime(td, clock_id, &now);
545 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
546 timespecsub(&ts, &now, &ts);
548 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
552 if (ts.tv_sec > INT32_MAX / 2) {
553 over = ts.tv_sec - INT32_MAX / 2;
560 if (TIMESEL(&sbt, tmp))
563 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
564 sbt, prec, C_ABSOLUTE);
565 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
567 if (error != EWOULDBLOCK) {
568 if (TIMESEL(&sbtt, tmp))
572 if (error == ERESTART)
574 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
575 ts = sbttots(sbt - sbtt);
586 #ifndef _SYS_SYSPROTO_H_
587 struct nanosleep_args {
588 struct timespec *rqtp;
589 struct timespec *rmtp;
594 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
597 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
598 uap->rqtp, uap->rmtp));
601 #ifndef _SYS_SYSPROTO_H_
602 struct clock_nanosleep_args {
605 struct timespec *rqtp;
606 struct timespec *rmtp;
611 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
615 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
617 return (kern_posix_error(td, error));
621 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
622 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
624 struct timespec rmt, rqt;
627 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
630 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
631 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
632 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
639 #ifndef _SYS_SYSPROTO_H_
640 struct gettimeofday_args {
642 struct timezone *tzp;
647 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
655 error = copyout(&atv, uap->tp, sizeof (atv));
657 if (error == 0 && uap->tzp != NULL) {
658 rtz.tz_minuteswest = 0;
660 error = copyout(&rtz, uap->tzp, sizeof (rtz));
665 #ifndef _SYS_SYSPROTO_H_
666 struct settimeofday_args {
668 struct timezone *tzp;
673 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
675 struct timeval atv, *tvp;
676 struct timezone atz, *tzp;
680 error = copyin(uap->tv, &atv, sizeof(atv));
687 error = copyin(uap->tzp, &atz, sizeof(atz));
693 return (kern_settimeofday(td, tvp, tzp));
697 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
701 error = priv_check(td, PRIV_SETTIMEOFDAY);
704 /* Verify all parameters before changing time. */
706 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
709 error = settime(td, tv);
715 * Get value of an interval timer. The process virtual and profiling virtual
716 * time timers are kept in the p_stats area, since they can be swapped out.
717 * These are kept internally in the way they are specified externally: in
718 * time until they expire.
720 * The real time interval timer is kept in the process table slot for the
721 * process, and its value (it_value) is kept as an absolute time rather than
722 * as a delta, so that it is easy to keep periodic real-time signals from
725 * Virtual time timers are processed in the hardclock() routine of
726 * kern_clock.c. The real time timer is processed by a timeout routine,
727 * called from the softclock() routine. Since a callout may be delayed in
728 * real time due to interrupt processing in the system, it is possible for
729 * the real time timeout routine (realitexpire, given below), to be delayed
730 * in real time past when it is supposed to occur. It does not suffice,
731 * therefore, to reload the real timer .it_value from the real time timers
732 * .it_interval. Rather, we compute the next time in absolute time the timer
735 #ifndef _SYS_SYSPROTO_H_
736 struct getitimer_args {
738 struct itimerval *itv;
742 sys_getitimer(struct thread *td, struct getitimer_args *uap)
744 struct itimerval aitv;
747 error = kern_getitimer(td, uap->which, &aitv);
750 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
754 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
756 struct proc *p = td->td_proc;
759 if (which > ITIMER_PROF)
762 if (which == ITIMER_REAL) {
764 * Convert from absolute to relative time in .it_value
765 * part of real time timer. If time for real time timer
766 * has passed return 0, else return difference between
767 * current time and time for the timer to go off.
770 *aitv = p->p_realtimer;
772 if (timevalisset(&aitv->it_value)) {
774 if (timevalcmp(&aitv->it_value, &ctv, <))
775 timevalclear(&aitv->it_value);
777 timevalsub(&aitv->it_value, &ctv);
781 *aitv = p->p_stats->p_timer[which];
785 if (KTRPOINT(td, KTR_STRUCT))
791 #ifndef _SYS_SYSPROTO_H_
792 struct setitimer_args {
794 struct itimerval *itv, *oitv;
798 sys_setitimer(struct thread *td, struct setitimer_args *uap)
800 struct itimerval aitv, oitv;
803 if (uap->itv == NULL) {
804 uap->itv = uap->oitv;
805 return (sys_getitimer(td, (struct getitimer_args *)uap));
808 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
810 error = kern_setitimer(td, uap->which, &aitv, &oitv);
811 if (error != 0 || uap->oitv == NULL)
813 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
817 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
818 struct itimerval *oitv)
820 struct proc *p = td->td_proc;
825 return (kern_getitimer(td, which, oitv));
827 if (which > ITIMER_PROF)
830 if (KTRPOINT(td, KTR_STRUCT))
833 if (itimerfix(&aitv->it_value) ||
834 aitv->it_value.tv_sec > INT32_MAX / 2)
836 if (!timevalisset(&aitv->it_value))
837 timevalclear(&aitv->it_interval);
838 else if (itimerfix(&aitv->it_interval) ||
839 aitv->it_interval.tv_sec > INT32_MAX / 2)
842 if (which == ITIMER_REAL) {
844 if (timevalisset(&p->p_realtimer.it_value))
845 callout_stop(&p->p_itcallout);
847 if (timevalisset(&aitv->it_value)) {
848 pr = tvtosbt(aitv->it_value) >> tc_precexp;
849 timevaladd(&aitv->it_value, &ctv);
850 sbt = tvtosbt(aitv->it_value);
851 callout_reset_sbt(&p->p_itcallout, sbt, pr,
852 realitexpire, p, C_ABSOLUTE);
854 *oitv = p->p_realtimer;
855 p->p_realtimer = *aitv;
857 if (timevalisset(&oitv->it_value)) {
858 if (timevalcmp(&oitv->it_value, &ctv, <))
859 timevalclear(&oitv->it_value);
861 timevalsub(&oitv->it_value, &ctv);
864 if (aitv->it_interval.tv_sec == 0 &&
865 aitv->it_interval.tv_usec != 0 &&
866 aitv->it_interval.tv_usec < tick)
867 aitv->it_interval.tv_usec = tick;
868 if (aitv->it_value.tv_sec == 0 &&
869 aitv->it_value.tv_usec != 0 &&
870 aitv->it_value.tv_usec < tick)
871 aitv->it_value.tv_usec = tick;
873 *oitv = p->p_stats->p_timer[which];
874 p->p_stats->p_timer[which] = *aitv;
878 if (KTRPOINT(td, KTR_STRUCT))
885 realitexpire_reset_callout(struct proc *p, sbintime_t *isbtp)
889 prec = isbtp == NULL ? tvtosbt(p->p_realtimer.it_interval) : *isbtp;
890 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
891 prec >> tc_precexp, realitexpire, p, C_ABSOLUTE);
895 itimer_proc_continue(struct proc *p)
901 PROC_LOCK_ASSERT(p, MA_OWNED);
903 if ((p->p_flag2 & P2_ITSTOPPED) != 0) {
904 p->p_flag2 &= ~P2_ITSTOPPED;
906 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >=))
909 realitexpire_reset_callout(p, NULL);
912 if (p->p_itimers != NULL) {
913 for (id = 3; id < TIMER_MAX; id++) {
914 it = p->p_itimers->its_timers[id];
917 if ((it->it_flags & ITF_PSTOPPED) != 0) {
919 if ((it->it_flags & ITF_PSTOPPED) != 0) {
920 it->it_flags &= ~ITF_PSTOPPED;
921 if ((it->it_flags & ITF_DELETING) == 0)
922 realtimer_expire_l(it, true);
931 * Real interval timer expired:
932 * send process whose timer expired an alarm signal.
933 * If time is not set up to reload, then just return.
934 * Else compute next time timer should go off which is > current time.
935 * This is where delay in processing this timeout causes multiple
936 * SIGALRM calls to be compressed into one.
937 * tvtohz() always adds 1 to allow for the time until the next clock
938 * interrupt being strictly less than 1 clock tick, but we don't want
939 * that here since we want to appear to be in sync with the clock
940 * interrupt even when we're delayed.
943 realitexpire(void *arg)
949 p = (struct proc *)arg;
950 kern_psignal(p, SIGALRM);
951 if (!timevalisset(&p->p_realtimer.it_interval)) {
952 timevalclear(&p->p_realtimer.it_value);
956 isbt = tvtosbt(p->p_realtimer.it_interval);
957 if (isbt >= sbt_timethreshold)
958 getmicrouptime(&ctv);
962 timevaladd(&p->p_realtimer.it_value,
963 &p->p_realtimer.it_interval);
964 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
966 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
967 p->p_flag2 |= P2_ITSTOPPED;
971 p->p_flag2 &= ~P2_ITSTOPPED;
972 realitexpire_reset_callout(p, &isbt);
976 * Check that a proposed value to load into the .it_value or
977 * .it_interval part of an interval timer is acceptable, and
978 * fix it to have at least minimal value (i.e. if it is less
979 * than the resolution of the clock, round it up.)
982 itimerfix(struct timeval *tv)
985 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
987 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
988 tv->tv_usec < (u_int)tick / 16)
989 tv->tv_usec = (u_int)tick / 16;
994 * Decrement an interval timer by a specified number
995 * of microseconds, which must be less than a second,
996 * i.e. < 1000000. If the timer expires, then reload
997 * it. In this case, carry over (usec - old value) to
998 * reduce the value reloaded into the timer so that
999 * the timer does not drift. This routine assumes
1000 * that it is called in a context where the timers
1001 * on which it is operating cannot change in value.
1004 itimerdecr(struct itimerval *itp, int usec)
1007 if (itp->it_value.tv_usec < usec) {
1008 if (itp->it_value.tv_sec == 0) {
1009 /* expired, and already in next interval */
1010 usec -= itp->it_value.tv_usec;
1013 itp->it_value.tv_usec += 1000000;
1014 itp->it_value.tv_sec--;
1016 itp->it_value.tv_usec -= usec;
1018 if (timevalisset(&itp->it_value))
1020 /* expired, exactly at end of interval */
1022 if (timevalisset(&itp->it_interval)) {
1023 itp->it_value = itp->it_interval;
1024 itp->it_value.tv_usec -= usec;
1025 if (itp->it_value.tv_usec < 0) {
1026 itp->it_value.tv_usec += 1000000;
1027 itp->it_value.tv_sec--;
1030 itp->it_value.tv_usec = 0; /* sec is already 0 */
1035 * Add and subtract routines for timevals.
1036 * N.B.: subtract routine doesn't deal with
1037 * results which are before the beginning,
1038 * it just gets very confused in this case.
1042 timevaladd(struct timeval *t1, const struct timeval *t2)
1045 t1->tv_sec += t2->tv_sec;
1046 t1->tv_usec += t2->tv_usec;
1051 timevalsub(struct timeval *t1, const struct timeval *t2)
1054 t1->tv_sec -= t2->tv_sec;
1055 t1->tv_usec -= t2->tv_usec;
1060 timevalfix(struct timeval *t1)
1063 if (t1->tv_usec < 0) {
1065 t1->tv_usec += 1000000;
1067 if (t1->tv_usec >= 1000000) {
1069 t1->tv_usec -= 1000000;
1074 * ratecheck(): simple time-based rate-limit checking.
1077 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1079 struct timeval tv, delta;
1082 getmicrouptime(&tv); /* NB: 10ms precision */
1084 timevalsub(&delta, lasttime);
1087 * check for 0,0 is so that the message will be seen at least once,
1088 * even if interval is huge.
1090 if (timevalcmp(&delta, mininterval, >=) ||
1091 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1100 * ppsratecheck(): packets (or events) per second limitation.
1102 * Return 0 if the limit is to be enforced (e.g. the caller
1103 * should drop a packet because of the rate limitation).
1105 * maxpps of 0 always causes zero to be returned. maxpps of -1
1106 * always causes 1 to be returned; this effectively defeats rate
1109 * Note that we maintain the struct timeval for compatibility
1110 * with other bsd systems. We reuse the storage and just monitor
1111 * clock ticks for minimal overhead.
1114 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1119 * Reset the last time and counter if this is the first call
1120 * or more than a second has passed since the last update of
1124 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1125 lasttime->tv_sec = now;
1127 return (maxpps != 0);
1129 (*curpps)++; /* NB: ignore potential overflow */
1130 return (maxpps < 0 || *curpps <= maxpps);
1137 static const struct kclock rt_clock = {
1138 .timer_create = realtimer_create,
1139 .timer_delete = realtimer_delete,
1140 .timer_settime = realtimer_settime,
1141 .timer_gettime = realtimer_gettime,
1144 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1145 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1146 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1147 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1148 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1149 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1150 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1154 register_posix_clock(int clockid, const struct kclock *clk)
1156 if ((unsigned)clockid >= MAX_CLOCKS) {
1157 printf("%s: invalid clockid\n", __func__);
1160 posix_clocks[clockid] = *clk;
1165 itimer_init(void *mem, int size, int flags)
1169 it = (struct itimer *)mem;
1170 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1175 itimer_fini(void *mem, int size)
1179 it = (struct itimer *)mem;
1180 mtx_destroy(&it->it_mtx);
1184 itimer_enter(struct itimer *it)
1187 mtx_assert(&it->it_mtx, MA_OWNED);
1192 itimer_leave(struct itimer *it)
1195 mtx_assert(&it->it_mtx, MA_OWNED);
1196 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1198 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1202 #ifndef _SYS_SYSPROTO_H_
1203 struct ktimer_create_args {
1205 struct sigevent * evp;
1210 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1212 struct sigevent *evp, ev;
1216 if (uap->evp == NULL) {
1219 error = copyin(uap->evp, &ev, sizeof(ev));
1224 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1226 error = copyout(&id, uap->timerid, sizeof(int));
1228 kern_ktimer_delete(td, id);
1234 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1235 int *timerid, int preset_id)
1237 struct proc *p = td->td_proc;
1242 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1245 if (posix_clocks[clock_id].timer_create == NULL)
1249 if (evp->sigev_notify != SIGEV_NONE &&
1250 evp->sigev_notify != SIGEV_SIGNAL &&
1251 evp->sigev_notify != SIGEV_THREAD_ID)
1253 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1254 evp->sigev_notify == SIGEV_THREAD_ID) &&
1255 !_SIG_VALID(evp->sigev_signo))
1259 if (p->p_itimers == NULL)
1262 it = uma_zalloc(itimer_zone, M_WAITOK);
1264 it->it_usecount = 0;
1265 timespecclear(&it->it_time.it_value);
1266 timespecclear(&it->it_time.it_interval);
1268 it->it_overrun_last = 0;
1269 it->it_clockid = clock_id;
1271 ksiginfo_init(&it->it_ksi);
1272 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1273 error = CLOCK_CALL(clock_id, timer_create, (it));
1278 if (preset_id != -1) {
1279 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1281 if (p->p_itimers->its_timers[id] != NULL) {
1288 * Find a free timer slot, skipping those reserved
1291 for (id = 3; id < TIMER_MAX; id++)
1292 if (p->p_itimers->its_timers[id] == NULL)
1294 if (id == TIMER_MAX) {
1300 p->p_itimers->its_timers[id] = it;
1302 it->it_sigev = *evp;
1304 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1307 case CLOCK_REALTIME:
1308 it->it_sigev.sigev_signo = SIGALRM;
1311 it->it_sigev.sigev_signo = SIGVTALRM;
1314 it->it_sigev.sigev_signo = SIGPROF;
1317 it->it_sigev.sigev_value.sival_int = id;
1320 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1321 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1322 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1323 it->it_ksi.ksi_code = SI_TIMER;
1324 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1325 it->it_ksi.ksi_timerid = id;
1333 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1335 uma_zfree(itimer_zone, it);
1339 #ifndef _SYS_SYSPROTO_H_
1340 struct ktimer_delete_args {
1345 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1348 return (kern_ktimer_delete(td, uap->timerid));
1351 static struct itimer *
1352 itimer_find(struct proc *p, int timerid)
1356 PROC_LOCK_ASSERT(p, MA_OWNED);
1357 if ((p->p_itimers == NULL) ||
1358 (timerid < 0) || (timerid >= TIMER_MAX) ||
1359 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1363 if ((it->it_flags & ITF_DELETING) != 0) {
1371 kern_ktimer_delete(struct thread *td, int timerid)
1373 struct proc *p = td->td_proc;
1377 it = itimer_find(p, timerid);
1384 it->it_flags |= ITF_DELETING;
1385 while (it->it_usecount > 0) {
1386 it->it_flags |= ITF_WANTED;
1387 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1389 it->it_flags &= ~ITF_WANTED;
1390 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1394 if (KSI_ONQ(&it->it_ksi))
1395 sigqueue_take(&it->it_ksi);
1396 p->p_itimers->its_timers[timerid] = NULL;
1398 uma_zfree(itimer_zone, it);
1402 #ifndef _SYS_SYSPROTO_H_
1403 struct ktimer_settime_args {
1406 const struct itimerspec * value;
1407 struct itimerspec * ovalue;
1411 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1413 struct itimerspec val, oval, *ovalp;
1416 error = copyin(uap->value, &val, sizeof(val));
1419 ovalp = uap->ovalue != NULL ? &oval : NULL;
1420 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1421 if (error == 0 && uap->ovalue != NULL)
1422 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1427 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1428 struct itimerspec *val, struct itimerspec *oval)
1436 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1442 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1450 #ifndef _SYS_SYSPROTO_H_
1451 struct ktimer_gettime_args {
1453 struct itimerspec * value;
1457 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1459 struct itimerspec val;
1462 error = kern_ktimer_gettime(td, uap->timerid, &val);
1464 error = copyout(&val, uap->value, sizeof(val));
1469 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1477 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1483 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1490 #ifndef _SYS_SYSPROTO_H_
1491 struct timer_getoverrun_args {
1496 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1499 return (kern_ktimer_getoverrun(td, uap->timerid));
1503 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1505 struct proc *p = td->td_proc;
1511 (it = itimer_find(p, timer_id)) == NULL) {
1515 td->td_retval[0] = it->it_overrun_last;
1524 realtimer_create(struct itimer *it)
1526 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1531 realtimer_delete(struct itimer *it)
1533 mtx_assert(&it->it_mtx, MA_OWNED);
1536 * clear timer's value and interval to tell realtimer_expire
1537 * to not rearm the timer.
1539 timespecclear(&it->it_time.it_value);
1540 timespecclear(&it->it_time.it_interval);
1542 callout_drain(&it->it_callout);
1548 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1550 struct timespec cts;
1552 mtx_assert(&it->it_mtx, MA_OWNED);
1554 realtimer_clocktime(it->it_clockid, &cts);
1555 *ovalue = it->it_time;
1556 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1557 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1558 if (ovalue->it_value.tv_sec < 0 ||
1559 (ovalue->it_value.tv_sec == 0 &&
1560 ovalue->it_value.tv_nsec == 0)) {
1561 ovalue->it_value.tv_sec = 0;
1562 ovalue->it_value.tv_nsec = 1;
1569 realtimer_settime(struct itimer *it, int flags, struct itimerspec *value,
1570 struct itimerspec *ovalue)
1572 struct timespec cts, ts;
1574 struct itimerspec val;
1576 mtx_assert(&it->it_mtx, MA_OWNED);
1579 if (itimespecfix(&val.it_value))
1582 if (timespecisset(&val.it_value)) {
1583 if (itimespecfix(&val.it_interval))
1586 timespecclear(&val.it_interval);
1590 realtimer_gettime(it, ovalue);
1593 if (timespecisset(&val.it_value)) {
1594 realtimer_clocktime(it->it_clockid, &cts);
1596 if ((flags & TIMER_ABSTIME) == 0) {
1597 /* Convert to absolute time. */
1598 timespecadd(&it->it_time.it_value, &cts,
1599 &it->it_time.it_value);
1601 timespecsub(&ts, &cts, &ts);
1603 * We don't care if ts is negative, tztohz will
1607 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1608 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1611 callout_stop(&it->it_callout);
1618 realtimer_clocktime(clockid_t id, struct timespec *ts)
1620 if (id == CLOCK_REALTIME)
1622 else /* CLOCK_MONOTONIC */
1627 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1631 PROC_LOCK_ASSERT(p, MA_OWNED);
1632 it = itimer_find(p, timerid);
1634 ksi->ksi_overrun = it->it_overrun;
1635 it->it_overrun_last = it->it_overrun;
1644 itimespecfix(struct timespec *ts)
1647 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= NS_PER_SEC)
1649 if ((UINT64_MAX - ts->tv_nsec) / NS_PER_SEC < ts->tv_sec)
1651 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1652 ts->tv_nsec = tick * 1000;
1656 #define timespectons(tsp) \
1657 ((uint64_t)(tsp)->tv_sec * NS_PER_SEC + (tsp)->tv_nsec)
1658 #define timespecfromns(ns) (struct timespec){ \
1659 .tv_sec = (ns) / NS_PER_SEC, \
1660 .tv_nsec = (ns) % NS_PER_SEC \
1664 realtimer_expire_l(struct itimer *it, bool proc_locked)
1666 struct timespec cts, ts;
1669 uint64_t interval, now, overruns, value;
1671 realtimer_clocktime(it->it_clockid, &cts);
1672 /* Only fire if time is reached. */
1673 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1674 if (timespecisset(&it->it_time.it_interval)) {
1675 timespecadd(&it->it_time.it_value,
1676 &it->it_time.it_interval,
1677 &it->it_time.it_value);
1679 interval = timespectons(&it->it_time.it_interval);
1680 value = timespectons(&it->it_time.it_value);
1681 now = timespectons(&cts);
1685 * We missed at least one period.
1687 overruns = howmany(now - value + 1, interval);
1688 if (it->it_overrun + overruns >=
1690 it->it_overrun + overruns <= INT_MAX) {
1691 it->it_overrun += (int)overruns;
1693 it->it_overrun = INT_MAX;
1694 it->it_ksi.ksi_errno = ERANGE;
1697 now + interval - (now - value) % interval;
1698 it->it_time.it_value = timespecfromns(value);
1701 /* single shot timer ? */
1702 timespecclear(&it->it_time.it_value);
1706 if (timespecisset(&it->it_time.it_value)) {
1707 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1708 it->it_flags |= ITF_PSTOPPED;
1710 timespecsub(&it->it_time.it_value, &cts, &ts);
1711 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1712 callout_reset(&it->it_callout, tvtohz(&tv),
1713 realtimer_expire, it);
1726 } else if (timespecisset(&it->it_time.it_value)) {
1728 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1729 it->it_flags |= ITF_PSTOPPED;
1731 ts = it->it_time.it_value;
1732 timespecsub(&ts, &cts, &ts);
1733 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1734 callout_reset(&it->it_callout, tvtohz(&tv),
1735 realtimer_expire, it);
1740 /* Timeout callback for realtime timer */
1742 realtimer_expire(void *arg)
1744 realtimer_expire_l(arg, false);
1748 itimer_fire(struct itimer *it)
1750 struct proc *p = it->it_proc;
1753 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1754 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1755 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1757 timespecclear(&it->it_time.it_value);
1758 timespecclear(&it->it_time.it_interval);
1759 callout_stop(&it->it_callout);
1763 if (!KSI_ONQ(&it->it_ksi)) {
1764 it->it_ksi.ksi_errno = 0;
1765 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1766 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1768 if (it->it_overrun < INT_MAX)
1771 it->it_ksi.ksi_errno = ERANGE;
1778 itimers_alloc(struct proc *p)
1780 struct itimers *its;
1782 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1784 if (p->p_itimers == NULL) {
1790 free(its, M_SUBPROC);
1794 /* Clean up timers when some process events are being triggered. */
1796 itimers_event_exit_exec(int start_idx, struct proc *p)
1798 struct itimers *its;
1806 for (i = start_idx; i < TIMER_MAX; ++i) {
1807 if ((it = its->its_timers[i]) != NULL)
1808 kern_ktimer_delete(curthread, i);
1810 if (its->its_timers[0] == NULL && its->its_timers[1] == NULL &&
1811 its->its_timers[2] == NULL) {
1812 /* Synchronize with itimer_proc_continue(). */
1814 p->p_itimers = NULL;
1816 free(its, M_SUBPROC);
1821 itimers_exec(struct proc *p)
1824 * According to susv3, XSI interval timers should be inherited
1827 itimers_event_exit_exec(3, p);
1831 itimers_exit(struct proc *p)
1833 itimers_event_exit_exec(0, p);