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>
62 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
63 #define CPUCLOCK_BIT 0x80000000
64 #define CPUCLOCK_PROCESS_BIT 0x40000000
65 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
66 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
67 #define MAKE_PROCESS_CPUCLOCK(pid) \
68 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
70 #define NS_PER_SEC 1000000000
72 static struct kclock posix_clocks[MAX_CLOCKS];
73 static uma_zone_t itimer_zone = NULL;
76 * Time of day and interval timer support.
78 * These routines provide the kernel entry points to get and set
79 * the time-of-day and per-process interval timers. Subroutines
80 * here provide support for adding and subtracting timeval structures
81 * and decrementing interval timers, optionally reloading the interval
82 * timers when they expire.
85 static int settime(struct thread *, struct timeval *);
86 static void timevalfix(struct timeval *);
87 static int user_clock_nanosleep(struct thread *td, clockid_t clock_id,
88 int flags, const struct timespec *ua_rqtp,
89 struct timespec *ua_rmtp);
91 static void itimer_start(void);
92 static int itimer_init(void *, int, int);
93 static void itimer_fini(void *, int);
94 static void itimer_enter(struct itimer *);
95 static void itimer_leave(struct itimer *);
96 static struct itimer *itimer_find(struct proc *, int);
97 static void itimers_alloc(struct proc *);
98 static int realtimer_create(struct itimer *);
99 static int realtimer_gettime(struct itimer *, struct itimerspec *);
100 static int realtimer_settime(struct itimer *, int,
101 struct itimerspec *, struct itimerspec *);
102 static int realtimer_delete(struct itimer *);
103 static void realtimer_clocktime(clockid_t, struct timespec *);
104 static void realtimer_expire(void *);
105 static void realtimer_expire_l(struct itimer *it, bool proc_locked);
107 static void realitexpire(void *arg);
109 static int register_posix_clock(int, const struct kclock *);
110 static void itimer_fire(struct itimer *it);
111 static int itimespecfix(struct timespec *ts);
113 #define CLOCK_CALL(clock, call, arglist) \
114 ((*posix_clocks[clock].call) arglist)
116 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
119 settime(struct thread *td, struct timeval *tv)
121 struct timeval delta, tv1, tv2;
122 static struct timeval maxtime, laststep;
127 timevalsub(&delta, &tv1);
130 * If the system is secure, we do not allow the time to be
131 * set to a value earlier than 1 second less than the highest
132 * time we have yet seen. The worst a miscreant can do in
133 * this circumstance is "freeze" time. He couldn't go
136 * We similarly do not allow the clock to be stepped more
137 * than one second, nor more than once per second. This allows
138 * a miscreant to make the clock march double-time, but no worse.
140 if (securelevel_gt(td->td_ucred, 1) != 0) {
141 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
143 * Update maxtime to latest time we've seen.
145 if (tv1.tv_sec > maxtime.tv_sec)
148 timevalsub(&tv2, &maxtime);
149 if (tv2.tv_sec < -1) {
150 tv->tv_sec = maxtime.tv_sec - 1;
151 printf("Time adjustment clamped to -1 second\n");
154 if (tv1.tv_sec == laststep.tv_sec)
156 if (delta.tv_sec > 1) {
157 tv->tv_sec = tv1.tv_sec + 1;
158 printf("Time adjustment clamped to +1 second\n");
164 ts.tv_sec = tv->tv_sec;
165 ts.tv_nsec = tv->tv_usec * 1000;
171 #ifndef _SYS_SYSPROTO_H_
172 struct clock_getcpuclockid2_args {
180 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
185 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
187 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
192 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
201 case CPUCLOCK_WHICH_PID:
203 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
209 pid = td->td_proc->p_pid;
211 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
213 case CPUCLOCK_WHICH_TID:
214 tid = id == 0 ? td->td_tid : id;
215 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
222 #ifndef _SYS_SYSPROTO_H_
223 struct clock_gettime_args {
230 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
235 error = kern_clock_gettime(td, uap->clock_id, &ats);
237 error = copyout(&ats, uap->tp, sizeof(ats));
243 cputick2timespec(uint64_t runtime, struct timespec *ats)
247 ats->tv_sec = runtime / tr;
248 ats->tv_nsec = ((runtime % tr) * 1000000000ULL) / tr;
252 kern_thread_cputime(struct thread *targettd, struct timespec *ats)
254 uint64_t runtime, curtime, switchtime;
256 if (targettd == NULL) { /* current thread */
258 switchtime = PCPU_GET(switchtime);
259 curtime = cpu_ticks();
260 runtime = curthread->td_runtime;
262 runtime += curtime - switchtime;
264 PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
265 thread_lock(targettd);
266 runtime = targettd->td_runtime;
267 thread_unlock(targettd);
269 cputick2timespec(runtime, ats);
273 kern_process_cputime(struct proc *targetp, struct timespec *ats)
278 PROC_LOCK_ASSERT(targetp, MA_OWNED);
279 PROC_STATLOCK(targetp);
280 rufetch(targetp, &ru);
281 runtime = targetp->p_rux.rux_runtime;
282 if (curthread->td_proc == targetp)
283 runtime += cpu_ticks() - PCPU_GET(switchtime);
284 PROC_STATUNLOCK(targetp);
285 cputick2timespec(runtime, ats);
289 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
298 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
299 tid = clock_id & CPUCLOCK_ID_MASK;
300 td2 = tdfind(tid, p->p_pid);
303 kern_thread_cputime(td2, ats);
304 PROC_UNLOCK(td2->td_proc);
306 pid = clock_id & CPUCLOCK_ID_MASK;
307 error = pget(pid, PGET_CANSEE, &p2);
310 kern_process_cputime(p2, ats);
317 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
319 struct timeval sys, user;
324 case CLOCK_REALTIME: /* Default to precise. */
325 case CLOCK_REALTIME_PRECISE:
328 case CLOCK_REALTIME_FAST:
334 calcru(p, &user, &sys);
337 TIMEVAL_TO_TIMESPEC(&user, ats);
342 calcru(p, &user, &sys);
345 timevaladd(&user, &sys);
346 TIMEVAL_TO_TIMESPEC(&user, ats);
348 case CLOCK_MONOTONIC: /* Default to precise. */
349 case CLOCK_MONOTONIC_PRECISE:
351 case CLOCK_UPTIME_PRECISE:
354 case CLOCK_UPTIME_FAST:
355 case CLOCK_MONOTONIC_FAST:
359 ats->tv_sec = time_second;
362 case CLOCK_THREAD_CPUTIME_ID:
363 kern_thread_cputime(NULL, ats);
365 case CLOCK_PROCESS_CPUTIME_ID:
367 kern_process_cputime(p, ats);
371 if ((int)clock_id >= 0)
373 return (get_cputime(td, clock_id, ats));
378 #ifndef _SYS_SYSPROTO_H_
379 struct clock_settime_args {
381 const struct timespec *tp;
386 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
391 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
393 return (kern_clock_settime(td, uap->clock_id, &ats));
396 static int allow_insane_settime = 0;
397 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
398 &allow_insane_settime, 0,
399 "do not perform possibly restrictive checks on settime(2) args");
402 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
407 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
409 if (clock_id != CLOCK_REALTIME)
411 if (!timespecvalid_interval(ats))
413 if (!allow_insane_settime &&
414 (ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60 ||
415 ats->tv_sec < utc_offset()))
417 /* XXX Don't convert nsec->usec and back */
418 TIMESPEC_TO_TIMEVAL(&atv, ats);
419 error = settime(td, &atv);
423 #ifndef _SYS_SYSPROTO_H_
424 struct clock_getres_args {
430 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
438 error = kern_clock_getres(td, uap->clock_id, &ts);
440 error = copyout(&ts, uap->tp, sizeof(ts));
445 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
451 case CLOCK_REALTIME_FAST:
452 case CLOCK_REALTIME_PRECISE:
453 case CLOCK_MONOTONIC:
454 case CLOCK_MONOTONIC_FAST:
455 case CLOCK_MONOTONIC_PRECISE:
457 case CLOCK_UPTIME_FAST:
458 case CLOCK_UPTIME_PRECISE:
460 * Round up the result of the division cheaply by adding 1.
461 * Rounding up is especially important if rounding down
462 * would give 0. Perfect rounding is unimportant.
464 ts->tv_nsec = NS_PER_SEC / tc_getfrequency() + 1;
468 /* Accurately round up here because we can do so cheaply. */
469 ts->tv_nsec = howmany(NS_PER_SEC, hz);
475 case CLOCK_THREAD_CPUTIME_ID:
476 case CLOCK_PROCESS_CPUTIME_ID:
478 ts->tv_nsec = 1000000000 / cpu_tickrate() + 1;
481 if ((int)clock_id < 0)
489 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
492 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
496 static uint8_t nanowait[MAXCPU];
499 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
500 const struct timespec *rqt, struct timespec *rmt)
502 struct timespec ts, now;
503 sbintime_t sbt, sbtt, prec, tmp;
508 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= NS_PER_SEC)
510 if ((flags & ~TIMER_ABSTIME) != 0)
514 case CLOCK_REALTIME_PRECISE:
515 case CLOCK_REALTIME_FAST:
517 is_abs_real = (flags & TIMER_ABSTIME) != 0;
519 case CLOCK_MONOTONIC:
520 case CLOCK_MONOTONIC_PRECISE:
521 case CLOCK_MONOTONIC_FAST:
523 case CLOCK_UPTIME_PRECISE:
524 case CLOCK_UPTIME_FAST:
529 case CLOCK_PROCESS_CPUTIME_ID:
531 case CLOCK_THREAD_CPUTIME_ID:
537 if ((flags & TIMER_ABSTIME) != 0) {
540 atomic_load_acq_int(&rtc_generation);
541 error = kern_clock_gettime(td, clock_id, &now);
542 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
543 timespecsub(&ts, &now, &ts);
545 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
549 if (ts.tv_sec > INT32_MAX / 2) {
550 over = ts.tv_sec - INT32_MAX / 2;
557 if (TIMESEL(&sbt, tmp))
560 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
561 sbt, prec, C_ABSOLUTE);
562 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
564 if (error != EWOULDBLOCK) {
565 if (TIMESEL(&sbtt, tmp))
569 if (error == ERESTART)
571 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
572 ts = sbttots(sbt - sbtt);
583 #ifndef _SYS_SYSPROTO_H_
584 struct nanosleep_args {
585 struct timespec *rqtp;
586 struct timespec *rmtp;
591 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
594 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
595 uap->rqtp, uap->rmtp));
598 #ifndef _SYS_SYSPROTO_H_
599 struct clock_nanosleep_args {
602 struct timespec *rqtp;
603 struct timespec *rmtp;
608 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
612 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
614 return (kern_posix_error(td, error));
618 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
619 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
621 struct timespec rmt, rqt;
624 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
627 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
628 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
629 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
636 #ifndef _SYS_SYSPROTO_H_
637 struct gettimeofday_args {
639 struct timezone *tzp;
644 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
652 error = copyout(&atv, uap->tp, sizeof (atv));
654 if (error == 0 && uap->tzp != NULL) {
655 rtz.tz_minuteswest = 0;
657 error = copyout(&rtz, uap->tzp, sizeof (rtz));
662 #ifndef _SYS_SYSPROTO_H_
663 struct settimeofday_args {
665 struct timezone *tzp;
670 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
672 struct timeval atv, *tvp;
673 struct timezone atz, *tzp;
677 error = copyin(uap->tv, &atv, sizeof(atv));
684 error = copyin(uap->tzp, &atz, sizeof(atz));
690 return (kern_settimeofday(td, tvp, tzp));
694 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
698 error = priv_check(td, PRIV_SETTIMEOFDAY);
701 /* Verify all parameters before changing time. */
703 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
706 error = settime(td, tv);
712 * Get value of an interval timer. The process virtual and profiling virtual
713 * time timers are kept in the p_stats area, since they can be swapped out.
714 * These are kept internally in the way they are specified externally: in
715 * time until they expire.
717 * The real time interval timer is kept in the process table slot for the
718 * process, and its value (it_value) is kept as an absolute time rather than
719 * as a delta, so that it is easy to keep periodic real-time signals from
722 * Virtual time timers are processed in the hardclock() routine of
723 * kern_clock.c. The real time timer is processed by a timeout routine,
724 * called from the softclock() routine. Since a callout may be delayed in
725 * real time due to interrupt processing in the system, it is possible for
726 * the real time timeout routine (realitexpire, given below), to be delayed
727 * in real time past when it is supposed to occur. It does not suffice,
728 * therefore, to reload the real timer .it_value from the real time timers
729 * .it_interval. Rather, we compute the next time in absolute time the timer
732 #ifndef _SYS_SYSPROTO_H_
733 struct getitimer_args {
735 struct itimerval *itv;
739 sys_getitimer(struct thread *td, struct getitimer_args *uap)
741 struct itimerval aitv;
744 error = kern_getitimer(td, uap->which, &aitv);
747 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
751 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
753 struct proc *p = td->td_proc;
756 if (which > ITIMER_PROF)
759 if (which == ITIMER_REAL) {
761 * Convert from absolute to relative time in .it_value
762 * part of real time timer. If time for real time timer
763 * has passed return 0, else return difference between
764 * current time and time for the timer to go off.
767 *aitv = p->p_realtimer;
769 if (timevalisset(&aitv->it_value)) {
771 if (timevalcmp(&aitv->it_value, &ctv, <))
772 timevalclear(&aitv->it_value);
774 timevalsub(&aitv->it_value, &ctv);
778 *aitv = p->p_stats->p_timer[which];
782 if (KTRPOINT(td, KTR_STRUCT))
788 #ifndef _SYS_SYSPROTO_H_
789 struct setitimer_args {
791 struct itimerval *itv, *oitv;
795 sys_setitimer(struct thread *td, struct setitimer_args *uap)
797 struct itimerval aitv, oitv;
800 if (uap->itv == NULL) {
801 uap->itv = uap->oitv;
802 return (sys_getitimer(td, (struct getitimer_args *)uap));
805 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
807 error = kern_setitimer(td, uap->which, &aitv, &oitv);
808 if (error != 0 || uap->oitv == NULL)
810 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
814 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
815 struct itimerval *oitv)
817 struct proc *p = td->td_proc;
822 return (kern_getitimer(td, which, oitv));
824 if (which > ITIMER_PROF)
827 if (KTRPOINT(td, KTR_STRUCT))
830 if (itimerfix(&aitv->it_value) ||
831 aitv->it_value.tv_sec > INT32_MAX / 2)
833 if (!timevalisset(&aitv->it_value))
834 timevalclear(&aitv->it_interval);
835 else if (itimerfix(&aitv->it_interval) ||
836 aitv->it_interval.tv_sec > INT32_MAX / 2)
839 if (which == ITIMER_REAL) {
841 if (timevalisset(&p->p_realtimer.it_value))
842 callout_stop(&p->p_itcallout);
844 if (timevalisset(&aitv->it_value)) {
845 pr = tvtosbt(aitv->it_value) >> tc_precexp;
846 timevaladd(&aitv->it_value, &ctv);
847 sbt = tvtosbt(aitv->it_value);
848 callout_reset_sbt(&p->p_itcallout, sbt, pr,
849 realitexpire, p, C_ABSOLUTE);
851 *oitv = p->p_realtimer;
852 p->p_realtimer = *aitv;
854 if (timevalisset(&oitv->it_value)) {
855 if (timevalcmp(&oitv->it_value, &ctv, <))
856 timevalclear(&oitv->it_value);
858 timevalsub(&oitv->it_value, &ctv);
861 if (aitv->it_interval.tv_sec == 0 &&
862 aitv->it_interval.tv_usec != 0 &&
863 aitv->it_interval.tv_usec < tick)
864 aitv->it_interval.tv_usec = tick;
865 if (aitv->it_value.tv_sec == 0 &&
866 aitv->it_value.tv_usec != 0 &&
867 aitv->it_value.tv_usec < tick)
868 aitv->it_value.tv_usec = tick;
870 *oitv = p->p_stats->p_timer[which];
871 p->p_stats->p_timer[which] = *aitv;
875 if (KTRPOINT(td, KTR_STRUCT))
882 realitexpire_reset_callout(struct proc *p, sbintime_t *isbtp)
886 prec = isbtp == NULL ? tvtosbt(p->p_realtimer.it_interval) : *isbtp;
887 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
888 prec >> tc_precexp, realitexpire, p, C_ABSOLUTE);
892 itimer_proc_continue(struct proc *p)
898 PROC_LOCK_ASSERT(p, MA_OWNED);
900 if ((p->p_flag2 & P2_ITSTOPPED) != 0) {
901 p->p_flag2 &= ~P2_ITSTOPPED;
903 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >=))
906 realitexpire_reset_callout(p, NULL);
909 if (p->p_itimers != NULL) {
910 for (id = 3; id < TIMER_MAX; id++) {
911 it = p->p_itimers->its_timers[id];
914 if ((it->it_flags & ITF_PSTOPPED) != 0) {
916 if ((it->it_flags & ITF_PSTOPPED) != 0) {
917 it->it_flags &= ~ITF_PSTOPPED;
918 if ((it->it_flags & ITF_DELETING) == 0)
919 realtimer_expire_l(it, true);
928 * Real interval timer expired:
929 * send process whose timer expired an alarm signal.
930 * If time is not set up to reload, then just return.
931 * Else compute next time timer should go off which is > current time.
932 * This is where delay in processing this timeout causes multiple
933 * SIGALRM calls to be compressed into one.
934 * tvtohz() always adds 1 to allow for the time until the next clock
935 * interrupt being strictly less than 1 clock tick, but we don't want
936 * that here since we want to appear to be in sync with the clock
937 * interrupt even when we're delayed.
940 realitexpire(void *arg)
946 p = (struct proc *)arg;
947 kern_psignal(p, SIGALRM);
948 if (!timevalisset(&p->p_realtimer.it_interval)) {
949 timevalclear(&p->p_realtimer.it_value);
953 isbt = tvtosbt(p->p_realtimer.it_interval);
954 if (isbt >= sbt_timethreshold)
955 getmicrouptime(&ctv);
959 timevaladd(&p->p_realtimer.it_value,
960 &p->p_realtimer.it_interval);
961 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
963 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
964 p->p_flag2 |= P2_ITSTOPPED;
968 p->p_flag2 &= ~P2_ITSTOPPED;
969 realitexpire_reset_callout(p, &isbt);
973 * Check that a proposed value to load into the .it_value or
974 * .it_interval part of an interval timer is acceptable, and
975 * fix it to have at least minimal value (i.e. if it is less
976 * than the resolution of the clock, round it up.)
979 itimerfix(struct timeval *tv)
982 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
984 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
985 tv->tv_usec < (u_int)tick / 16)
986 tv->tv_usec = (u_int)tick / 16;
991 * Decrement an interval timer by a specified number
992 * of microseconds, which must be less than a second,
993 * i.e. < 1000000. If the timer expires, then reload
994 * it. In this case, carry over (usec - old value) to
995 * reduce the value reloaded into the timer so that
996 * the timer does not drift. This routine assumes
997 * that it is called in a context where the timers
998 * on which it is operating cannot change in value.
1001 itimerdecr(struct itimerval *itp, int usec)
1004 if (itp->it_value.tv_usec < usec) {
1005 if (itp->it_value.tv_sec == 0) {
1006 /* expired, and already in next interval */
1007 usec -= itp->it_value.tv_usec;
1010 itp->it_value.tv_usec += 1000000;
1011 itp->it_value.tv_sec--;
1013 itp->it_value.tv_usec -= usec;
1015 if (timevalisset(&itp->it_value))
1017 /* expired, exactly at end of interval */
1019 if (timevalisset(&itp->it_interval)) {
1020 itp->it_value = itp->it_interval;
1021 itp->it_value.tv_usec -= usec;
1022 if (itp->it_value.tv_usec < 0) {
1023 itp->it_value.tv_usec += 1000000;
1024 itp->it_value.tv_sec--;
1027 itp->it_value.tv_usec = 0; /* sec is already 0 */
1032 * Add and subtract routines for timevals.
1033 * N.B.: subtract routine doesn't deal with
1034 * results which are before the beginning,
1035 * it just gets very confused in this case.
1039 timevaladd(struct timeval *t1, const struct timeval *t2)
1042 t1->tv_sec += t2->tv_sec;
1043 t1->tv_usec += t2->tv_usec;
1048 timevalsub(struct timeval *t1, const struct timeval *t2)
1051 t1->tv_sec -= t2->tv_sec;
1052 t1->tv_usec -= t2->tv_usec;
1057 timevalfix(struct timeval *t1)
1060 if (t1->tv_usec < 0) {
1062 t1->tv_usec += 1000000;
1064 if (t1->tv_usec >= 1000000) {
1066 t1->tv_usec -= 1000000;
1071 * ratecheck(): simple time-based rate-limit checking.
1074 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1076 struct timeval tv, delta;
1079 getmicrouptime(&tv); /* NB: 10ms precision */
1081 timevalsub(&delta, lasttime);
1084 * check for 0,0 is so that the message will be seen at least once,
1085 * even if interval is huge.
1087 if (timevalcmp(&delta, mininterval, >=) ||
1088 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1097 * eventratecheck(): events per second limitation.
1099 * Return 0 if the limit is to be enforced (e.g. the caller
1100 * should ignore the event because of the rate limitation).
1102 * maxeps of 0 always causes zero to be returned. maxeps of -1
1103 * always causes 1 to be returned; this effectively defeats rate
1106 * Note that we maintain the struct timeval for compatibility
1107 * with other bsd systems. We reuse the storage and just monitor
1108 * clock ticks for minimal overhead.
1111 eventratecheck(struct timeval *lasttime, int *cureps, int maxeps)
1116 * Reset the last time and counter if this is the first call
1117 * or more than a second has passed since the last update of
1121 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1122 lasttime->tv_sec = now;
1124 return (maxeps != 0);
1126 (*cureps)++; /* NB: ignore potential overflow */
1127 return (maxeps < 0 || *cureps <= maxeps);
1134 static const struct kclock rt_clock = {
1135 .timer_create = realtimer_create,
1136 .timer_delete = realtimer_delete,
1137 .timer_settime = realtimer_settime,
1138 .timer_gettime = realtimer_gettime,
1141 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1142 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1143 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1144 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1145 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1146 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1147 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1151 register_posix_clock(int clockid, const struct kclock *clk)
1153 if ((unsigned)clockid >= MAX_CLOCKS) {
1154 printf("%s: invalid clockid\n", __func__);
1157 posix_clocks[clockid] = *clk;
1162 itimer_init(void *mem, int size, int flags)
1166 it = (struct itimer *)mem;
1167 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1172 itimer_fini(void *mem, int size)
1176 it = (struct itimer *)mem;
1177 mtx_destroy(&it->it_mtx);
1181 itimer_enter(struct itimer *it)
1184 mtx_assert(&it->it_mtx, MA_OWNED);
1189 itimer_leave(struct itimer *it)
1192 mtx_assert(&it->it_mtx, MA_OWNED);
1193 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1195 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1199 #ifndef _SYS_SYSPROTO_H_
1200 struct ktimer_create_args {
1202 struct sigevent * evp;
1207 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1209 struct sigevent *evp, ev;
1213 if (uap->evp == NULL) {
1216 error = copyin(uap->evp, &ev, sizeof(ev));
1221 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1223 error = copyout(&id, uap->timerid, sizeof(int));
1225 kern_ktimer_delete(td, id);
1231 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1232 int *timerid, int preset_id)
1234 struct proc *p = td->td_proc;
1239 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1242 if (posix_clocks[clock_id].timer_create == NULL)
1246 if (evp->sigev_notify != SIGEV_NONE &&
1247 evp->sigev_notify != SIGEV_SIGNAL &&
1248 evp->sigev_notify != SIGEV_THREAD_ID)
1250 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1251 evp->sigev_notify == SIGEV_THREAD_ID) &&
1252 !_SIG_VALID(evp->sigev_signo))
1256 if (p->p_itimers == NULL)
1259 it = uma_zalloc(itimer_zone, M_WAITOK);
1261 it->it_usecount = 0;
1262 timespecclear(&it->it_time.it_value);
1263 timespecclear(&it->it_time.it_interval);
1265 it->it_overrun_last = 0;
1266 it->it_clockid = clock_id;
1268 ksiginfo_init(&it->it_ksi);
1269 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1270 error = CLOCK_CALL(clock_id, timer_create, (it));
1275 if (preset_id != -1) {
1276 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1278 if (p->p_itimers->its_timers[id] != NULL) {
1285 * Find a free timer slot, skipping those reserved
1288 for (id = 3; id < TIMER_MAX; id++)
1289 if (p->p_itimers->its_timers[id] == NULL)
1291 if (id == TIMER_MAX) {
1297 p->p_itimers->its_timers[id] = it;
1299 it->it_sigev = *evp;
1301 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1304 case CLOCK_REALTIME:
1305 it->it_sigev.sigev_signo = SIGALRM;
1308 it->it_sigev.sigev_signo = SIGVTALRM;
1311 it->it_sigev.sigev_signo = SIGPROF;
1314 it->it_sigev.sigev_value.sival_int = id;
1317 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1318 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1319 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1320 it->it_ksi.ksi_code = SI_TIMER;
1321 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1322 it->it_ksi.ksi_timerid = id;
1330 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1332 uma_zfree(itimer_zone, it);
1336 #ifndef _SYS_SYSPROTO_H_
1337 struct ktimer_delete_args {
1342 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1345 return (kern_ktimer_delete(td, uap->timerid));
1348 static struct itimer *
1349 itimer_find(struct proc *p, int timerid)
1353 PROC_LOCK_ASSERT(p, MA_OWNED);
1354 if ((p->p_itimers == NULL) ||
1355 (timerid < 0) || (timerid >= TIMER_MAX) ||
1356 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1360 if ((it->it_flags & ITF_DELETING) != 0) {
1368 kern_ktimer_delete(struct thread *td, int timerid)
1370 struct proc *p = td->td_proc;
1374 it = itimer_find(p, timerid);
1381 it->it_flags |= ITF_DELETING;
1382 while (it->it_usecount > 0) {
1383 it->it_flags |= ITF_WANTED;
1384 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1386 it->it_flags &= ~ITF_WANTED;
1387 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1391 if (KSI_ONQ(&it->it_ksi))
1392 sigqueue_take(&it->it_ksi);
1393 p->p_itimers->its_timers[timerid] = NULL;
1395 uma_zfree(itimer_zone, it);
1399 #ifndef _SYS_SYSPROTO_H_
1400 struct ktimer_settime_args {
1403 const struct itimerspec * value;
1404 struct itimerspec * ovalue;
1408 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1410 struct itimerspec val, oval, *ovalp;
1413 error = copyin(uap->value, &val, sizeof(val));
1416 ovalp = uap->ovalue != NULL ? &oval : NULL;
1417 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1418 if (error == 0 && uap->ovalue != NULL)
1419 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1424 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1425 struct itimerspec *val, struct itimerspec *oval)
1433 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1439 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1447 #ifndef _SYS_SYSPROTO_H_
1448 struct ktimer_gettime_args {
1450 struct itimerspec * value;
1454 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1456 struct itimerspec val;
1459 error = kern_ktimer_gettime(td, uap->timerid, &val);
1461 error = copyout(&val, uap->value, sizeof(val));
1466 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1474 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1480 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1487 #ifndef _SYS_SYSPROTO_H_
1488 struct timer_getoverrun_args {
1493 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1496 return (kern_ktimer_getoverrun(td, uap->timerid));
1500 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1502 struct proc *p = td->td_proc;
1508 (it = itimer_find(p, timer_id)) == NULL) {
1512 td->td_retval[0] = it->it_overrun_last;
1521 realtimer_create(struct itimer *it)
1523 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1528 realtimer_delete(struct itimer *it)
1530 mtx_assert(&it->it_mtx, MA_OWNED);
1533 * clear timer's value and interval to tell realtimer_expire
1534 * to not rearm the timer.
1536 timespecclear(&it->it_time.it_value);
1537 timespecclear(&it->it_time.it_interval);
1539 callout_drain(&it->it_callout);
1545 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1547 struct timespec cts;
1549 mtx_assert(&it->it_mtx, MA_OWNED);
1551 realtimer_clocktime(it->it_clockid, &cts);
1552 *ovalue = it->it_time;
1553 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1554 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1555 if (ovalue->it_value.tv_sec < 0 ||
1556 (ovalue->it_value.tv_sec == 0 &&
1557 ovalue->it_value.tv_nsec == 0)) {
1558 ovalue->it_value.tv_sec = 0;
1559 ovalue->it_value.tv_nsec = 1;
1566 realtimer_settime(struct itimer *it, int flags, struct itimerspec *value,
1567 struct itimerspec *ovalue)
1569 struct timespec cts, ts;
1571 struct itimerspec val;
1573 mtx_assert(&it->it_mtx, MA_OWNED);
1576 if (itimespecfix(&val.it_value))
1579 if (timespecisset(&val.it_value)) {
1580 if (itimespecfix(&val.it_interval))
1583 timespecclear(&val.it_interval);
1587 realtimer_gettime(it, ovalue);
1590 if (timespecisset(&val.it_value)) {
1591 realtimer_clocktime(it->it_clockid, &cts);
1593 if ((flags & TIMER_ABSTIME) == 0) {
1594 /* Convert to absolute time. */
1595 timespecadd(&it->it_time.it_value, &cts,
1596 &it->it_time.it_value);
1598 timespecsub(&ts, &cts, &ts);
1600 * We don't care if ts is negative, tztohz will
1604 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1605 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1608 callout_stop(&it->it_callout);
1615 realtimer_clocktime(clockid_t id, struct timespec *ts)
1617 if (id == CLOCK_REALTIME)
1619 else /* CLOCK_MONOTONIC */
1624 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1628 PROC_LOCK_ASSERT(p, MA_OWNED);
1629 it = itimer_find(p, timerid);
1631 ksi->ksi_overrun = it->it_overrun;
1632 it->it_overrun_last = it->it_overrun;
1641 itimespecfix(struct timespec *ts)
1644 if (!timespecvalid_interval(ts))
1646 if ((UINT64_MAX - ts->tv_nsec) / NS_PER_SEC < ts->tv_sec)
1648 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1649 ts->tv_nsec = tick * 1000;
1653 #define timespectons(tsp) \
1654 ((uint64_t)(tsp)->tv_sec * NS_PER_SEC + (tsp)->tv_nsec)
1655 #define timespecfromns(ns) (struct timespec){ \
1656 .tv_sec = (ns) / NS_PER_SEC, \
1657 .tv_nsec = (ns) % NS_PER_SEC \
1661 realtimer_expire_l(struct itimer *it, bool proc_locked)
1663 struct timespec cts, ts;
1666 uint64_t interval, now, overruns, value;
1668 realtimer_clocktime(it->it_clockid, &cts);
1669 /* Only fire if time is reached. */
1670 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1671 if (timespecisset(&it->it_time.it_interval)) {
1672 timespecadd(&it->it_time.it_value,
1673 &it->it_time.it_interval,
1674 &it->it_time.it_value);
1676 interval = timespectons(&it->it_time.it_interval);
1677 value = timespectons(&it->it_time.it_value);
1678 now = timespectons(&cts);
1682 * We missed at least one period.
1684 overruns = howmany(now - value + 1, interval);
1685 if (it->it_overrun + overruns >=
1687 it->it_overrun + overruns <= INT_MAX) {
1688 it->it_overrun += (int)overruns;
1690 it->it_overrun = INT_MAX;
1691 it->it_ksi.ksi_errno = ERANGE;
1694 now + interval - (now - value) % interval;
1695 it->it_time.it_value = timespecfromns(value);
1698 /* single shot timer ? */
1699 timespecclear(&it->it_time.it_value);
1703 if (timespecisset(&it->it_time.it_value)) {
1704 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1705 it->it_flags |= ITF_PSTOPPED;
1707 timespecsub(&it->it_time.it_value, &cts, &ts);
1708 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1709 callout_reset(&it->it_callout, tvtohz(&tv),
1710 realtimer_expire, it);
1723 } else if (timespecisset(&it->it_time.it_value)) {
1725 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1726 it->it_flags |= ITF_PSTOPPED;
1728 ts = it->it_time.it_value;
1729 timespecsub(&ts, &cts, &ts);
1730 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1731 callout_reset(&it->it_callout, tvtohz(&tv),
1732 realtimer_expire, it);
1737 /* Timeout callback for realtime timer */
1739 realtimer_expire(void *arg)
1741 realtimer_expire_l(arg, false);
1745 itimer_fire(struct itimer *it)
1747 struct proc *p = it->it_proc;
1750 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1751 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1752 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1754 timespecclear(&it->it_time.it_value);
1755 timespecclear(&it->it_time.it_interval);
1756 callout_stop(&it->it_callout);
1760 if (!KSI_ONQ(&it->it_ksi)) {
1761 it->it_ksi.ksi_errno = 0;
1762 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1763 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1765 if (it->it_overrun < INT_MAX)
1768 it->it_ksi.ksi_errno = ERANGE;
1775 itimers_alloc(struct proc *p)
1777 struct itimers *its;
1779 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1781 if (p->p_itimers == NULL) {
1787 free(its, M_SUBPROC);
1791 /* Clean up timers when some process events are being triggered. */
1793 itimers_event_exit_exec(int start_idx, struct proc *p)
1795 struct itimers *its;
1803 for (i = start_idx; i < TIMER_MAX; ++i) {
1804 if ((it = its->its_timers[i]) != NULL)
1805 kern_ktimer_delete(curthread, i);
1807 if (its->its_timers[0] == NULL && its->its_timers[1] == NULL &&
1808 its->its_timers[2] == NULL) {
1809 /* Synchronize with itimer_proc_continue(). */
1811 p->p_itimers = NULL;
1813 free(its, M_SUBPROC);
1818 itimers_exec(struct proc *p)
1821 * According to susv3, XSI interval timers should be inherited
1824 itimers_event_exit_exec(3, p);
1828 itimers_exit(struct proc *p)
1830 itimers_event_exit_exec(0, p);