2 * Copyright (c) 1982, 1986, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)kern_time.c 8.1 (Berkeley) 6/10/93
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include "opt_ktrace.h"
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/limits.h>
40 #include <sys/clock.h>
42 #include <sys/mutex.h>
43 #include <sys/sysproto.h>
44 #include <sys/eventhandler.h>
45 #include <sys/resourcevar.h>
46 #include <sys/signalvar.h>
47 #include <sys/kernel.h>
48 #include <sys/sleepqueue.h>
49 #include <sys/syscallsubr.h>
50 #include <sys/sysctl.h>
51 #include <sys/sysent.h>
54 #include <sys/posix4.h>
56 #include <sys/timers.h>
57 #include <sys/timetc.h>
58 #include <sys/vnode.h>
60 #include <sys/ktrace.h>
64 #include <vm/vm_extern.h>
66 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
67 #define CPUCLOCK_BIT 0x80000000
68 #define CPUCLOCK_PROCESS_BIT 0x40000000
69 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
70 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
71 #define MAKE_PROCESS_CPUCLOCK(pid) \
72 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
74 static struct kclock posix_clocks[MAX_CLOCKS];
75 static uma_zone_t itimer_zone = NULL;
78 * Time of day and interval timer support.
80 * These routines provide the kernel entry points to get and set
81 * the time-of-day and per-process interval timers. Subroutines
82 * here provide support for adding and subtracting timeval structures
83 * and decrementing interval timers, optionally reloading the interval
84 * timers when they expire.
87 static int settime(struct thread *, struct timeval *);
88 static void timevalfix(struct timeval *);
89 static int user_clock_nanosleep(struct thread *td, clockid_t clock_id,
90 int flags, const struct timespec *ua_rqtp,
91 struct timespec *ua_rmtp);
93 static void itimer_start(void);
94 static int itimer_init(void *, int, int);
95 static void itimer_fini(void *, int);
96 static void itimer_enter(struct itimer *);
97 static void itimer_leave(struct itimer *);
98 static struct itimer *itimer_find(struct proc *, int);
99 static void itimers_alloc(struct proc *);
100 static void itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
101 static void itimers_event_hook_exit(void *arg, struct proc *p);
102 static int realtimer_create(struct itimer *);
103 static int realtimer_gettime(struct itimer *, struct itimerspec *);
104 static int realtimer_settime(struct itimer *, int,
105 struct itimerspec *, struct itimerspec *);
106 static int realtimer_delete(struct itimer *);
107 static void realtimer_clocktime(clockid_t, struct timespec *);
108 static void realtimer_expire(void *);
110 int register_posix_clock(int, struct kclock *);
111 void itimer_fire(struct itimer *it);
112 int itimespecfix(struct timespec *ts);
114 #define CLOCK_CALL(clock, call, arglist) \
115 ((*posix_clocks[clock].call) arglist)
117 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
121 settime(struct thread *td, struct timeval *tv)
123 struct timeval delta, tv1, tv2;
124 static struct timeval maxtime, laststep;
129 timevalsub(&delta, &tv1);
132 * If the system is secure, we do not allow the time to be
133 * set to a value earlier than 1 second less than the highest
134 * time we have yet seen. The worst a miscreant can do in
135 * this circumstance is "freeze" time. He couldn't go
138 * We similarly do not allow the clock to be stepped more
139 * than one second, nor more than once per second. This allows
140 * a miscreant to make the clock march double-time, but no worse.
142 if (securelevel_gt(td->td_ucred, 1) != 0) {
143 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
145 * Update maxtime to latest time we've seen.
147 if (tv1.tv_sec > maxtime.tv_sec)
150 timevalsub(&tv2, &maxtime);
151 if (tv2.tv_sec < -1) {
152 tv->tv_sec = maxtime.tv_sec - 1;
153 printf("Time adjustment clamped to -1 second\n");
156 if (tv1.tv_sec == laststep.tv_sec)
158 if (delta.tv_sec > 1) {
159 tv->tv_sec = tv1.tv_sec + 1;
160 printf("Time adjustment clamped to +1 second\n");
166 ts.tv_sec = tv->tv_sec;
167 ts.tv_nsec = tv->tv_usec * 1000;
173 #ifndef _SYS_SYSPROTO_H_
174 struct clock_getcpuclockid2_args {
182 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
187 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
189 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
194 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
203 case CPUCLOCK_WHICH_PID:
205 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
211 pid = td->td_proc->p_pid;
213 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
215 case CPUCLOCK_WHICH_TID:
216 tid = id == 0 ? td->td_tid : id;
217 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
224 #ifndef _SYS_SYSPROTO_H_
225 struct clock_gettime_args {
232 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
237 error = kern_clock_gettime(td, uap->clock_id, &ats);
239 error = copyout(&ats, uap->tp, sizeof(ats));
245 cputick2timespec(uint64_t runtime, struct timespec *ats)
247 runtime = cputick2usec(runtime);
248 ats->tv_sec = runtime / 1000000;
249 ats->tv_nsec = runtime % 1000000 * 1000;
253 get_thread_cputime(struct thread *targettd, struct timespec *ats)
255 uint64_t runtime, curtime, switchtime;
257 if (targettd == NULL) { /* current thread */
259 switchtime = PCPU_GET(switchtime);
260 curtime = cpu_ticks();
261 runtime = curthread->td_runtime;
263 runtime += curtime - switchtime;
265 thread_lock(targettd);
266 runtime = targettd->td_runtime;
267 thread_unlock(targettd);
269 cputick2timespec(runtime, ats);
273 get_process_cputime(struct proc *targetp, struct timespec *ats)
278 PROC_STATLOCK(targetp);
279 rufetch(targetp, &ru);
280 runtime = targetp->p_rux.rux_runtime;
281 PROC_STATUNLOCK(targetp);
282 cputick2timespec(runtime, ats);
286 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
295 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
296 tid = clock_id & CPUCLOCK_ID_MASK;
297 td2 = tdfind(tid, p->p_pid);
300 get_thread_cputime(td2, ats);
301 PROC_UNLOCK(td2->td_proc);
303 pid = clock_id & CPUCLOCK_ID_MASK;
304 error = pget(pid, PGET_CANSEE, &p2);
307 get_process_cputime(p2, ats);
314 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
316 struct timeval sys, user;
321 case CLOCK_REALTIME: /* Default to precise. */
322 case CLOCK_REALTIME_PRECISE:
325 case CLOCK_REALTIME_FAST:
331 calcru(p, &user, &sys);
334 TIMEVAL_TO_TIMESPEC(&user, ats);
339 calcru(p, &user, &sys);
342 timevaladd(&user, &sys);
343 TIMEVAL_TO_TIMESPEC(&user, ats);
345 case CLOCK_MONOTONIC: /* Default to precise. */
346 case CLOCK_MONOTONIC_PRECISE:
348 case CLOCK_UPTIME_PRECISE:
351 case CLOCK_UPTIME_FAST:
352 case CLOCK_MONOTONIC_FAST:
356 ats->tv_sec = time_second;
359 case CLOCK_THREAD_CPUTIME_ID:
360 get_thread_cputime(NULL, ats);
362 case CLOCK_PROCESS_CPUTIME_ID:
364 get_process_cputime(p, ats);
368 if ((int)clock_id >= 0)
370 return (get_cputime(td, clock_id, ats));
375 #ifndef _SYS_SYSPROTO_H_
376 struct clock_settime_args {
378 const struct timespec *tp;
383 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
388 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
390 return (kern_clock_settime(td, uap->clock_id, &ats));
393 static int allow_insane_settime = 0;
394 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
395 &allow_insane_settime, 0,
396 "do not perform possibly restrictive checks on settime(2) args");
399 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
404 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
406 if (clock_id != CLOCK_REALTIME)
408 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
411 if (!allow_insane_settime && ats->tv_sec > 9999ULL * 366 * 24 * 60 * 60)
413 /* XXX Don't convert nsec->usec and back */
414 TIMESPEC_TO_TIMEVAL(&atv, ats);
415 error = settime(td, &atv);
419 #ifndef _SYS_SYSPROTO_H_
420 struct clock_getres_args {
426 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
434 error = kern_clock_getres(td, uap->clock_id, &ts);
436 error = copyout(&ts, uap->tp, sizeof(ts));
441 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
447 case CLOCK_REALTIME_FAST:
448 case CLOCK_REALTIME_PRECISE:
449 case CLOCK_MONOTONIC:
450 case CLOCK_MONOTONIC_FAST:
451 case CLOCK_MONOTONIC_PRECISE:
453 case CLOCK_UPTIME_FAST:
454 case CLOCK_UPTIME_PRECISE:
456 * Round up the result of the division cheaply by adding 1.
457 * Rounding up is especially important if rounding down
458 * would give 0. Perfect rounding is unimportant.
460 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
464 /* Accurately round up here because we can do so cheaply. */
465 ts->tv_nsec = howmany(1000000000, hz);
471 case CLOCK_THREAD_CPUTIME_ID:
472 case CLOCK_PROCESS_CPUTIME_ID:
474 /* sync with cputick2usec */
475 ts->tv_nsec = 1000000 / cpu_tickrate();
476 if (ts->tv_nsec == 0)
480 if ((int)clock_id < 0)
488 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
491 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
495 static uint8_t nanowait[MAXCPU];
498 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
499 const struct timespec *rqt, struct timespec *rmt)
501 struct timespec ts, now;
502 sbintime_t sbt, sbtt, prec, tmp;
507 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
509 if ((flags & ~TIMER_ABSTIME) != 0)
513 case CLOCK_REALTIME_PRECISE:
514 case CLOCK_REALTIME_FAST:
516 is_abs_real = (flags & TIMER_ABSTIME) != 0;
518 case CLOCK_MONOTONIC:
519 case CLOCK_MONOTONIC_PRECISE:
520 case CLOCK_MONOTONIC_FAST:
522 case CLOCK_UPTIME_PRECISE:
523 case CLOCK_UPTIME_FAST:
528 case CLOCK_PROCESS_CPUTIME_ID:
530 case CLOCK_THREAD_CPUTIME_ID:
536 if ((flags & TIMER_ABSTIME) != 0) {
539 atomic_load_acq_int(&rtc_generation);
540 error = kern_clock_gettime(td, clock_id, &now);
541 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
542 timespecsub(&ts, &now);
544 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
548 if (ts.tv_sec > INT32_MAX / 2) {
549 over = ts.tv_sec - INT32_MAX / 2;
556 if (TIMESEL(&sbt, tmp))
559 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
560 sbt, prec, C_ABSOLUTE);
561 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
563 if (error != EWOULDBLOCK) {
567 if (error == ERESTART)
569 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
570 ts = sbttots(sbt - sbtt);
581 #ifndef _SYS_SYSPROTO_H_
582 struct nanosleep_args {
583 struct timespec *rqtp;
584 struct timespec *rmtp;
589 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
592 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
593 uap->rqtp, uap->rmtp));
596 #ifndef _SYS_SYSPROTO_H_
597 struct clock_nanosleep_args {
600 struct timespec *rqtp;
601 struct timespec *rmtp;
606 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
610 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
612 return (kern_posix_error(td, error));
616 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
617 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
619 struct timespec rmt, rqt;
622 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
625 if (ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0 &&
626 !useracc(ua_rmtp, sizeof(rmt), VM_PROT_WRITE))
628 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
629 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
632 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
639 #ifndef _SYS_SYSPROTO_H_
640 struct gettimeofday_args {
642 struct timezone *tzp;
647 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
655 error = copyout(&atv, uap->tp, sizeof (atv));
657 if (error == 0 && uap->tzp != NULL) {
658 rtz.tz_minuteswest = tz_minuteswest;
659 rtz.tz_dsttime = tz_dsttime;
660 error = copyout(&rtz, uap->tzp, sizeof (rtz));
665 #ifndef _SYS_SYSPROTO_H_
666 struct settimeofday_args {
668 struct timezone *tzp;
673 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
675 struct timeval atv, *tvp;
676 struct timezone atz, *tzp;
680 error = copyin(uap->tv, &atv, sizeof(atv));
687 error = copyin(uap->tzp, &atz, sizeof(atz));
693 return (kern_settimeofday(td, tvp, tzp));
697 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
701 error = priv_check(td, PRIV_SETTIMEOFDAY);
704 /* Verify all parameters before changing time. */
706 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
709 error = settime(td, tv);
711 if (tzp && error == 0) {
712 tz_minuteswest = tzp->tz_minuteswest;
713 tz_dsttime = tzp->tz_dsttime;
719 * Get value of an interval timer. The process virtual and profiling virtual
720 * time timers are kept in the p_stats area, since they can be swapped out.
721 * These are kept internally in the way they are specified externally: in
722 * time until they expire.
724 * The real time interval timer is kept in the process table slot for the
725 * process, and its value (it_value) is kept as an absolute time rather than
726 * as a delta, so that it is easy to keep periodic real-time signals from
729 * Virtual time timers are processed in the hardclock() routine of
730 * kern_clock.c. The real time timer is processed by a timeout routine,
731 * called from the softclock() routine. Since a callout may be delayed in
732 * real time due to interrupt processing in the system, it is possible for
733 * the real time timeout routine (realitexpire, given below), to be delayed
734 * in real time past when it is supposed to occur. It does not suffice,
735 * therefore, to reload the real timer .it_value from the real time timers
736 * .it_interval. Rather, we compute the next time in absolute time the timer
739 #ifndef _SYS_SYSPROTO_H_
740 struct getitimer_args {
742 struct itimerval *itv;
746 sys_getitimer(struct thread *td, struct getitimer_args *uap)
748 struct itimerval aitv;
751 error = kern_getitimer(td, uap->which, &aitv);
754 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
758 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
760 struct proc *p = td->td_proc;
763 if (which > ITIMER_PROF)
766 if (which == ITIMER_REAL) {
768 * Convert from absolute to relative time in .it_value
769 * part of real time timer. If time for real time timer
770 * has passed return 0, else return difference between
771 * current time and time for the timer to go off.
774 *aitv = p->p_realtimer;
776 if (timevalisset(&aitv->it_value)) {
778 if (timevalcmp(&aitv->it_value, &ctv, <))
779 timevalclear(&aitv->it_value);
781 timevalsub(&aitv->it_value, &ctv);
785 *aitv = p->p_stats->p_timer[which];
789 if (KTRPOINT(td, KTR_STRUCT))
795 #ifndef _SYS_SYSPROTO_H_
796 struct setitimer_args {
798 struct itimerval *itv, *oitv;
802 sys_setitimer(struct thread *td, struct setitimer_args *uap)
804 struct itimerval aitv, oitv;
807 if (uap->itv == NULL) {
808 uap->itv = uap->oitv;
809 return (sys_getitimer(td, (struct getitimer_args *)uap));
812 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
814 error = kern_setitimer(td, uap->which, &aitv, &oitv);
815 if (error != 0 || uap->oitv == NULL)
817 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
821 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
822 struct itimerval *oitv)
824 struct proc *p = td->td_proc;
829 return (kern_getitimer(td, which, oitv));
831 if (which > ITIMER_PROF)
834 if (KTRPOINT(td, KTR_STRUCT))
837 if (itimerfix(&aitv->it_value) ||
838 aitv->it_value.tv_sec > INT32_MAX / 2)
840 if (!timevalisset(&aitv->it_value))
841 timevalclear(&aitv->it_interval);
842 else if (itimerfix(&aitv->it_interval) ||
843 aitv->it_interval.tv_sec > INT32_MAX / 2)
846 if (which == ITIMER_REAL) {
848 if (timevalisset(&p->p_realtimer.it_value))
849 callout_stop(&p->p_itcallout);
851 if (timevalisset(&aitv->it_value)) {
852 pr = tvtosbt(aitv->it_value) >> tc_precexp;
853 timevaladd(&aitv->it_value, &ctv);
854 sbt = tvtosbt(aitv->it_value);
855 callout_reset_sbt(&p->p_itcallout, sbt, pr,
856 realitexpire, p, C_ABSOLUTE);
858 *oitv = p->p_realtimer;
859 p->p_realtimer = *aitv;
861 if (timevalisset(&oitv->it_value)) {
862 if (timevalcmp(&oitv->it_value, &ctv, <))
863 timevalclear(&oitv->it_value);
865 timevalsub(&oitv->it_value, &ctv);
868 if (aitv->it_interval.tv_sec == 0 &&
869 aitv->it_interval.tv_usec != 0 &&
870 aitv->it_interval.tv_usec < tick)
871 aitv->it_interval.tv_usec = tick;
872 if (aitv->it_value.tv_sec == 0 &&
873 aitv->it_value.tv_usec != 0 &&
874 aitv->it_value.tv_usec < tick)
875 aitv->it_value.tv_usec = tick;
877 *oitv = p->p_stats->p_timer[which];
878 p->p_stats->p_timer[which] = *aitv;
882 if (KTRPOINT(td, KTR_STRUCT))
889 * Real interval timer expired:
890 * send process whose timer expired an alarm signal.
891 * If time is not set up to reload, then just return.
892 * Else compute next time timer should go off which is > current time.
893 * This is where delay in processing this timeout causes multiple
894 * SIGALRM calls to be compressed into one.
895 * tvtohz() always adds 1 to allow for the time until the next clock
896 * interrupt being strictly less than 1 clock tick, but we don't want
897 * that here since we want to appear to be in sync with the clock
898 * interrupt even when we're delayed.
901 realitexpire(void *arg)
907 p = (struct proc *)arg;
908 kern_psignal(p, SIGALRM);
909 if (!timevalisset(&p->p_realtimer.it_interval)) {
910 timevalclear(&p->p_realtimer.it_value);
911 if (p->p_flag & P_WEXIT)
912 wakeup(&p->p_itcallout);
915 isbt = tvtosbt(p->p_realtimer.it_interval);
916 if (isbt >= sbt_timethreshold)
917 getmicrouptime(&ctv);
921 timevaladd(&p->p_realtimer.it_value,
922 &p->p_realtimer.it_interval);
923 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
924 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
925 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
929 * Check that a proposed value to load into the .it_value or
930 * .it_interval part of an interval timer is acceptable, and
931 * fix it to have at least minimal value (i.e. if it is less
932 * than the resolution of the clock, round it up.)
935 itimerfix(struct timeval *tv)
938 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
940 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
941 tv->tv_usec < (u_int)tick / 16)
942 tv->tv_usec = (u_int)tick / 16;
947 * Decrement an interval timer by a specified number
948 * of microseconds, which must be less than a second,
949 * i.e. < 1000000. If the timer expires, then reload
950 * it. In this case, carry over (usec - old value) to
951 * reduce the value reloaded into the timer so that
952 * the timer does not drift. This routine assumes
953 * that it is called in a context where the timers
954 * on which it is operating cannot change in value.
957 itimerdecr(struct itimerval *itp, int usec)
960 if (itp->it_value.tv_usec < usec) {
961 if (itp->it_value.tv_sec == 0) {
962 /* expired, and already in next interval */
963 usec -= itp->it_value.tv_usec;
966 itp->it_value.tv_usec += 1000000;
967 itp->it_value.tv_sec--;
969 itp->it_value.tv_usec -= usec;
971 if (timevalisset(&itp->it_value))
973 /* expired, exactly at end of interval */
975 if (timevalisset(&itp->it_interval)) {
976 itp->it_value = itp->it_interval;
977 itp->it_value.tv_usec -= usec;
978 if (itp->it_value.tv_usec < 0) {
979 itp->it_value.tv_usec += 1000000;
980 itp->it_value.tv_sec--;
983 itp->it_value.tv_usec = 0; /* sec is already 0 */
988 * Add and subtract routines for timevals.
989 * N.B.: subtract routine doesn't deal with
990 * results which are before the beginning,
991 * it just gets very confused in this case.
995 timevaladd(struct timeval *t1, const struct timeval *t2)
998 t1->tv_sec += t2->tv_sec;
999 t1->tv_usec += t2->tv_usec;
1004 timevalsub(struct timeval *t1, const struct timeval *t2)
1007 t1->tv_sec -= t2->tv_sec;
1008 t1->tv_usec -= t2->tv_usec;
1013 timevalfix(struct timeval *t1)
1016 if (t1->tv_usec < 0) {
1018 t1->tv_usec += 1000000;
1020 if (t1->tv_usec >= 1000000) {
1022 t1->tv_usec -= 1000000;
1027 * ratecheck(): simple time-based rate-limit checking.
1030 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1032 struct timeval tv, delta;
1035 getmicrouptime(&tv); /* NB: 10ms precision */
1037 timevalsub(&delta, lasttime);
1040 * check for 0,0 is so that the message will be seen at least once,
1041 * even if interval is huge.
1043 if (timevalcmp(&delta, mininterval, >=) ||
1044 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1053 * ppsratecheck(): packets (or events) per second limitation.
1055 * Return 0 if the limit is to be enforced (e.g. the caller
1056 * should drop a packet because of the rate limitation).
1058 * maxpps of 0 always causes zero to be returned. maxpps of -1
1059 * always causes 1 to be returned; this effectively defeats rate
1062 * Note that we maintain the struct timeval for compatibility
1063 * with other bsd systems. We reuse the storage and just monitor
1064 * clock ticks for minimal overhead.
1067 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1072 * Reset the last time and counter if this is the first call
1073 * or more than a second has passed since the last update of
1077 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1078 lasttime->tv_sec = now;
1080 return (maxpps != 0);
1082 (*curpps)++; /* NB: ignore potential overflow */
1083 return (maxpps < 0 || *curpps <= maxpps);
1090 struct kclock rt_clock = {
1091 .timer_create = realtimer_create,
1092 .timer_delete = realtimer_delete,
1093 .timer_settime = realtimer_settime,
1094 .timer_gettime = realtimer_gettime,
1098 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1099 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1100 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1101 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1102 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1103 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1104 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1105 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1106 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1107 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1108 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1112 register_posix_clock(int clockid, struct kclock *clk)
1114 if ((unsigned)clockid >= MAX_CLOCKS) {
1115 printf("%s: invalid clockid\n", __func__);
1118 posix_clocks[clockid] = *clk;
1123 itimer_init(void *mem, int size, int flags)
1127 it = (struct itimer *)mem;
1128 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1133 itimer_fini(void *mem, int size)
1137 it = (struct itimer *)mem;
1138 mtx_destroy(&it->it_mtx);
1142 itimer_enter(struct itimer *it)
1145 mtx_assert(&it->it_mtx, MA_OWNED);
1150 itimer_leave(struct itimer *it)
1153 mtx_assert(&it->it_mtx, MA_OWNED);
1154 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1156 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1160 #ifndef _SYS_SYSPROTO_H_
1161 struct ktimer_create_args {
1163 struct sigevent * evp;
1168 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1170 struct sigevent *evp, ev;
1174 if (uap->evp == NULL) {
1177 error = copyin(uap->evp, &ev, sizeof(ev));
1182 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1184 error = copyout(&id, uap->timerid, sizeof(int));
1186 kern_ktimer_delete(td, id);
1192 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1193 int *timerid, int preset_id)
1195 struct proc *p = td->td_proc;
1200 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1203 if (posix_clocks[clock_id].timer_create == NULL)
1207 if (evp->sigev_notify != SIGEV_NONE &&
1208 evp->sigev_notify != SIGEV_SIGNAL &&
1209 evp->sigev_notify != SIGEV_THREAD_ID)
1211 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1212 evp->sigev_notify == SIGEV_THREAD_ID) &&
1213 !_SIG_VALID(evp->sigev_signo))
1217 if (p->p_itimers == NULL)
1220 it = uma_zalloc(itimer_zone, M_WAITOK);
1222 it->it_usecount = 0;
1224 timespecclear(&it->it_time.it_value);
1225 timespecclear(&it->it_time.it_interval);
1227 it->it_overrun_last = 0;
1228 it->it_clockid = clock_id;
1229 it->it_timerid = -1;
1231 ksiginfo_init(&it->it_ksi);
1232 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1233 error = CLOCK_CALL(clock_id, timer_create, (it));
1238 if (preset_id != -1) {
1239 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1241 if (p->p_itimers->its_timers[id] != NULL) {
1248 * Find a free timer slot, skipping those reserved
1251 for (id = 3; id < TIMER_MAX; id++)
1252 if (p->p_itimers->its_timers[id] == NULL)
1254 if (id == TIMER_MAX) {
1260 it->it_timerid = id;
1261 p->p_itimers->its_timers[id] = it;
1263 it->it_sigev = *evp;
1265 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1268 case CLOCK_REALTIME:
1269 it->it_sigev.sigev_signo = SIGALRM;
1272 it->it_sigev.sigev_signo = SIGVTALRM;
1275 it->it_sigev.sigev_signo = SIGPROF;
1278 it->it_sigev.sigev_value.sival_int = id;
1281 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1282 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1283 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1284 it->it_ksi.ksi_code = SI_TIMER;
1285 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1286 it->it_ksi.ksi_timerid = id;
1294 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1296 uma_zfree(itimer_zone, it);
1300 #ifndef _SYS_SYSPROTO_H_
1301 struct ktimer_delete_args {
1306 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1309 return (kern_ktimer_delete(td, uap->timerid));
1312 static struct itimer *
1313 itimer_find(struct proc *p, int timerid)
1317 PROC_LOCK_ASSERT(p, MA_OWNED);
1318 if ((p->p_itimers == NULL) ||
1319 (timerid < 0) || (timerid >= TIMER_MAX) ||
1320 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1324 if ((it->it_flags & ITF_DELETING) != 0) {
1332 kern_ktimer_delete(struct thread *td, int timerid)
1334 struct proc *p = td->td_proc;
1338 it = itimer_find(p, timerid);
1345 it->it_flags |= ITF_DELETING;
1346 while (it->it_usecount > 0) {
1347 it->it_flags |= ITF_WANTED;
1348 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1350 it->it_flags &= ~ITF_WANTED;
1351 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1355 if (KSI_ONQ(&it->it_ksi))
1356 sigqueue_take(&it->it_ksi);
1357 p->p_itimers->its_timers[timerid] = NULL;
1359 uma_zfree(itimer_zone, it);
1363 #ifndef _SYS_SYSPROTO_H_
1364 struct ktimer_settime_args {
1367 const struct itimerspec * value;
1368 struct itimerspec * ovalue;
1372 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1374 struct itimerspec val, oval, *ovalp;
1377 error = copyin(uap->value, &val, sizeof(val));
1380 ovalp = uap->ovalue != NULL ? &oval : NULL;
1381 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1382 if (error == 0 && uap->ovalue != NULL)
1383 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1388 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1389 struct itimerspec *val, struct itimerspec *oval)
1397 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1403 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1411 #ifndef _SYS_SYSPROTO_H_
1412 struct ktimer_gettime_args {
1414 struct itimerspec * value;
1418 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1420 struct itimerspec val;
1423 error = kern_ktimer_gettime(td, uap->timerid, &val);
1425 error = copyout(&val, uap->value, sizeof(val));
1430 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1438 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1444 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1451 #ifndef _SYS_SYSPROTO_H_
1452 struct timer_getoverrun_args {
1457 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1460 return (kern_ktimer_getoverrun(td, uap->timerid));
1464 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1466 struct proc *p = td->td_proc;
1472 (it = itimer_find(p, timer_id)) == NULL) {
1476 td->td_retval[0] = it->it_overrun_last;
1485 realtimer_create(struct itimer *it)
1487 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1492 realtimer_delete(struct itimer *it)
1494 mtx_assert(&it->it_mtx, MA_OWNED);
1497 * clear timer's value and interval to tell realtimer_expire
1498 * to not rearm the timer.
1500 timespecclear(&it->it_time.it_value);
1501 timespecclear(&it->it_time.it_interval);
1503 callout_drain(&it->it_callout);
1509 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1511 struct timespec cts;
1513 mtx_assert(&it->it_mtx, MA_OWNED);
1515 realtimer_clocktime(it->it_clockid, &cts);
1516 *ovalue = it->it_time;
1517 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1518 timespecsub(&ovalue->it_value, &cts);
1519 if (ovalue->it_value.tv_sec < 0 ||
1520 (ovalue->it_value.tv_sec == 0 &&
1521 ovalue->it_value.tv_nsec == 0)) {
1522 ovalue->it_value.tv_sec = 0;
1523 ovalue->it_value.tv_nsec = 1;
1530 realtimer_settime(struct itimer *it, int flags,
1531 struct itimerspec *value, struct itimerspec *ovalue)
1533 struct timespec cts, ts;
1535 struct itimerspec val;
1537 mtx_assert(&it->it_mtx, MA_OWNED);
1540 if (itimespecfix(&val.it_value))
1543 if (timespecisset(&val.it_value)) {
1544 if (itimespecfix(&val.it_interval))
1547 timespecclear(&val.it_interval);
1551 realtimer_gettime(it, ovalue);
1554 if (timespecisset(&val.it_value)) {
1555 realtimer_clocktime(it->it_clockid, &cts);
1557 if ((flags & TIMER_ABSTIME) == 0) {
1558 /* Convert to absolute time. */
1559 timespecadd(&it->it_time.it_value, &cts);
1561 timespecsub(&ts, &cts);
1563 * We don't care if ts is negative, tztohz will
1567 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1568 callout_reset(&it->it_callout, tvtohz(&tv),
1569 realtimer_expire, it);
1571 callout_stop(&it->it_callout);
1578 realtimer_clocktime(clockid_t id, struct timespec *ts)
1580 if (id == CLOCK_REALTIME)
1582 else /* CLOCK_MONOTONIC */
1587 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1591 PROC_LOCK_ASSERT(p, MA_OWNED);
1592 it = itimer_find(p, timerid);
1594 ksi->ksi_overrun = it->it_overrun;
1595 it->it_overrun_last = it->it_overrun;
1604 itimespecfix(struct timespec *ts)
1607 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1609 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1610 ts->tv_nsec = tick * 1000;
1614 /* Timeout callback for realtime timer */
1616 realtimer_expire(void *arg)
1618 struct timespec cts, ts;
1622 it = (struct itimer *)arg;
1624 realtimer_clocktime(it->it_clockid, &cts);
1625 /* Only fire if time is reached. */
1626 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1627 if (timespecisset(&it->it_time.it_interval)) {
1628 timespecadd(&it->it_time.it_value,
1629 &it->it_time.it_interval);
1630 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1631 if (it->it_overrun < INT_MAX)
1634 it->it_ksi.ksi_errno = ERANGE;
1635 timespecadd(&it->it_time.it_value,
1636 &it->it_time.it_interval);
1639 /* single shot timer ? */
1640 timespecclear(&it->it_time.it_value);
1642 if (timespecisset(&it->it_time.it_value)) {
1643 ts = it->it_time.it_value;
1644 timespecsub(&ts, &cts);
1645 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1646 callout_reset(&it->it_callout, tvtohz(&tv),
1647 realtimer_expire, it);
1654 } else if (timespecisset(&it->it_time.it_value)) {
1655 ts = it->it_time.it_value;
1656 timespecsub(&ts, &cts);
1657 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1658 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1664 itimer_fire(struct itimer *it)
1666 struct proc *p = it->it_proc;
1669 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1670 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1671 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1673 timespecclear(&it->it_time.it_value);
1674 timespecclear(&it->it_time.it_interval);
1675 callout_stop(&it->it_callout);
1679 if (!KSI_ONQ(&it->it_ksi)) {
1680 it->it_ksi.ksi_errno = 0;
1681 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1682 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1684 if (it->it_overrun < INT_MAX)
1687 it->it_ksi.ksi_errno = ERANGE;
1694 itimers_alloc(struct proc *p)
1696 struct itimers *its;
1699 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1700 LIST_INIT(&its->its_virtual);
1701 LIST_INIT(&its->its_prof);
1702 TAILQ_INIT(&its->its_worklist);
1703 for (i = 0; i < TIMER_MAX; i++)
1704 its->its_timers[i] = NULL;
1706 if (p->p_itimers == NULL) {
1712 free(its, M_SUBPROC);
1717 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1719 itimers_event_hook_exit(arg, p);
1722 /* Clean up timers when some process events are being triggered. */
1724 itimers_event_hook_exit(void *arg, struct proc *p)
1726 struct itimers *its;
1728 int event = (int)(intptr_t)arg;
1731 if (p->p_itimers != NULL) {
1733 for (i = 0; i < MAX_CLOCKS; ++i) {
1734 if (posix_clocks[i].event_hook != NULL)
1735 CLOCK_CALL(i, event_hook, (p, i, event));
1738 * According to susv3, XSI interval timers should be inherited
1741 if (event == ITIMER_EV_EXEC)
1743 else if (event == ITIMER_EV_EXIT)
1746 panic("unhandled event");
1747 for (; i < TIMER_MAX; ++i) {
1748 if ((it = its->its_timers[i]) != NULL)
1749 kern_ktimer_delete(curthread, i);
1751 if (its->its_timers[0] == NULL &&
1752 its->its_timers[1] == NULL &&
1753 its->its_timers[2] == NULL) {
1754 free(its, M_SUBPROC);
1755 p->p_itimers = NULL;