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 && ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60)
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 = 1000000000 / tc_getfrequency() + 1;
468 /* Accurately round up here because we can do so cheaply. */
469 ts->tv_nsec = howmany(1000000000, hz);
475 case CLOCK_THREAD_CPUTIME_ID:
476 case CLOCK_PROCESS_CPUTIME_ID:
478 /* sync with cputick2usec */
479 ts->tv_nsec = 1000000 / cpu_tickrate();
480 if (ts->tv_nsec == 0)
484 if ((int)clock_id < 0)
492 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
495 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
499 static uint8_t nanowait[MAXCPU];
502 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
503 const struct timespec *rqt, struct timespec *rmt)
505 struct timespec ts, now;
506 sbintime_t sbt, sbtt, prec, tmp;
511 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
513 if ((flags & ~TIMER_ABSTIME) != 0)
517 case CLOCK_REALTIME_PRECISE:
518 case CLOCK_REALTIME_FAST:
520 is_abs_real = (flags & TIMER_ABSTIME) != 0;
522 case CLOCK_MONOTONIC:
523 case CLOCK_MONOTONIC_PRECISE:
524 case CLOCK_MONOTONIC_FAST:
526 case CLOCK_UPTIME_PRECISE:
527 case CLOCK_UPTIME_FAST:
532 case CLOCK_PROCESS_CPUTIME_ID:
534 case CLOCK_THREAD_CPUTIME_ID:
540 if ((flags & TIMER_ABSTIME) != 0) {
543 atomic_load_acq_int(&rtc_generation);
544 error = kern_clock_gettime(td, clock_id, &now);
545 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
546 timespecsub(&ts, &now, &ts);
548 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
552 if (ts.tv_sec > INT32_MAX / 2) {
553 over = ts.tv_sec - INT32_MAX / 2;
560 if (TIMESEL(&sbt, tmp))
563 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
564 sbt, prec, C_ABSOLUTE);
565 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
567 if (error != EWOULDBLOCK) {
568 if (TIMESEL(&sbtt, tmp))
572 if (error == ERESTART)
574 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
575 ts = sbttots(sbt - sbtt);
586 #ifndef _SYS_SYSPROTO_H_
587 struct nanosleep_args {
588 struct timespec *rqtp;
589 struct timespec *rmtp;
594 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
597 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
598 uap->rqtp, uap->rmtp));
601 #ifndef _SYS_SYSPROTO_H_
602 struct clock_nanosleep_args {
605 struct timespec *rqtp;
606 struct timespec *rmtp;
611 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
615 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
617 return (kern_posix_error(td, error));
621 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
622 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
624 struct timespec rmt, rqt;
627 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
630 if (ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0 &&
631 !useracc(ua_rmtp, sizeof(rmt), VM_PROT_WRITE))
633 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
634 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
637 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
644 #ifndef _SYS_SYSPROTO_H_
645 struct gettimeofday_args {
647 struct timezone *tzp;
652 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
660 error = copyout(&atv, uap->tp, sizeof (atv));
662 if (error == 0 && uap->tzp != NULL) {
663 rtz.tz_minuteswest = 0;
665 error = copyout(&rtz, uap->tzp, sizeof (rtz));
670 #ifndef _SYS_SYSPROTO_H_
671 struct settimeofday_args {
673 struct timezone *tzp;
678 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
680 struct timeval atv, *tvp;
681 struct timezone atz, *tzp;
685 error = copyin(uap->tv, &atv, sizeof(atv));
692 error = copyin(uap->tzp, &atz, sizeof(atz));
698 return (kern_settimeofday(td, tvp, tzp));
702 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
706 error = priv_check(td, PRIV_SETTIMEOFDAY);
709 /* Verify all parameters before changing time. */
711 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
714 error = settime(td, tv);
720 * Get value of an interval timer. The process virtual and profiling virtual
721 * time timers are kept in the p_stats area, since they can be swapped out.
722 * These are kept internally in the way they are specified externally: in
723 * time until they expire.
725 * The real time interval timer is kept in the process table slot for the
726 * process, and its value (it_value) is kept as an absolute time rather than
727 * as a delta, so that it is easy to keep periodic real-time signals from
730 * Virtual time timers are processed in the hardclock() routine of
731 * kern_clock.c. The real time timer is processed by a timeout routine,
732 * called from the softclock() routine. Since a callout may be delayed in
733 * real time due to interrupt processing in the system, it is possible for
734 * the real time timeout routine (realitexpire, given below), to be delayed
735 * in real time past when it is supposed to occur. It does not suffice,
736 * therefore, to reload the real timer .it_value from the real time timers
737 * .it_interval. Rather, we compute the next time in absolute time the timer
740 #ifndef _SYS_SYSPROTO_H_
741 struct getitimer_args {
743 struct itimerval *itv;
747 sys_getitimer(struct thread *td, struct getitimer_args *uap)
749 struct itimerval aitv;
752 error = kern_getitimer(td, uap->which, &aitv);
755 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
759 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
761 struct proc *p = td->td_proc;
764 if (which > ITIMER_PROF)
767 if (which == ITIMER_REAL) {
769 * Convert from absolute to relative time in .it_value
770 * part of real time timer. If time for real time timer
771 * has passed return 0, else return difference between
772 * current time and time for the timer to go off.
775 *aitv = p->p_realtimer;
777 if (timevalisset(&aitv->it_value)) {
779 if (timevalcmp(&aitv->it_value, &ctv, <))
780 timevalclear(&aitv->it_value);
782 timevalsub(&aitv->it_value, &ctv);
786 *aitv = p->p_stats->p_timer[which];
790 if (KTRPOINT(td, KTR_STRUCT))
796 #ifndef _SYS_SYSPROTO_H_
797 struct setitimer_args {
799 struct itimerval *itv, *oitv;
803 sys_setitimer(struct thread *td, struct setitimer_args *uap)
805 struct itimerval aitv, oitv;
808 if (uap->itv == NULL) {
809 uap->itv = uap->oitv;
810 return (sys_getitimer(td, (struct getitimer_args *)uap));
813 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
815 error = kern_setitimer(td, uap->which, &aitv, &oitv);
816 if (error != 0 || uap->oitv == NULL)
818 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
822 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
823 struct itimerval *oitv)
825 struct proc *p = td->td_proc;
830 return (kern_getitimer(td, which, oitv));
832 if (which > ITIMER_PROF)
835 if (KTRPOINT(td, KTR_STRUCT))
838 if (itimerfix(&aitv->it_value) ||
839 aitv->it_value.tv_sec > INT32_MAX / 2)
841 if (!timevalisset(&aitv->it_value))
842 timevalclear(&aitv->it_interval);
843 else if (itimerfix(&aitv->it_interval) ||
844 aitv->it_interval.tv_sec > INT32_MAX / 2)
847 if (which == ITIMER_REAL) {
849 if (timevalisset(&p->p_realtimer.it_value))
850 callout_stop(&p->p_itcallout);
852 if (timevalisset(&aitv->it_value)) {
853 pr = tvtosbt(aitv->it_value) >> tc_precexp;
854 timevaladd(&aitv->it_value, &ctv);
855 sbt = tvtosbt(aitv->it_value);
856 callout_reset_sbt(&p->p_itcallout, sbt, pr,
857 realitexpire, p, C_ABSOLUTE);
859 *oitv = p->p_realtimer;
860 p->p_realtimer = *aitv;
862 if (timevalisset(&oitv->it_value)) {
863 if (timevalcmp(&oitv->it_value, &ctv, <))
864 timevalclear(&oitv->it_value);
866 timevalsub(&oitv->it_value, &ctv);
869 if (aitv->it_interval.tv_sec == 0 &&
870 aitv->it_interval.tv_usec != 0 &&
871 aitv->it_interval.tv_usec < tick)
872 aitv->it_interval.tv_usec = tick;
873 if (aitv->it_value.tv_sec == 0 &&
874 aitv->it_value.tv_usec != 0 &&
875 aitv->it_value.tv_usec < tick)
876 aitv->it_value.tv_usec = tick;
878 *oitv = p->p_stats->p_timer[which];
879 p->p_stats->p_timer[which] = *aitv;
883 if (KTRPOINT(td, KTR_STRUCT))
890 * Real interval timer expired:
891 * send process whose timer expired an alarm signal.
892 * If time is not set up to reload, then just return.
893 * Else compute next time timer should go off which is > current time.
894 * This is where delay in processing this timeout causes multiple
895 * SIGALRM calls to be compressed into one.
896 * tvtohz() always adds 1 to allow for the time until the next clock
897 * interrupt being strictly less than 1 clock tick, but we don't want
898 * that here since we want to appear to be in sync with the clock
899 * interrupt even when we're delayed.
902 realitexpire(void *arg)
908 p = (struct proc *)arg;
909 kern_psignal(p, SIGALRM);
910 if (!timevalisset(&p->p_realtimer.it_interval)) {
911 timevalclear(&p->p_realtimer.it_value);
912 if (p->p_flag & P_WEXIT)
913 wakeup(&p->p_itcallout);
916 isbt = tvtosbt(p->p_realtimer.it_interval);
917 if (isbt >= sbt_timethreshold)
918 getmicrouptime(&ctv);
922 timevaladd(&p->p_realtimer.it_value,
923 &p->p_realtimer.it_interval);
924 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
925 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
926 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
930 * Check that a proposed value to load into the .it_value or
931 * .it_interval part of an interval timer is acceptable, and
932 * fix it to have at least minimal value (i.e. if it is less
933 * than the resolution of the clock, round it up.)
936 itimerfix(struct timeval *tv)
939 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
941 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
942 tv->tv_usec < (u_int)tick / 16)
943 tv->tv_usec = (u_int)tick / 16;
948 * Decrement an interval timer by a specified number
949 * of microseconds, which must be less than a second,
950 * i.e. < 1000000. If the timer expires, then reload
951 * it. In this case, carry over (usec - old value) to
952 * reduce the value reloaded into the timer so that
953 * the timer does not drift. This routine assumes
954 * that it is called in a context where the timers
955 * on which it is operating cannot change in value.
958 itimerdecr(struct itimerval *itp, int usec)
961 if (itp->it_value.tv_usec < usec) {
962 if (itp->it_value.tv_sec == 0) {
963 /* expired, and already in next interval */
964 usec -= itp->it_value.tv_usec;
967 itp->it_value.tv_usec += 1000000;
968 itp->it_value.tv_sec--;
970 itp->it_value.tv_usec -= usec;
972 if (timevalisset(&itp->it_value))
974 /* expired, exactly at end of interval */
976 if (timevalisset(&itp->it_interval)) {
977 itp->it_value = itp->it_interval;
978 itp->it_value.tv_usec -= usec;
979 if (itp->it_value.tv_usec < 0) {
980 itp->it_value.tv_usec += 1000000;
981 itp->it_value.tv_sec--;
984 itp->it_value.tv_usec = 0; /* sec is already 0 */
989 * Add and subtract routines for timevals.
990 * N.B.: subtract routine doesn't deal with
991 * results which are before the beginning,
992 * it just gets very confused in this case.
996 timevaladd(struct timeval *t1, const struct timeval *t2)
999 t1->tv_sec += t2->tv_sec;
1000 t1->tv_usec += t2->tv_usec;
1005 timevalsub(struct timeval *t1, const struct timeval *t2)
1008 t1->tv_sec -= t2->tv_sec;
1009 t1->tv_usec -= t2->tv_usec;
1014 timevalfix(struct timeval *t1)
1017 if (t1->tv_usec < 0) {
1019 t1->tv_usec += 1000000;
1021 if (t1->tv_usec >= 1000000) {
1023 t1->tv_usec -= 1000000;
1028 * ratecheck(): simple time-based rate-limit checking.
1031 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1033 struct timeval tv, delta;
1036 getmicrouptime(&tv); /* NB: 10ms precision */
1038 timevalsub(&delta, lasttime);
1041 * check for 0,0 is so that the message will be seen at least once,
1042 * even if interval is huge.
1044 if (timevalcmp(&delta, mininterval, >=) ||
1045 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1054 * ppsratecheck(): packets (or events) per second limitation.
1056 * Return 0 if the limit is to be enforced (e.g. the caller
1057 * should drop a packet because of the rate limitation).
1059 * maxpps of 0 always causes zero to be returned. maxpps of -1
1060 * always causes 1 to be returned; this effectively defeats rate
1063 * Note that we maintain the struct timeval for compatibility
1064 * with other bsd systems. We reuse the storage and just monitor
1065 * clock ticks for minimal overhead.
1068 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1073 * Reset the last time and counter if this is the first call
1074 * or more than a second has passed since the last update of
1078 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1079 lasttime->tv_sec = now;
1081 return (maxpps != 0);
1083 (*curpps)++; /* NB: ignore potential overflow */
1084 return (maxpps < 0 || *curpps <= maxpps);
1091 struct kclock rt_clock = {
1092 .timer_create = realtimer_create,
1093 .timer_delete = realtimer_delete,
1094 .timer_settime = realtimer_settime,
1095 .timer_gettime = realtimer_gettime,
1099 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1100 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1101 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1102 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1103 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1104 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1105 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1106 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1107 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1108 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1109 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1113 register_posix_clock(int clockid, struct kclock *clk)
1115 if ((unsigned)clockid >= MAX_CLOCKS) {
1116 printf("%s: invalid clockid\n", __func__);
1119 posix_clocks[clockid] = *clk;
1124 itimer_init(void *mem, int size, int flags)
1128 it = (struct itimer *)mem;
1129 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1134 itimer_fini(void *mem, int size)
1138 it = (struct itimer *)mem;
1139 mtx_destroy(&it->it_mtx);
1143 itimer_enter(struct itimer *it)
1146 mtx_assert(&it->it_mtx, MA_OWNED);
1151 itimer_leave(struct itimer *it)
1154 mtx_assert(&it->it_mtx, MA_OWNED);
1155 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1157 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1161 #ifndef _SYS_SYSPROTO_H_
1162 struct ktimer_create_args {
1164 struct sigevent * evp;
1169 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1171 struct sigevent *evp, ev;
1175 if (uap->evp == NULL) {
1178 error = copyin(uap->evp, &ev, sizeof(ev));
1183 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1185 error = copyout(&id, uap->timerid, sizeof(int));
1187 kern_ktimer_delete(td, id);
1193 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1194 int *timerid, int preset_id)
1196 struct proc *p = td->td_proc;
1201 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1204 if (posix_clocks[clock_id].timer_create == NULL)
1208 if (evp->sigev_notify != SIGEV_NONE &&
1209 evp->sigev_notify != SIGEV_SIGNAL &&
1210 evp->sigev_notify != SIGEV_THREAD_ID)
1212 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1213 evp->sigev_notify == SIGEV_THREAD_ID) &&
1214 !_SIG_VALID(evp->sigev_signo))
1218 if (p->p_itimers == NULL)
1221 it = uma_zalloc(itimer_zone, M_WAITOK);
1223 it->it_usecount = 0;
1225 timespecclear(&it->it_time.it_value);
1226 timespecclear(&it->it_time.it_interval);
1228 it->it_overrun_last = 0;
1229 it->it_clockid = clock_id;
1230 it->it_timerid = -1;
1232 ksiginfo_init(&it->it_ksi);
1233 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1234 error = CLOCK_CALL(clock_id, timer_create, (it));
1239 if (preset_id != -1) {
1240 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1242 if (p->p_itimers->its_timers[id] != NULL) {
1249 * Find a free timer slot, skipping those reserved
1252 for (id = 3; id < TIMER_MAX; id++)
1253 if (p->p_itimers->its_timers[id] == NULL)
1255 if (id == TIMER_MAX) {
1261 it->it_timerid = id;
1262 p->p_itimers->its_timers[id] = it;
1264 it->it_sigev = *evp;
1266 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1269 case CLOCK_REALTIME:
1270 it->it_sigev.sigev_signo = SIGALRM;
1273 it->it_sigev.sigev_signo = SIGVTALRM;
1276 it->it_sigev.sigev_signo = SIGPROF;
1279 it->it_sigev.sigev_value.sival_int = id;
1282 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1283 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1284 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1285 it->it_ksi.ksi_code = SI_TIMER;
1286 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1287 it->it_ksi.ksi_timerid = id;
1295 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1297 uma_zfree(itimer_zone, it);
1301 #ifndef _SYS_SYSPROTO_H_
1302 struct ktimer_delete_args {
1307 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1310 return (kern_ktimer_delete(td, uap->timerid));
1313 static struct itimer *
1314 itimer_find(struct proc *p, int timerid)
1318 PROC_LOCK_ASSERT(p, MA_OWNED);
1319 if ((p->p_itimers == NULL) ||
1320 (timerid < 0) || (timerid >= TIMER_MAX) ||
1321 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1325 if ((it->it_flags & ITF_DELETING) != 0) {
1333 kern_ktimer_delete(struct thread *td, int timerid)
1335 struct proc *p = td->td_proc;
1339 it = itimer_find(p, timerid);
1346 it->it_flags |= ITF_DELETING;
1347 while (it->it_usecount > 0) {
1348 it->it_flags |= ITF_WANTED;
1349 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1351 it->it_flags &= ~ITF_WANTED;
1352 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1356 if (KSI_ONQ(&it->it_ksi))
1357 sigqueue_take(&it->it_ksi);
1358 p->p_itimers->its_timers[timerid] = NULL;
1360 uma_zfree(itimer_zone, it);
1364 #ifndef _SYS_SYSPROTO_H_
1365 struct ktimer_settime_args {
1368 const struct itimerspec * value;
1369 struct itimerspec * ovalue;
1373 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1375 struct itimerspec val, oval, *ovalp;
1378 error = copyin(uap->value, &val, sizeof(val));
1381 ovalp = uap->ovalue != NULL ? &oval : NULL;
1382 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1383 if (error == 0 && uap->ovalue != NULL)
1384 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1389 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1390 struct itimerspec *val, struct itimerspec *oval)
1398 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1404 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1412 #ifndef _SYS_SYSPROTO_H_
1413 struct ktimer_gettime_args {
1415 struct itimerspec * value;
1419 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1421 struct itimerspec val;
1424 error = kern_ktimer_gettime(td, uap->timerid, &val);
1426 error = copyout(&val, uap->value, sizeof(val));
1431 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1439 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1445 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1452 #ifndef _SYS_SYSPROTO_H_
1453 struct timer_getoverrun_args {
1458 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1461 return (kern_ktimer_getoverrun(td, uap->timerid));
1465 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1467 struct proc *p = td->td_proc;
1473 (it = itimer_find(p, timer_id)) == NULL) {
1477 td->td_retval[0] = it->it_overrun_last;
1486 realtimer_create(struct itimer *it)
1488 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1493 realtimer_delete(struct itimer *it)
1495 mtx_assert(&it->it_mtx, MA_OWNED);
1498 * clear timer's value and interval to tell realtimer_expire
1499 * to not rearm the timer.
1501 timespecclear(&it->it_time.it_value);
1502 timespecclear(&it->it_time.it_interval);
1504 callout_drain(&it->it_callout);
1510 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1512 struct timespec cts;
1514 mtx_assert(&it->it_mtx, MA_OWNED);
1516 realtimer_clocktime(it->it_clockid, &cts);
1517 *ovalue = it->it_time;
1518 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1519 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1520 if (ovalue->it_value.tv_sec < 0 ||
1521 (ovalue->it_value.tv_sec == 0 &&
1522 ovalue->it_value.tv_nsec == 0)) {
1523 ovalue->it_value.tv_sec = 0;
1524 ovalue->it_value.tv_nsec = 1;
1531 realtimer_settime(struct itimer *it, int flags,
1532 struct itimerspec *value, struct itimerspec *ovalue)
1534 struct timespec cts, ts;
1536 struct itimerspec val;
1538 mtx_assert(&it->it_mtx, MA_OWNED);
1541 if (itimespecfix(&val.it_value))
1544 if (timespecisset(&val.it_value)) {
1545 if (itimespecfix(&val.it_interval))
1548 timespecclear(&val.it_interval);
1552 realtimer_gettime(it, ovalue);
1555 if (timespecisset(&val.it_value)) {
1556 realtimer_clocktime(it->it_clockid, &cts);
1558 if ((flags & TIMER_ABSTIME) == 0) {
1559 /* Convert to absolute time. */
1560 timespecadd(&it->it_time.it_value, &cts,
1561 &it->it_time.it_value);
1563 timespecsub(&ts, &cts, &ts);
1565 * We don't care if ts is negative, tztohz will
1569 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1570 callout_reset(&it->it_callout, tvtohz(&tv),
1571 realtimer_expire, it);
1573 callout_stop(&it->it_callout);
1580 realtimer_clocktime(clockid_t id, struct timespec *ts)
1582 if (id == CLOCK_REALTIME)
1584 else /* CLOCK_MONOTONIC */
1589 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1593 PROC_LOCK_ASSERT(p, MA_OWNED);
1594 it = itimer_find(p, timerid);
1596 ksi->ksi_overrun = it->it_overrun;
1597 it->it_overrun_last = it->it_overrun;
1606 itimespecfix(struct timespec *ts)
1609 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1611 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1612 ts->tv_nsec = tick * 1000;
1616 /* Timeout callback for realtime timer */
1618 realtimer_expire(void *arg)
1620 struct timespec cts, ts;
1624 it = (struct itimer *)arg;
1626 realtimer_clocktime(it->it_clockid, &cts);
1627 /* Only fire if time is reached. */
1628 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1629 if (timespecisset(&it->it_time.it_interval)) {
1630 timespecadd(&it->it_time.it_value,
1631 &it->it_time.it_interval,
1632 &it->it_time.it_value);
1633 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1634 if (it->it_overrun < INT_MAX)
1637 it->it_ksi.ksi_errno = ERANGE;
1638 timespecadd(&it->it_time.it_value,
1639 &it->it_time.it_interval,
1640 &it->it_time.it_value);
1643 /* single shot timer ? */
1644 timespecclear(&it->it_time.it_value);
1646 if (timespecisset(&it->it_time.it_value)) {
1647 timespecsub(&it->it_time.it_value, &cts, &ts);
1648 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1649 callout_reset(&it->it_callout, tvtohz(&tv),
1650 realtimer_expire, it);
1657 } else if (timespecisset(&it->it_time.it_value)) {
1658 ts = it->it_time.it_value;
1659 timespecsub(&ts, &cts, &ts);
1660 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1661 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1667 itimer_fire(struct itimer *it)
1669 struct proc *p = it->it_proc;
1672 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1673 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1674 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1676 timespecclear(&it->it_time.it_value);
1677 timespecclear(&it->it_time.it_interval);
1678 callout_stop(&it->it_callout);
1682 if (!KSI_ONQ(&it->it_ksi)) {
1683 it->it_ksi.ksi_errno = 0;
1684 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1685 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1687 if (it->it_overrun < INT_MAX)
1690 it->it_ksi.ksi_errno = ERANGE;
1697 itimers_alloc(struct proc *p)
1699 struct itimers *its;
1702 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1703 LIST_INIT(&its->its_virtual);
1704 LIST_INIT(&its->its_prof);
1705 TAILQ_INIT(&its->its_worklist);
1706 for (i = 0; i < TIMER_MAX; i++)
1707 its->its_timers[i] = NULL;
1709 if (p->p_itimers == NULL) {
1715 free(its, M_SUBPROC);
1720 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1722 itimers_event_hook_exit(arg, p);
1725 /* Clean up timers when some process events are being triggered. */
1727 itimers_event_hook_exit(void *arg, struct proc *p)
1729 struct itimers *its;
1731 int event = (int)(intptr_t)arg;
1734 if (p->p_itimers != NULL) {
1736 for (i = 0; i < MAX_CLOCKS; ++i) {
1737 if (posix_clocks[i].event_hook != NULL)
1738 CLOCK_CALL(i, event_hook, (p, i, event));
1741 * According to susv3, XSI interval timers should be inherited
1744 if (event == ITIMER_EV_EXEC)
1746 else if (event == ITIMER_EV_EXIT)
1749 panic("unhandled event");
1750 for (; i < TIMER_MAX; ++i) {
1751 if ((it = its->its_timers[i]) != NULL)
1752 kern_ktimer_delete(curthread, i);
1754 if (its->its_timers[0] == NULL &&
1755 its->its_timers[1] == NULL &&
1756 its->its_timers[2] == NULL) {
1757 free(its, M_SUBPROC);
1758 p->p_itimers = NULL;