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/eventhandler.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/kernel.h>
50 #include <sys/sleepqueue.h>
51 #include <sys/syscallsubr.h>
52 #include <sys/sysctl.h>
53 #include <sys/sysent.h>
56 #include <sys/posix4.h>
58 #include <sys/timers.h>
59 #include <sys/timetc.h>
60 #include <sys/vnode.h>
62 #include <sys/ktrace.h>
66 #include <vm/vm_extern.h>
68 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
69 #define CPUCLOCK_BIT 0x80000000
70 #define CPUCLOCK_PROCESS_BIT 0x40000000
71 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
72 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
73 #define MAKE_PROCESS_CPUCLOCK(pid) \
74 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
76 static struct kclock posix_clocks[MAX_CLOCKS];
77 static uma_zone_t itimer_zone = NULL;
80 * Time of day and interval timer support.
82 * These routines provide the kernel entry points to get and set
83 * the time-of-day and per-process interval timers. Subroutines
84 * here provide support for adding and subtracting timeval structures
85 * and decrementing interval timers, optionally reloading the interval
86 * timers when they expire.
89 static int settime(struct thread *, struct timeval *);
90 static void timevalfix(struct timeval *);
91 static int user_clock_nanosleep(struct thread *td, clockid_t clock_id,
92 int flags, const struct timespec *ua_rqtp,
93 struct timespec *ua_rmtp);
95 static void itimer_start(void);
96 static int itimer_init(void *, int, int);
97 static void itimer_fini(void *, int);
98 static void itimer_enter(struct itimer *);
99 static void itimer_leave(struct itimer *);
100 static struct itimer *itimer_find(struct proc *, int);
101 static void itimers_alloc(struct proc *);
102 static void itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
103 static void itimers_event_hook_exit(void *arg, struct proc *p);
104 static int realtimer_create(struct itimer *);
105 static int realtimer_gettime(struct itimer *, struct itimerspec *);
106 static int realtimer_settime(struct itimer *, int,
107 struct itimerspec *, struct itimerspec *);
108 static int realtimer_delete(struct itimer *);
109 static void realtimer_clocktime(clockid_t, struct timespec *);
110 static void realtimer_expire(void *);
112 int register_posix_clock(int, struct kclock *);
113 void itimer_fire(struct itimer *it);
114 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);
123 settime(struct thread *td, struct timeval *tv)
125 struct timeval delta, tv1, tv2;
126 static struct timeval maxtime, laststep;
131 timevalsub(&delta, &tv1);
134 * If the system is secure, we do not allow the time to be
135 * set to a value earlier than 1 second less than the highest
136 * time we have yet seen. The worst a miscreant can do in
137 * this circumstance is "freeze" time. He couldn't go
140 * We similarly do not allow the clock to be stepped more
141 * than one second, nor more than once per second. This allows
142 * a miscreant to make the clock march double-time, but no worse.
144 if (securelevel_gt(td->td_ucred, 1) != 0) {
145 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
147 * Update maxtime to latest time we've seen.
149 if (tv1.tv_sec > maxtime.tv_sec)
152 timevalsub(&tv2, &maxtime);
153 if (tv2.tv_sec < -1) {
154 tv->tv_sec = maxtime.tv_sec - 1;
155 printf("Time adjustment clamped to -1 second\n");
158 if (tv1.tv_sec == laststep.tv_sec)
160 if (delta.tv_sec > 1) {
161 tv->tv_sec = tv1.tv_sec + 1;
162 printf("Time adjustment clamped to +1 second\n");
168 ts.tv_sec = tv->tv_sec;
169 ts.tv_nsec = tv->tv_usec * 1000;
175 #ifndef _SYS_SYSPROTO_H_
176 struct clock_getcpuclockid2_args {
184 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
189 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
191 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
196 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
205 case CPUCLOCK_WHICH_PID:
207 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
213 pid = td->td_proc->p_pid;
215 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
217 case CPUCLOCK_WHICH_TID:
218 tid = id == 0 ? td->td_tid : id;
219 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
226 #ifndef _SYS_SYSPROTO_H_
227 struct clock_gettime_args {
234 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
239 error = kern_clock_gettime(td, uap->clock_id, &ats);
241 error = copyout(&ats, uap->tp, sizeof(ats));
247 cputick2timespec(uint64_t runtime, struct timespec *ats)
249 runtime = cputick2usec(runtime);
250 ats->tv_sec = runtime / 1000000;
251 ats->tv_nsec = runtime % 1000000 * 1000;
255 get_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 thread_lock(targettd);
268 runtime = targettd->td_runtime;
269 thread_unlock(targettd);
271 cputick2timespec(runtime, ats);
275 get_process_cputime(struct proc *targetp, struct timespec *ats)
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 get_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 get_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 get_thread_cputime(NULL, ats);
366 case CLOCK_PROCESS_CPUTIME_ID:
368 get_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 (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
415 if (!allow_insane_settime &&
416 (ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60 ||
417 ats->tv_sec < utc_offset()))
419 /* XXX Don't convert nsec->usec and back */
420 TIMESPEC_TO_TIMEVAL(&atv, ats);
421 error = settime(td, &atv);
425 #ifndef _SYS_SYSPROTO_H_
426 struct clock_getres_args {
432 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
440 error = kern_clock_getres(td, uap->clock_id, &ts);
442 error = copyout(&ts, uap->tp, sizeof(ts));
447 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
453 case CLOCK_REALTIME_FAST:
454 case CLOCK_REALTIME_PRECISE:
455 case CLOCK_MONOTONIC:
456 case CLOCK_MONOTONIC_FAST:
457 case CLOCK_MONOTONIC_PRECISE:
459 case CLOCK_UPTIME_FAST:
460 case CLOCK_UPTIME_PRECISE:
462 * Round up the result of the division cheaply by adding 1.
463 * Rounding up is especially important if rounding down
464 * would give 0. Perfect rounding is unimportant.
466 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
470 /* Accurately round up here because we can do so cheaply. */
471 ts->tv_nsec = howmany(1000000000, hz);
477 case CLOCK_THREAD_CPUTIME_ID:
478 case CLOCK_PROCESS_CPUTIME_ID:
480 /* sync with cputick2usec */
481 ts->tv_nsec = 1000000 / cpu_tickrate();
482 if (ts->tv_nsec == 0)
486 if ((int)clock_id < 0)
494 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
497 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
501 static uint8_t nanowait[MAXCPU];
504 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
505 const struct timespec *rqt, struct timespec *rmt)
507 struct timespec ts, now;
508 sbintime_t sbt, sbtt, prec, tmp;
513 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
515 if ((flags & ~TIMER_ABSTIME) != 0)
519 case CLOCK_REALTIME_PRECISE:
520 case CLOCK_REALTIME_FAST:
522 is_abs_real = (flags & TIMER_ABSTIME) != 0;
524 case CLOCK_MONOTONIC:
525 case CLOCK_MONOTONIC_PRECISE:
526 case CLOCK_MONOTONIC_FAST:
528 case CLOCK_UPTIME_PRECISE:
529 case CLOCK_UPTIME_FAST:
534 case CLOCK_PROCESS_CPUTIME_ID:
536 case CLOCK_THREAD_CPUTIME_ID:
542 if ((flags & TIMER_ABSTIME) != 0) {
545 atomic_load_acq_int(&rtc_generation);
546 error = kern_clock_gettime(td, clock_id, &now);
547 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
548 timespecsub(&ts, &now, &ts);
550 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
554 if (ts.tv_sec > INT32_MAX / 2) {
555 over = ts.tv_sec - INT32_MAX / 2;
562 if (TIMESEL(&sbt, tmp))
565 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
566 sbt, prec, C_ABSOLUTE);
567 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
569 if (error != EWOULDBLOCK) {
570 if (TIMESEL(&sbtt, tmp))
574 if (error == ERESTART)
576 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
577 ts = sbttots(sbt - sbtt);
588 #ifndef _SYS_SYSPROTO_H_
589 struct nanosleep_args {
590 struct timespec *rqtp;
591 struct timespec *rmtp;
596 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
599 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
600 uap->rqtp, uap->rmtp));
603 #ifndef _SYS_SYSPROTO_H_
604 struct clock_nanosleep_args {
607 struct timespec *rqtp;
608 struct timespec *rmtp;
613 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
617 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
619 return (kern_posix_error(td, error));
623 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
624 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
626 struct timespec rmt, rqt;
629 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
632 if (ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0 &&
633 !useracc(ua_rmtp, sizeof(rmt), VM_PROT_WRITE))
635 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
636 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
639 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
646 #ifndef _SYS_SYSPROTO_H_
647 struct gettimeofday_args {
649 struct timezone *tzp;
654 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
662 error = copyout(&atv, uap->tp, sizeof (atv));
664 if (error == 0 && uap->tzp != NULL) {
665 rtz.tz_minuteswest = 0;
667 error = copyout(&rtz, uap->tzp, sizeof (rtz));
672 #ifndef _SYS_SYSPROTO_H_
673 struct settimeofday_args {
675 struct timezone *tzp;
680 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
682 struct timeval atv, *tvp;
683 struct timezone atz, *tzp;
687 error = copyin(uap->tv, &atv, sizeof(atv));
694 error = copyin(uap->tzp, &atz, sizeof(atz));
700 return (kern_settimeofday(td, tvp, tzp));
704 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
708 error = priv_check(td, PRIV_SETTIMEOFDAY);
711 /* Verify all parameters before changing time. */
713 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
716 error = settime(td, tv);
722 * Get value of an interval timer. The process virtual and profiling virtual
723 * time timers are kept in the p_stats area, since they can be swapped out.
724 * These are kept internally in the way they are specified externally: in
725 * time until they expire.
727 * The real time interval timer is kept in the process table slot for the
728 * process, and its value (it_value) is kept as an absolute time rather than
729 * as a delta, so that it is easy to keep periodic real-time signals from
732 * Virtual time timers are processed in the hardclock() routine of
733 * kern_clock.c. The real time timer is processed by a timeout routine,
734 * called from the softclock() routine. Since a callout may be delayed in
735 * real time due to interrupt processing in the system, it is possible for
736 * the real time timeout routine (realitexpire, given below), to be delayed
737 * in real time past when it is supposed to occur. It does not suffice,
738 * therefore, to reload the real timer .it_value from the real time timers
739 * .it_interval. Rather, we compute the next time in absolute time the timer
742 #ifndef _SYS_SYSPROTO_H_
743 struct getitimer_args {
745 struct itimerval *itv;
749 sys_getitimer(struct thread *td, struct getitimer_args *uap)
751 struct itimerval aitv;
754 error = kern_getitimer(td, uap->which, &aitv);
757 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
761 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
763 struct proc *p = td->td_proc;
766 if (which > ITIMER_PROF)
769 if (which == ITIMER_REAL) {
771 * Convert from absolute to relative time in .it_value
772 * part of real time timer. If time for real time timer
773 * has passed return 0, else return difference between
774 * current time and time for the timer to go off.
777 *aitv = p->p_realtimer;
779 if (timevalisset(&aitv->it_value)) {
781 if (timevalcmp(&aitv->it_value, &ctv, <))
782 timevalclear(&aitv->it_value);
784 timevalsub(&aitv->it_value, &ctv);
788 *aitv = p->p_stats->p_timer[which];
792 if (KTRPOINT(td, KTR_STRUCT))
798 #ifndef _SYS_SYSPROTO_H_
799 struct setitimer_args {
801 struct itimerval *itv, *oitv;
805 sys_setitimer(struct thread *td, struct setitimer_args *uap)
807 struct itimerval aitv, oitv;
810 if (uap->itv == NULL) {
811 uap->itv = uap->oitv;
812 return (sys_getitimer(td, (struct getitimer_args *)uap));
815 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
817 error = kern_setitimer(td, uap->which, &aitv, &oitv);
818 if (error != 0 || uap->oitv == NULL)
820 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
824 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
825 struct itimerval *oitv)
827 struct proc *p = td->td_proc;
832 return (kern_getitimer(td, which, oitv));
834 if (which > ITIMER_PROF)
837 if (KTRPOINT(td, KTR_STRUCT))
840 if (itimerfix(&aitv->it_value) ||
841 aitv->it_value.tv_sec > INT32_MAX / 2)
843 if (!timevalisset(&aitv->it_value))
844 timevalclear(&aitv->it_interval);
845 else if (itimerfix(&aitv->it_interval) ||
846 aitv->it_interval.tv_sec > INT32_MAX / 2)
849 if (which == ITIMER_REAL) {
851 if (timevalisset(&p->p_realtimer.it_value))
852 callout_stop(&p->p_itcallout);
854 if (timevalisset(&aitv->it_value)) {
855 pr = tvtosbt(aitv->it_value) >> tc_precexp;
856 timevaladd(&aitv->it_value, &ctv);
857 sbt = tvtosbt(aitv->it_value);
858 callout_reset_sbt(&p->p_itcallout, sbt, pr,
859 realitexpire, p, C_ABSOLUTE);
861 *oitv = p->p_realtimer;
862 p->p_realtimer = *aitv;
864 if (timevalisset(&oitv->it_value)) {
865 if (timevalcmp(&oitv->it_value, &ctv, <))
866 timevalclear(&oitv->it_value);
868 timevalsub(&oitv->it_value, &ctv);
871 if (aitv->it_interval.tv_sec == 0 &&
872 aitv->it_interval.tv_usec != 0 &&
873 aitv->it_interval.tv_usec < tick)
874 aitv->it_interval.tv_usec = tick;
875 if (aitv->it_value.tv_sec == 0 &&
876 aitv->it_value.tv_usec != 0 &&
877 aitv->it_value.tv_usec < tick)
878 aitv->it_value.tv_usec = tick;
880 *oitv = p->p_stats->p_timer[which];
881 p->p_stats->p_timer[which] = *aitv;
885 if (KTRPOINT(td, KTR_STRUCT))
892 * Real interval timer expired:
893 * send process whose timer expired an alarm signal.
894 * If time is not set up to reload, then just return.
895 * Else compute next time timer should go off which is > current time.
896 * This is where delay in processing this timeout causes multiple
897 * SIGALRM calls to be compressed into one.
898 * tvtohz() always adds 1 to allow for the time until the next clock
899 * interrupt being strictly less than 1 clock tick, but we don't want
900 * that here since we want to appear to be in sync with the clock
901 * interrupt even when we're delayed.
904 realitexpire(void *arg)
910 p = (struct proc *)arg;
911 kern_psignal(p, SIGALRM);
912 if (!timevalisset(&p->p_realtimer.it_interval)) {
913 timevalclear(&p->p_realtimer.it_value);
914 if (p->p_flag & P_WEXIT)
915 wakeup(&p->p_itcallout);
918 isbt = tvtosbt(p->p_realtimer.it_interval);
919 if (isbt >= sbt_timethreshold)
920 getmicrouptime(&ctv);
924 timevaladd(&p->p_realtimer.it_value,
925 &p->p_realtimer.it_interval);
926 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
927 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
928 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
932 * Check that a proposed value to load into the .it_value or
933 * .it_interval part of an interval timer is acceptable, and
934 * fix it to have at least minimal value (i.e. if it is less
935 * than the resolution of the clock, round it up.)
938 itimerfix(struct timeval *tv)
941 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
943 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
944 tv->tv_usec < (u_int)tick / 16)
945 tv->tv_usec = (u_int)tick / 16;
950 * Decrement an interval timer by a specified number
951 * of microseconds, which must be less than a second,
952 * i.e. < 1000000. If the timer expires, then reload
953 * it. In this case, carry over (usec - old value) to
954 * reduce the value reloaded into the timer so that
955 * the timer does not drift. This routine assumes
956 * that it is called in a context where the timers
957 * on which it is operating cannot change in value.
960 itimerdecr(struct itimerval *itp, int usec)
963 if (itp->it_value.tv_usec < usec) {
964 if (itp->it_value.tv_sec == 0) {
965 /* expired, and already in next interval */
966 usec -= itp->it_value.tv_usec;
969 itp->it_value.tv_usec += 1000000;
970 itp->it_value.tv_sec--;
972 itp->it_value.tv_usec -= usec;
974 if (timevalisset(&itp->it_value))
976 /* expired, exactly at end of interval */
978 if (timevalisset(&itp->it_interval)) {
979 itp->it_value = itp->it_interval;
980 itp->it_value.tv_usec -= usec;
981 if (itp->it_value.tv_usec < 0) {
982 itp->it_value.tv_usec += 1000000;
983 itp->it_value.tv_sec--;
986 itp->it_value.tv_usec = 0; /* sec is already 0 */
991 * Add and subtract routines for timevals.
992 * N.B.: subtract routine doesn't deal with
993 * results which are before the beginning,
994 * it just gets very confused in this case.
998 timevaladd(struct timeval *t1, const struct timeval *t2)
1001 t1->tv_sec += t2->tv_sec;
1002 t1->tv_usec += t2->tv_usec;
1007 timevalsub(struct timeval *t1, const struct timeval *t2)
1010 t1->tv_sec -= t2->tv_sec;
1011 t1->tv_usec -= t2->tv_usec;
1016 timevalfix(struct timeval *t1)
1019 if (t1->tv_usec < 0) {
1021 t1->tv_usec += 1000000;
1023 if (t1->tv_usec >= 1000000) {
1025 t1->tv_usec -= 1000000;
1030 * ratecheck(): simple time-based rate-limit checking.
1033 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1035 struct timeval tv, delta;
1038 getmicrouptime(&tv); /* NB: 10ms precision */
1040 timevalsub(&delta, lasttime);
1043 * check for 0,0 is so that the message will be seen at least once,
1044 * even if interval is huge.
1046 if (timevalcmp(&delta, mininterval, >=) ||
1047 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1056 * ppsratecheck(): packets (or events) per second limitation.
1058 * Return 0 if the limit is to be enforced (e.g. the caller
1059 * should drop a packet because of the rate limitation).
1061 * maxpps of 0 always causes zero to be returned. maxpps of -1
1062 * always causes 1 to be returned; this effectively defeats rate
1065 * Note that we maintain the struct timeval for compatibility
1066 * with other bsd systems. We reuse the storage and just monitor
1067 * clock ticks for minimal overhead.
1070 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1075 * Reset the last time and counter if this is the first call
1076 * or more than a second has passed since the last update of
1080 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1081 lasttime->tv_sec = now;
1083 return (maxpps != 0);
1085 (*curpps)++; /* NB: ignore potential overflow */
1086 return (maxpps < 0 || *curpps <= maxpps);
1093 struct kclock rt_clock = {
1094 .timer_create = realtimer_create,
1095 .timer_delete = realtimer_delete,
1096 .timer_settime = realtimer_settime,
1097 .timer_gettime = realtimer_gettime,
1101 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1102 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1103 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1104 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1105 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1106 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1107 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1108 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1109 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1110 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1111 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1115 register_posix_clock(int clockid, struct kclock *clk)
1117 if ((unsigned)clockid >= MAX_CLOCKS) {
1118 printf("%s: invalid clockid\n", __func__);
1121 posix_clocks[clockid] = *clk;
1126 itimer_init(void *mem, int size, int flags)
1130 it = (struct itimer *)mem;
1131 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1136 itimer_fini(void *mem, int size)
1140 it = (struct itimer *)mem;
1141 mtx_destroy(&it->it_mtx);
1145 itimer_enter(struct itimer *it)
1148 mtx_assert(&it->it_mtx, MA_OWNED);
1153 itimer_leave(struct itimer *it)
1156 mtx_assert(&it->it_mtx, MA_OWNED);
1157 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1159 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1163 #ifndef _SYS_SYSPROTO_H_
1164 struct ktimer_create_args {
1166 struct sigevent * evp;
1171 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1173 struct sigevent *evp, ev;
1177 if (uap->evp == NULL) {
1180 error = copyin(uap->evp, &ev, sizeof(ev));
1185 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1187 error = copyout(&id, uap->timerid, sizeof(int));
1189 kern_ktimer_delete(td, id);
1195 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1196 int *timerid, int preset_id)
1198 struct proc *p = td->td_proc;
1203 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1206 if (posix_clocks[clock_id].timer_create == NULL)
1210 if (evp->sigev_notify != SIGEV_NONE &&
1211 evp->sigev_notify != SIGEV_SIGNAL &&
1212 evp->sigev_notify != SIGEV_THREAD_ID)
1214 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1215 evp->sigev_notify == SIGEV_THREAD_ID) &&
1216 !_SIG_VALID(evp->sigev_signo))
1220 if (p->p_itimers == NULL)
1223 it = uma_zalloc(itimer_zone, M_WAITOK);
1225 it->it_usecount = 0;
1227 timespecclear(&it->it_time.it_value);
1228 timespecclear(&it->it_time.it_interval);
1230 it->it_overrun_last = 0;
1231 it->it_clockid = clock_id;
1232 it->it_timerid = -1;
1234 ksiginfo_init(&it->it_ksi);
1235 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1236 error = CLOCK_CALL(clock_id, timer_create, (it));
1241 if (preset_id != -1) {
1242 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1244 if (p->p_itimers->its_timers[id] != NULL) {
1251 * Find a free timer slot, skipping those reserved
1254 for (id = 3; id < TIMER_MAX; id++)
1255 if (p->p_itimers->its_timers[id] == NULL)
1257 if (id == TIMER_MAX) {
1263 it->it_timerid = id;
1264 p->p_itimers->its_timers[id] = it;
1266 it->it_sigev = *evp;
1268 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1271 case CLOCK_REALTIME:
1272 it->it_sigev.sigev_signo = SIGALRM;
1275 it->it_sigev.sigev_signo = SIGVTALRM;
1278 it->it_sigev.sigev_signo = SIGPROF;
1281 it->it_sigev.sigev_value.sival_int = id;
1284 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1285 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1286 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1287 it->it_ksi.ksi_code = SI_TIMER;
1288 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1289 it->it_ksi.ksi_timerid = id;
1297 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1299 uma_zfree(itimer_zone, it);
1303 #ifndef _SYS_SYSPROTO_H_
1304 struct ktimer_delete_args {
1309 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1312 return (kern_ktimer_delete(td, uap->timerid));
1315 static struct itimer *
1316 itimer_find(struct proc *p, int timerid)
1320 PROC_LOCK_ASSERT(p, MA_OWNED);
1321 if ((p->p_itimers == NULL) ||
1322 (timerid < 0) || (timerid >= TIMER_MAX) ||
1323 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1327 if ((it->it_flags & ITF_DELETING) != 0) {
1335 kern_ktimer_delete(struct thread *td, int timerid)
1337 struct proc *p = td->td_proc;
1341 it = itimer_find(p, timerid);
1348 it->it_flags |= ITF_DELETING;
1349 while (it->it_usecount > 0) {
1350 it->it_flags |= ITF_WANTED;
1351 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1353 it->it_flags &= ~ITF_WANTED;
1354 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1358 if (KSI_ONQ(&it->it_ksi))
1359 sigqueue_take(&it->it_ksi);
1360 p->p_itimers->its_timers[timerid] = NULL;
1362 uma_zfree(itimer_zone, it);
1366 #ifndef _SYS_SYSPROTO_H_
1367 struct ktimer_settime_args {
1370 const struct itimerspec * value;
1371 struct itimerspec * ovalue;
1375 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1377 struct itimerspec val, oval, *ovalp;
1380 error = copyin(uap->value, &val, sizeof(val));
1383 ovalp = uap->ovalue != NULL ? &oval : NULL;
1384 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1385 if (error == 0 && uap->ovalue != NULL)
1386 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1391 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1392 struct itimerspec *val, struct itimerspec *oval)
1400 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1406 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1414 #ifndef _SYS_SYSPROTO_H_
1415 struct ktimer_gettime_args {
1417 struct itimerspec * value;
1421 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1423 struct itimerspec val;
1426 error = kern_ktimer_gettime(td, uap->timerid, &val);
1428 error = copyout(&val, uap->value, sizeof(val));
1433 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1441 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1447 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1454 #ifndef _SYS_SYSPROTO_H_
1455 struct timer_getoverrun_args {
1460 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1463 return (kern_ktimer_getoverrun(td, uap->timerid));
1467 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1469 struct proc *p = td->td_proc;
1475 (it = itimer_find(p, timer_id)) == NULL) {
1479 td->td_retval[0] = it->it_overrun_last;
1488 realtimer_create(struct itimer *it)
1490 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1495 realtimer_delete(struct itimer *it)
1497 mtx_assert(&it->it_mtx, MA_OWNED);
1500 * clear timer's value and interval to tell realtimer_expire
1501 * to not rearm the timer.
1503 timespecclear(&it->it_time.it_value);
1504 timespecclear(&it->it_time.it_interval);
1506 callout_drain(&it->it_callout);
1512 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1514 struct timespec cts;
1516 mtx_assert(&it->it_mtx, MA_OWNED);
1518 realtimer_clocktime(it->it_clockid, &cts);
1519 *ovalue = it->it_time;
1520 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1521 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1522 if (ovalue->it_value.tv_sec < 0 ||
1523 (ovalue->it_value.tv_sec == 0 &&
1524 ovalue->it_value.tv_nsec == 0)) {
1525 ovalue->it_value.tv_sec = 0;
1526 ovalue->it_value.tv_nsec = 1;
1533 realtimer_settime(struct itimer *it, int flags,
1534 struct itimerspec *value, struct itimerspec *ovalue)
1536 struct timespec cts, ts;
1538 struct itimerspec val;
1540 mtx_assert(&it->it_mtx, MA_OWNED);
1543 if (itimespecfix(&val.it_value))
1546 if (timespecisset(&val.it_value)) {
1547 if (itimespecfix(&val.it_interval))
1550 timespecclear(&val.it_interval);
1554 realtimer_gettime(it, ovalue);
1557 if (timespecisset(&val.it_value)) {
1558 realtimer_clocktime(it->it_clockid, &cts);
1560 if ((flags & TIMER_ABSTIME) == 0) {
1561 /* Convert to absolute time. */
1562 timespecadd(&it->it_time.it_value, &cts,
1563 &it->it_time.it_value);
1565 timespecsub(&ts, &cts, &ts);
1567 * We don't care if ts is negative, tztohz will
1571 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1572 callout_reset(&it->it_callout, tvtohz(&tv),
1573 realtimer_expire, it);
1575 callout_stop(&it->it_callout);
1582 realtimer_clocktime(clockid_t id, struct timespec *ts)
1584 if (id == CLOCK_REALTIME)
1586 else /* CLOCK_MONOTONIC */
1591 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1595 PROC_LOCK_ASSERT(p, MA_OWNED);
1596 it = itimer_find(p, timerid);
1598 ksi->ksi_overrun = it->it_overrun;
1599 it->it_overrun_last = it->it_overrun;
1608 itimespecfix(struct timespec *ts)
1611 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1613 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1614 ts->tv_nsec = tick * 1000;
1618 /* Timeout callback for realtime timer */
1620 realtimer_expire(void *arg)
1622 struct timespec cts, ts;
1626 it = (struct itimer *)arg;
1628 realtimer_clocktime(it->it_clockid, &cts);
1629 /* Only fire if time is reached. */
1630 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1631 if (timespecisset(&it->it_time.it_interval)) {
1632 timespecadd(&it->it_time.it_value,
1633 &it->it_time.it_interval,
1634 &it->it_time.it_value);
1635 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1636 if (it->it_overrun < INT_MAX)
1639 it->it_ksi.ksi_errno = ERANGE;
1640 timespecadd(&it->it_time.it_value,
1641 &it->it_time.it_interval,
1642 &it->it_time.it_value);
1645 /* single shot timer ? */
1646 timespecclear(&it->it_time.it_value);
1648 if (timespecisset(&it->it_time.it_value)) {
1649 timespecsub(&it->it_time.it_value, &cts, &ts);
1650 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1651 callout_reset(&it->it_callout, tvtohz(&tv),
1652 realtimer_expire, it);
1659 } else if (timespecisset(&it->it_time.it_value)) {
1660 ts = it->it_time.it_value;
1661 timespecsub(&ts, &cts, &ts);
1662 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1663 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1669 itimer_fire(struct itimer *it)
1671 struct proc *p = it->it_proc;
1674 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1675 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1676 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1678 timespecclear(&it->it_time.it_value);
1679 timespecclear(&it->it_time.it_interval);
1680 callout_stop(&it->it_callout);
1684 if (!KSI_ONQ(&it->it_ksi)) {
1685 it->it_ksi.ksi_errno = 0;
1686 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1687 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1689 if (it->it_overrun < INT_MAX)
1692 it->it_ksi.ksi_errno = ERANGE;
1699 itimers_alloc(struct proc *p)
1701 struct itimers *its;
1704 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1705 LIST_INIT(&its->its_virtual);
1706 LIST_INIT(&its->its_prof);
1707 TAILQ_INIT(&its->its_worklist);
1708 for (i = 0; i < TIMER_MAX; i++)
1709 its->its_timers[i] = NULL;
1711 if (p->p_itimers == NULL) {
1717 free(its, M_SUBPROC);
1722 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1724 itimers_event_hook_exit(arg, p);
1727 /* Clean up timers when some process events are being triggered. */
1729 itimers_event_hook_exit(void *arg, struct proc *p)
1731 struct itimers *its;
1733 int event = (int)(intptr_t)arg;
1736 if (p->p_itimers != NULL) {
1738 for (i = 0; i < MAX_CLOCKS; ++i) {
1739 if (posix_clocks[i].event_hook != NULL)
1740 CLOCK_CALL(i, event_hook, (p, i, event));
1743 * According to susv3, XSI interval timers should be inherited
1746 if (event == ITIMER_EV_EXEC)
1748 else if (event == ITIMER_EV_EXIT)
1751 panic("unhandled event");
1752 for (; i < TIMER_MAX; ++i) {
1753 if ((it = its->its_timers[i]) != NULL)
1754 kern_ktimer_delete(curthread, i);
1756 if (its->its_timers[0] == NULL &&
1757 its->its_timers[1] == NULL &&
1758 its->its_timers[2] == NULL) {
1759 free(its, M_SUBPROC);
1760 p->p_itimers = NULL;