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
32 #include <sys/cdefs.h>
33 #include "opt_ktrace.h"
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/limits.h>
38 #include <sys/clock.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>
45 #include <sys/sleepqueue.h>
46 #include <sys/syscallsubr.h>
47 #include <sys/sysctl.h>
50 #include <sys/posix4.h>
52 #include <sys/timers.h>
53 #include <sys/timetc.h>
54 #include <sys/vnode.h>
56 #include <sys/ktrace.h>
60 #include <vm/vm_extern.h>
63 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
64 #define CPUCLOCK_BIT 0x80000000
65 #define CPUCLOCK_PROCESS_BIT 0x40000000
66 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
67 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
68 #define MAKE_PROCESS_CPUCLOCK(pid) \
69 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
71 #define NS_PER_SEC 1000000000
73 static struct kclock posix_clocks[MAX_CLOCKS];
74 static uma_zone_t itimer_zone = NULL;
77 * Time of day and interval timer support.
79 * These routines provide the kernel entry points to get and set
80 * the time-of-day and per-process interval timers. Subroutines
81 * here provide support for adding and subtracting timeval structures
82 * and decrementing interval timers, optionally reloading the interval
83 * timers when they expire.
86 static int settime(struct thread *, struct timeval *);
87 static void timevalfix(struct timeval *);
88 static int user_clock_nanosleep(struct thread *td, clockid_t clock_id,
89 int flags, const struct timespec *ua_rqtp,
90 struct timespec *ua_rmtp);
92 static void itimer_start(void);
93 static int itimer_init(void *, int, int);
94 static void itimer_fini(void *, int);
95 static void itimer_enter(struct itimer *);
96 static void itimer_leave(struct itimer *);
97 static struct itimer *itimer_find(struct proc *, int);
98 static void itimers_alloc(struct proc *);
99 static int realtimer_create(struct itimer *);
100 static int realtimer_gettime(struct itimer *, struct itimerspec *);
101 static int realtimer_settime(struct itimer *, int,
102 struct itimerspec *, struct itimerspec *);
103 static int realtimer_delete(struct itimer *);
104 static void realtimer_clocktime(clockid_t, struct timespec *);
105 static void realtimer_expire(void *);
106 static void realtimer_expire_l(struct itimer *it, bool proc_locked);
108 static void realitexpire(void *arg);
110 static int register_posix_clock(int, const struct kclock *);
111 static void itimer_fire(struct itimer *it);
112 static int itimespecfix(struct timespec *ts);
114 #define CLOCK_CALL(clock, call, arglist) \
115 ((*posix_clocks[clock].call) arglist)
117 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
120 settime(struct thread *td, struct timeval *tv)
122 struct timeval delta, tv1, tv2;
123 static struct timeval maxtime, laststep;
128 timevalsub(&delta, &tv1);
131 * If the system is secure, we do not allow the time to be
132 * set to a value earlier than 1 second less than the highest
133 * time we have yet seen. The worst a miscreant can do in
134 * this circumstance is "freeze" time. He couldn't go
137 * We similarly do not allow the clock to be stepped more
138 * than one second, nor more than once per second. This allows
139 * a miscreant to make the clock march double-time, but no worse.
141 if (securelevel_gt(td->td_ucred, 1) != 0) {
142 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
144 * Update maxtime to latest time we've seen.
146 if (tv1.tv_sec > maxtime.tv_sec)
149 timevalsub(&tv2, &maxtime);
150 if (tv2.tv_sec < -1) {
151 tv->tv_sec = maxtime.tv_sec - 1;
152 printf("Time adjustment clamped to -1 second\n");
155 if (tv1.tv_sec == laststep.tv_sec)
157 if (delta.tv_sec > 1) {
158 tv->tv_sec = tv1.tv_sec + 1;
159 printf("Time adjustment clamped to +1 second\n");
165 ts.tv_sec = tv->tv_sec;
166 ts.tv_nsec = tv->tv_usec * 1000;
172 #ifndef _SYS_SYSPROTO_H_
173 struct clock_getcpuclockid2_args {
181 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
186 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
188 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
193 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
202 case CPUCLOCK_WHICH_PID:
204 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
210 pid = td->td_proc->p_pid;
212 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
214 case CPUCLOCK_WHICH_TID:
215 tid = id == 0 ? td->td_tid : id;
216 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
223 #ifndef _SYS_SYSPROTO_H_
224 struct clock_gettime_args {
231 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
236 error = kern_clock_gettime(td, uap->clock_id, &ats);
238 error = copyout(&ats, uap->tp, sizeof(ats));
244 cputick2timespec(uint64_t runtime, struct timespec *ats)
248 ats->tv_sec = runtime / tr;
249 ats->tv_nsec = ((runtime % tr) * 1000000000ULL) / tr;
253 kern_thread_cputime(struct thread *targettd, struct timespec *ats)
255 uint64_t runtime, curtime, switchtime;
257 if (targettd == NULL) { /* current thread */
259 switchtime = PCPU_GET(switchtime);
260 curtime = cpu_ticks();
261 runtime = curthread->td_runtime;
263 runtime += curtime - switchtime;
265 PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
266 thread_lock(targettd);
267 runtime = targettd->td_runtime;
268 thread_unlock(targettd);
270 cputick2timespec(runtime, ats);
274 kern_process_cputime(struct proc *targetp, struct timespec *ats)
279 PROC_LOCK_ASSERT(targetp, MA_OWNED);
280 PROC_STATLOCK(targetp);
281 rufetch(targetp, &ru);
282 runtime = targetp->p_rux.rux_runtime;
283 if (curthread->td_proc == targetp)
284 runtime += cpu_ticks() - PCPU_GET(switchtime);
285 PROC_STATUNLOCK(targetp);
286 cputick2timespec(runtime, ats);
290 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
299 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
300 tid = clock_id & CPUCLOCK_ID_MASK;
301 td2 = tdfind(tid, p->p_pid);
304 kern_thread_cputime(td2, ats);
305 PROC_UNLOCK(td2->td_proc);
307 pid = clock_id & CPUCLOCK_ID_MASK;
308 error = pget(pid, PGET_CANSEE, &p2);
311 kern_process_cputime(p2, ats);
318 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
320 struct timeval sys, user;
325 case CLOCK_REALTIME: /* Default to precise. */
326 case CLOCK_REALTIME_PRECISE:
329 case CLOCK_REALTIME_FAST:
335 calcru(p, &user, &sys);
338 TIMEVAL_TO_TIMESPEC(&user, ats);
343 calcru(p, &user, &sys);
346 timevaladd(&user, &sys);
347 TIMEVAL_TO_TIMESPEC(&user, ats);
349 case CLOCK_MONOTONIC: /* Default to precise. */
350 case CLOCK_MONOTONIC_PRECISE:
352 case CLOCK_UPTIME_PRECISE:
355 case CLOCK_UPTIME_FAST:
356 case CLOCK_MONOTONIC_FAST:
360 ats->tv_sec = time_second;
363 case CLOCK_THREAD_CPUTIME_ID:
364 kern_thread_cputime(NULL, ats);
366 case CLOCK_PROCESS_CPUTIME_ID:
368 kern_process_cputime(p, ats);
372 if ((int)clock_id >= 0)
374 return (get_cputime(td, clock_id, ats));
379 #ifndef _SYS_SYSPROTO_H_
380 struct clock_settime_args {
382 const struct timespec *tp;
387 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
392 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
394 return (kern_clock_settime(td, uap->clock_id, &ats));
397 static int allow_insane_settime = 0;
398 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
399 &allow_insane_settime, 0,
400 "do not perform possibly restrictive checks on settime(2) args");
403 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
408 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
410 if (clock_id != CLOCK_REALTIME)
412 if (!timespecvalid_interval(ats))
414 if (!allow_insane_settime &&
415 (ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60 ||
416 ats->tv_sec < utc_offset()))
418 /* XXX Don't convert nsec->usec and back */
419 TIMESPEC_TO_TIMEVAL(&atv, ats);
420 error = settime(td, &atv);
424 #ifndef _SYS_SYSPROTO_H_
425 struct clock_getres_args {
431 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
439 error = kern_clock_getres(td, uap->clock_id, &ts);
441 error = copyout(&ts, uap->tp, sizeof(ts));
446 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
452 case CLOCK_REALTIME_FAST:
453 case CLOCK_REALTIME_PRECISE:
454 case CLOCK_MONOTONIC:
455 case CLOCK_MONOTONIC_FAST:
456 case CLOCK_MONOTONIC_PRECISE:
458 case CLOCK_UPTIME_FAST:
459 case CLOCK_UPTIME_PRECISE:
461 * Round up the result of the division cheaply by adding 1.
462 * Rounding up is especially important if rounding down
463 * would give 0. Perfect rounding is unimportant.
465 ts->tv_nsec = NS_PER_SEC / tc_getfrequency() + 1;
469 /* Accurately round up here because we can do so cheaply. */
470 ts->tv_nsec = howmany(NS_PER_SEC, hz);
476 case CLOCK_THREAD_CPUTIME_ID:
477 case CLOCK_PROCESS_CPUTIME_ID:
479 ts->tv_nsec = 1000000000 / cpu_tickrate() + 1;
482 if ((int)clock_id < 0)
490 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
493 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
497 static uint8_t nanowait[MAXCPU];
500 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
501 const struct timespec *rqt, struct timespec *rmt)
503 struct timespec ts, now;
504 sbintime_t sbt, sbtt, prec, tmp;
509 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= NS_PER_SEC)
511 if ((flags & ~TIMER_ABSTIME) != 0)
515 case CLOCK_REALTIME_PRECISE:
516 case CLOCK_REALTIME_FAST:
518 is_abs_real = (flags & TIMER_ABSTIME) != 0;
520 case CLOCK_MONOTONIC:
521 case CLOCK_MONOTONIC_PRECISE:
522 case CLOCK_MONOTONIC_FAST:
524 case CLOCK_UPTIME_PRECISE:
525 case CLOCK_UPTIME_FAST:
530 case CLOCK_PROCESS_CPUTIME_ID:
532 case CLOCK_THREAD_CPUTIME_ID:
538 if ((flags & TIMER_ABSTIME) != 0) {
541 atomic_load_acq_int(&rtc_generation);
542 error = kern_clock_gettime(td, clock_id, &now);
543 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
544 timespecsub(&ts, &now, &ts);
546 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
550 if (ts.tv_sec > INT32_MAX / 2) {
551 over = ts.tv_sec - INT32_MAX / 2;
558 if (TIMESEL(&sbt, tmp))
561 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
562 sbt, prec, C_ABSOLUTE);
563 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
565 if (error != EWOULDBLOCK) {
566 if (TIMESEL(&sbtt, tmp))
570 if (error == ERESTART)
572 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
573 ts = sbttots(sbt - sbtt);
584 #ifndef _SYS_SYSPROTO_H_
585 struct nanosleep_args {
586 struct timespec *rqtp;
587 struct timespec *rmtp;
592 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
595 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
596 uap->rqtp, uap->rmtp));
599 #ifndef _SYS_SYSPROTO_H_
600 struct clock_nanosleep_args {
603 struct timespec *rqtp;
604 struct timespec *rmtp;
609 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
613 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
615 return (kern_posix_error(td, error));
619 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
620 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
622 struct timespec rmt, rqt;
625 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
628 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
629 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
630 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
637 #ifndef _SYS_SYSPROTO_H_
638 struct gettimeofday_args {
640 struct timezone *tzp;
645 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
653 error = copyout(&atv, uap->tp, sizeof (atv));
655 if (error == 0 && uap->tzp != NULL) {
656 rtz.tz_minuteswest = 0;
658 error = copyout(&rtz, uap->tzp, sizeof (rtz));
663 #ifndef _SYS_SYSPROTO_H_
664 struct settimeofday_args {
666 struct timezone *tzp;
671 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
673 struct timeval atv, *tvp;
674 struct timezone atz, *tzp;
678 error = copyin(uap->tv, &atv, sizeof(atv));
685 error = copyin(uap->tzp, &atz, sizeof(atz));
691 return (kern_settimeofday(td, tvp, tzp));
695 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
699 error = priv_check(td, PRIV_SETTIMEOFDAY);
702 /* Verify all parameters before changing time. */
704 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
707 error = settime(td, tv);
713 * Get value of an interval timer. The process virtual and profiling virtual
714 * time timers are kept in the p_stats area, since they can be swapped out.
715 * These are kept internally in the way they are specified externally: in
716 * time until they expire.
718 * The real time interval timer is kept in the process table slot for the
719 * process, and its value (it_value) is kept as an absolute time rather than
720 * as a delta, so that it is easy to keep periodic real-time signals from
723 * Virtual time timers are processed in the hardclock() routine of
724 * kern_clock.c. The real time timer is processed by a timeout routine,
725 * called from the softclock() routine. Since a callout may be delayed in
726 * real time due to interrupt processing in the system, it is possible for
727 * the real time timeout routine (realitexpire, given below), to be delayed
728 * in real time past when it is supposed to occur. It does not suffice,
729 * therefore, to reload the real timer .it_value from the real time timers
730 * .it_interval. Rather, we compute the next time in absolute time the timer
733 #ifndef _SYS_SYSPROTO_H_
734 struct getitimer_args {
736 struct itimerval *itv;
740 sys_getitimer(struct thread *td, struct getitimer_args *uap)
742 struct itimerval aitv;
745 error = kern_getitimer(td, uap->which, &aitv);
748 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
752 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
754 struct proc *p = td->td_proc;
757 if (which > ITIMER_PROF)
760 if (which == ITIMER_REAL) {
762 * Convert from absolute to relative time in .it_value
763 * part of real time timer. If time for real time timer
764 * has passed return 0, else return difference between
765 * current time and time for the timer to go off.
768 *aitv = p->p_realtimer;
770 if (timevalisset(&aitv->it_value)) {
772 if (timevalcmp(&aitv->it_value, &ctv, <))
773 timevalclear(&aitv->it_value);
775 timevalsub(&aitv->it_value, &ctv);
779 *aitv = p->p_stats->p_timer[which];
783 if (KTRPOINT(td, KTR_STRUCT))
789 #ifndef _SYS_SYSPROTO_H_
790 struct setitimer_args {
792 struct itimerval *itv, *oitv;
796 sys_setitimer(struct thread *td, struct setitimer_args *uap)
798 struct itimerval aitv, oitv;
801 if (uap->itv == NULL) {
802 uap->itv = uap->oitv;
803 return (sys_getitimer(td, (struct getitimer_args *)uap));
806 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
808 error = kern_setitimer(td, uap->which, &aitv, &oitv);
809 if (error != 0 || uap->oitv == NULL)
811 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
815 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
816 struct itimerval *oitv)
818 struct proc *p = td->td_proc;
823 return (kern_getitimer(td, which, oitv));
825 if (which > ITIMER_PROF)
828 if (KTRPOINT(td, KTR_STRUCT))
831 if (itimerfix(&aitv->it_value) ||
832 aitv->it_value.tv_sec > INT32_MAX / 2)
834 if (!timevalisset(&aitv->it_value))
835 timevalclear(&aitv->it_interval);
836 else if (itimerfix(&aitv->it_interval) ||
837 aitv->it_interval.tv_sec > INT32_MAX / 2)
840 if (which == ITIMER_REAL) {
842 if (timevalisset(&p->p_realtimer.it_value))
843 callout_stop(&p->p_itcallout);
845 if (timevalisset(&aitv->it_value)) {
846 pr = tvtosbt(aitv->it_value) >> tc_precexp;
847 timevaladd(&aitv->it_value, &ctv);
848 sbt = tvtosbt(aitv->it_value);
849 callout_reset_sbt(&p->p_itcallout, sbt, pr,
850 realitexpire, p, C_ABSOLUTE);
852 *oitv = p->p_realtimer;
853 p->p_realtimer = *aitv;
855 if (timevalisset(&oitv->it_value)) {
856 if (timevalcmp(&oitv->it_value, &ctv, <))
857 timevalclear(&oitv->it_value);
859 timevalsub(&oitv->it_value, &ctv);
862 if (aitv->it_interval.tv_sec == 0 &&
863 aitv->it_interval.tv_usec != 0 &&
864 aitv->it_interval.tv_usec < tick)
865 aitv->it_interval.tv_usec = tick;
866 if (aitv->it_value.tv_sec == 0 &&
867 aitv->it_value.tv_usec != 0 &&
868 aitv->it_value.tv_usec < tick)
869 aitv->it_value.tv_usec = tick;
871 *oitv = p->p_stats->p_timer[which];
872 p->p_stats->p_timer[which] = *aitv;
876 if (KTRPOINT(td, KTR_STRUCT))
883 realitexpire_reset_callout(struct proc *p, sbintime_t *isbtp)
887 prec = isbtp == NULL ? tvtosbt(p->p_realtimer.it_interval) : *isbtp;
888 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
889 prec >> tc_precexp, realitexpire, p, C_ABSOLUTE);
893 itimer_proc_continue(struct proc *p)
899 PROC_LOCK_ASSERT(p, MA_OWNED);
901 if ((p->p_flag2 & P2_ITSTOPPED) != 0) {
902 p->p_flag2 &= ~P2_ITSTOPPED;
904 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >=))
907 realitexpire_reset_callout(p, NULL);
910 if (p->p_itimers != NULL) {
911 for (id = 3; id < TIMER_MAX; id++) {
912 it = p->p_itimers->its_timers[id];
915 if ((it->it_flags & ITF_PSTOPPED) != 0) {
917 if ((it->it_flags & ITF_PSTOPPED) != 0) {
918 it->it_flags &= ~ITF_PSTOPPED;
919 if ((it->it_flags & ITF_DELETING) == 0)
920 realtimer_expire_l(it, true);
929 * Real interval timer expired:
930 * send process whose timer expired an alarm signal.
931 * If time is not set up to reload, then just return.
932 * Else compute next time timer should go off which is > current time.
933 * This is where delay in processing this timeout causes multiple
934 * SIGALRM calls to be compressed into one.
935 * tvtohz() always adds 1 to allow for the time until the next clock
936 * interrupt being strictly less than 1 clock tick, but we don't want
937 * that here since we want to appear to be in sync with the clock
938 * interrupt even when we're delayed.
941 realitexpire(void *arg)
947 p = (struct proc *)arg;
948 kern_psignal(p, SIGALRM);
949 if (!timevalisset(&p->p_realtimer.it_interval)) {
950 timevalclear(&p->p_realtimer.it_value);
954 isbt = tvtosbt(p->p_realtimer.it_interval);
955 if (isbt >= sbt_timethreshold)
956 getmicrouptime(&ctv);
960 timevaladd(&p->p_realtimer.it_value,
961 &p->p_realtimer.it_interval);
962 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
964 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
965 p->p_flag2 |= P2_ITSTOPPED;
969 p->p_flag2 &= ~P2_ITSTOPPED;
970 realitexpire_reset_callout(p, &isbt);
974 * Check that a proposed value to load into the .it_value or
975 * .it_interval part of an interval timer is acceptable, and
976 * fix it to have at least minimal value (i.e. if it is less
977 * than the resolution of the clock, round it up.)
980 itimerfix(struct timeval *tv)
983 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
985 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
986 tv->tv_usec < (u_int)tick / 16)
987 tv->tv_usec = (u_int)tick / 16;
992 * Decrement an interval timer by a specified number
993 * of microseconds, which must be less than a second,
994 * i.e. < 1000000. If the timer expires, then reload
995 * it. In this case, carry over (usec - old value) to
996 * reduce the value reloaded into the timer so that
997 * the timer does not drift. This routine assumes
998 * that it is called in a context where the timers
999 * on which it is operating cannot change in value.
1002 itimerdecr(struct itimerval *itp, int usec)
1005 if (itp->it_value.tv_usec < usec) {
1006 if (itp->it_value.tv_sec == 0) {
1007 /* expired, and already in next interval */
1008 usec -= itp->it_value.tv_usec;
1011 itp->it_value.tv_usec += 1000000;
1012 itp->it_value.tv_sec--;
1014 itp->it_value.tv_usec -= usec;
1016 if (timevalisset(&itp->it_value))
1018 /* expired, exactly at end of interval */
1020 if (timevalisset(&itp->it_interval)) {
1021 itp->it_value = itp->it_interval;
1022 itp->it_value.tv_usec -= usec;
1023 if (itp->it_value.tv_usec < 0) {
1024 itp->it_value.tv_usec += 1000000;
1025 itp->it_value.tv_sec--;
1028 itp->it_value.tv_usec = 0; /* sec is already 0 */
1033 * Add and subtract routines for timevals.
1034 * N.B.: subtract routine doesn't deal with
1035 * results which are before the beginning,
1036 * it just gets very confused in this case.
1040 timevaladd(struct timeval *t1, const struct timeval *t2)
1043 t1->tv_sec += t2->tv_sec;
1044 t1->tv_usec += t2->tv_usec;
1049 timevalsub(struct timeval *t1, const struct timeval *t2)
1052 t1->tv_sec -= t2->tv_sec;
1053 t1->tv_usec -= t2->tv_usec;
1058 timevalfix(struct timeval *t1)
1061 if (t1->tv_usec < 0) {
1063 t1->tv_usec += 1000000;
1065 if (t1->tv_usec >= 1000000) {
1067 t1->tv_usec -= 1000000;
1072 * ratecheck(): simple time-based rate-limit checking.
1075 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1077 struct timeval tv, delta;
1080 getmicrouptime(&tv); /* NB: 10ms precision */
1082 timevalsub(&delta, lasttime);
1085 * check for 0,0 is so that the message will be seen at least once,
1086 * even if interval is huge.
1088 if (timevalcmp(&delta, mininterval, >=) ||
1089 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1098 * eventratecheck(): events per second limitation.
1100 * Return 0 if the limit is to be enforced (e.g. the caller
1101 * should ignore the event because of the rate limitation).
1103 * maxeps of 0 always causes zero to be returned. maxeps of -1
1104 * always causes 1 to be returned; this effectively defeats rate
1107 * Note that we maintain the struct timeval for compatibility
1108 * with other bsd systems. We reuse the storage and just monitor
1109 * clock ticks for minimal overhead.
1112 eventratecheck(struct timeval *lasttime, int *cureps, int maxeps)
1117 * Reset the last time and counter if this is the first call
1118 * or more than a second has passed since the last update of
1122 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1123 lasttime->tv_sec = now;
1125 return (maxeps != 0);
1127 (*cureps)++; /* NB: ignore potential overflow */
1128 return (maxeps < 0 || *cureps <= maxeps);
1135 static const struct kclock rt_clock = {
1136 .timer_create = realtimer_create,
1137 .timer_delete = realtimer_delete,
1138 .timer_settime = realtimer_settime,
1139 .timer_gettime = realtimer_gettime,
1142 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1143 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1144 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1145 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1146 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1147 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1148 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1152 register_posix_clock(int clockid, const struct kclock *clk)
1154 if ((unsigned)clockid >= MAX_CLOCKS) {
1155 printf("%s: invalid clockid\n", __func__);
1158 posix_clocks[clockid] = *clk;
1163 itimer_init(void *mem, int size, int flags)
1167 it = (struct itimer *)mem;
1168 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1173 itimer_fini(void *mem, int size)
1177 it = (struct itimer *)mem;
1178 mtx_destroy(&it->it_mtx);
1182 itimer_enter(struct itimer *it)
1185 mtx_assert(&it->it_mtx, MA_OWNED);
1190 itimer_leave(struct itimer *it)
1193 mtx_assert(&it->it_mtx, MA_OWNED);
1194 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1196 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1200 #ifndef _SYS_SYSPROTO_H_
1201 struct ktimer_create_args {
1203 struct sigevent * evp;
1208 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1210 struct sigevent *evp, ev;
1214 if (uap->evp == NULL) {
1217 error = copyin(uap->evp, &ev, sizeof(ev));
1222 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1224 error = copyout(&id, uap->timerid, sizeof(int));
1226 kern_ktimer_delete(td, id);
1232 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1233 int *timerid, int preset_id)
1235 struct proc *p = td->td_proc;
1240 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1243 if (posix_clocks[clock_id].timer_create == NULL)
1247 if (evp->sigev_notify != SIGEV_NONE &&
1248 evp->sigev_notify != SIGEV_SIGNAL &&
1249 evp->sigev_notify != SIGEV_THREAD_ID)
1251 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1252 evp->sigev_notify == SIGEV_THREAD_ID) &&
1253 !_SIG_VALID(evp->sigev_signo))
1257 if (p->p_itimers == NULL)
1260 it = uma_zalloc(itimer_zone, M_WAITOK);
1262 it->it_usecount = 0;
1263 timespecclear(&it->it_time.it_value);
1264 timespecclear(&it->it_time.it_interval);
1266 it->it_overrun_last = 0;
1267 it->it_clockid = clock_id;
1269 ksiginfo_init(&it->it_ksi);
1270 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1271 error = CLOCK_CALL(clock_id, timer_create, (it));
1276 if (preset_id != -1) {
1277 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1279 if (p->p_itimers->its_timers[id] != NULL) {
1286 * Find a free timer slot, skipping those reserved
1289 for (id = 3; id < TIMER_MAX; id++)
1290 if (p->p_itimers->its_timers[id] == NULL)
1292 if (id == TIMER_MAX) {
1298 p->p_itimers->its_timers[id] = it;
1300 it->it_sigev = *evp;
1302 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1305 case CLOCK_REALTIME:
1306 it->it_sigev.sigev_signo = SIGALRM;
1309 it->it_sigev.sigev_signo = SIGVTALRM;
1312 it->it_sigev.sigev_signo = SIGPROF;
1315 it->it_sigev.sigev_value.sival_int = id;
1318 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1319 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1320 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1321 it->it_ksi.ksi_code = SI_TIMER;
1322 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1323 it->it_ksi.ksi_timerid = id;
1331 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1333 uma_zfree(itimer_zone, it);
1337 #ifndef _SYS_SYSPROTO_H_
1338 struct ktimer_delete_args {
1343 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1346 return (kern_ktimer_delete(td, uap->timerid));
1349 static struct itimer *
1350 itimer_find(struct proc *p, int timerid)
1354 PROC_LOCK_ASSERT(p, MA_OWNED);
1355 if ((p->p_itimers == NULL) ||
1356 (timerid < 0) || (timerid >= TIMER_MAX) ||
1357 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1361 if ((it->it_flags & ITF_DELETING) != 0) {
1369 kern_ktimer_delete(struct thread *td, int timerid)
1371 struct proc *p = td->td_proc;
1375 it = itimer_find(p, timerid);
1382 it->it_flags |= ITF_DELETING;
1383 while (it->it_usecount > 0) {
1384 it->it_flags |= ITF_WANTED;
1385 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1387 it->it_flags &= ~ITF_WANTED;
1388 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1392 if (KSI_ONQ(&it->it_ksi))
1393 sigqueue_take(&it->it_ksi);
1394 p->p_itimers->its_timers[timerid] = NULL;
1396 uma_zfree(itimer_zone, it);
1400 #ifndef _SYS_SYSPROTO_H_
1401 struct ktimer_settime_args {
1404 const struct itimerspec * value;
1405 struct itimerspec * ovalue;
1409 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1411 struct itimerspec val, oval, *ovalp;
1414 error = copyin(uap->value, &val, sizeof(val));
1417 ovalp = uap->ovalue != NULL ? &oval : NULL;
1418 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1419 if (error == 0 && uap->ovalue != NULL)
1420 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1425 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1426 struct itimerspec *val, struct itimerspec *oval)
1434 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1440 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1448 #ifndef _SYS_SYSPROTO_H_
1449 struct ktimer_gettime_args {
1451 struct itimerspec * value;
1455 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1457 struct itimerspec val;
1460 error = kern_ktimer_gettime(td, uap->timerid, &val);
1462 error = copyout(&val, uap->value, sizeof(val));
1467 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1475 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1481 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1488 #ifndef _SYS_SYSPROTO_H_
1489 struct timer_getoverrun_args {
1494 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1497 return (kern_ktimer_getoverrun(td, uap->timerid));
1501 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1503 struct proc *p = td->td_proc;
1509 (it = itimer_find(p, timer_id)) == NULL) {
1513 td->td_retval[0] = it->it_overrun_last;
1522 realtimer_create(struct itimer *it)
1524 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1529 realtimer_delete(struct itimer *it)
1531 mtx_assert(&it->it_mtx, MA_OWNED);
1534 * clear timer's value and interval to tell realtimer_expire
1535 * to not rearm the timer.
1537 timespecclear(&it->it_time.it_value);
1538 timespecclear(&it->it_time.it_interval);
1540 callout_drain(&it->it_callout);
1546 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1548 struct timespec cts;
1550 mtx_assert(&it->it_mtx, MA_OWNED);
1552 realtimer_clocktime(it->it_clockid, &cts);
1553 *ovalue = it->it_time;
1554 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1555 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1556 if (ovalue->it_value.tv_sec < 0 ||
1557 (ovalue->it_value.tv_sec == 0 &&
1558 ovalue->it_value.tv_nsec == 0)) {
1559 ovalue->it_value.tv_sec = 0;
1560 ovalue->it_value.tv_nsec = 1;
1567 realtimer_settime(struct itimer *it, int flags, struct itimerspec *value,
1568 struct itimerspec *ovalue)
1570 struct timespec cts, ts;
1572 struct itimerspec val;
1574 mtx_assert(&it->it_mtx, MA_OWNED);
1577 if (itimespecfix(&val.it_value))
1580 if (timespecisset(&val.it_value)) {
1581 if (itimespecfix(&val.it_interval))
1584 timespecclear(&val.it_interval);
1588 realtimer_gettime(it, ovalue);
1591 if (timespecisset(&val.it_value)) {
1592 realtimer_clocktime(it->it_clockid, &cts);
1594 if ((flags & TIMER_ABSTIME) == 0) {
1595 /* Convert to absolute time. */
1596 timespecadd(&it->it_time.it_value, &cts,
1597 &it->it_time.it_value);
1599 timespecsub(&ts, &cts, &ts);
1601 * We don't care if ts is negative, tztohz will
1605 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1606 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1609 callout_stop(&it->it_callout);
1616 realtimer_clocktime(clockid_t id, struct timespec *ts)
1618 if (id == CLOCK_REALTIME)
1620 else /* CLOCK_MONOTONIC */
1625 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1629 PROC_LOCK_ASSERT(p, MA_OWNED);
1630 it = itimer_find(p, timerid);
1632 ksi->ksi_overrun = it->it_overrun;
1633 it->it_overrun_last = it->it_overrun;
1642 itimespecfix(struct timespec *ts)
1645 if (!timespecvalid_interval(ts))
1647 if ((UINT64_MAX - ts->tv_nsec) / NS_PER_SEC < ts->tv_sec)
1649 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1650 ts->tv_nsec = tick * 1000;
1654 #define timespectons(tsp) \
1655 ((uint64_t)(tsp)->tv_sec * NS_PER_SEC + (tsp)->tv_nsec)
1656 #define timespecfromns(ns) (struct timespec){ \
1657 .tv_sec = (ns) / NS_PER_SEC, \
1658 .tv_nsec = (ns) % NS_PER_SEC \
1662 realtimer_expire_l(struct itimer *it, bool proc_locked)
1664 struct timespec cts, ts;
1667 uint64_t interval, now, overruns, value;
1669 realtimer_clocktime(it->it_clockid, &cts);
1670 /* Only fire if time is reached. */
1671 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1672 if (timespecisset(&it->it_time.it_interval)) {
1673 timespecadd(&it->it_time.it_value,
1674 &it->it_time.it_interval,
1675 &it->it_time.it_value);
1677 interval = timespectons(&it->it_time.it_interval);
1678 value = timespectons(&it->it_time.it_value);
1679 now = timespectons(&cts);
1683 * We missed at least one period.
1685 overruns = howmany(now - value + 1, interval);
1686 if (it->it_overrun + overruns >=
1688 it->it_overrun + overruns <= INT_MAX) {
1689 it->it_overrun += (int)overruns;
1691 it->it_overrun = INT_MAX;
1692 it->it_ksi.ksi_errno = ERANGE;
1695 now + interval - (now - value) % interval;
1696 it->it_time.it_value = timespecfromns(value);
1699 /* single shot timer ? */
1700 timespecclear(&it->it_time.it_value);
1704 if (timespecisset(&it->it_time.it_value)) {
1705 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1706 it->it_flags |= ITF_PSTOPPED;
1708 timespecsub(&it->it_time.it_value, &cts, &ts);
1709 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1710 callout_reset(&it->it_callout, tvtohz(&tv),
1711 realtimer_expire, it);
1724 } else if (timespecisset(&it->it_time.it_value)) {
1726 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1727 it->it_flags |= ITF_PSTOPPED;
1729 ts = it->it_time.it_value;
1730 timespecsub(&ts, &cts, &ts);
1731 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1732 callout_reset(&it->it_callout, tvtohz(&tv),
1733 realtimer_expire, it);
1738 /* Timeout callback for realtime timer */
1740 realtimer_expire(void *arg)
1742 realtimer_expire_l(arg, false);
1746 itimer_fire(struct itimer *it)
1748 struct proc *p = it->it_proc;
1751 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1752 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1753 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1755 timespecclear(&it->it_time.it_value);
1756 timespecclear(&it->it_time.it_interval);
1757 callout_stop(&it->it_callout);
1761 if (!KSI_ONQ(&it->it_ksi)) {
1762 it->it_ksi.ksi_errno = 0;
1763 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1764 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1766 if (it->it_overrun < INT_MAX)
1769 it->it_ksi.ksi_errno = ERANGE;
1776 itimers_alloc(struct proc *p)
1778 struct itimers *its;
1780 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1782 if (p->p_itimers == NULL) {
1788 free(its, M_SUBPROC);
1792 /* Clean up timers when some process events are being triggered. */
1794 itimers_event_exit_exec(int start_idx, struct proc *p)
1796 struct itimers *its;
1804 for (i = start_idx; i < TIMER_MAX; ++i) {
1805 if ((it = its->its_timers[i]) != NULL)
1806 kern_ktimer_delete(curthread, i);
1808 if (its->its_timers[0] == NULL && its->its_timers[1] == NULL &&
1809 its->its_timers[2] == NULL) {
1810 /* Synchronize with itimer_proc_continue(). */
1812 p->p_itimers = NULL;
1814 free(its, M_SUBPROC);
1819 itimers_exec(struct proc *p)
1822 * According to susv3, XSI interval timers should be inherited
1825 itimers_event_exit_exec(3, p);
1829 itimers_exit(struct proc *p)
1831 itimers_event_exit_exec(0, p);