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 kern_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 PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
268 thread_lock(targettd);
269 runtime = targettd->td_runtime;
270 thread_unlock(targettd);
272 cputick2timespec(runtime, ats);
276 kern_process_cputime(struct proc *targetp, struct timespec *ats)
281 PROC_LOCK_ASSERT(targetp, MA_OWNED);
282 PROC_STATLOCK(targetp);
283 rufetch(targetp, &ru);
284 runtime = targetp->p_rux.rux_runtime;
285 if (curthread->td_proc == targetp)
286 runtime += cpu_ticks() - PCPU_GET(switchtime);
287 PROC_STATUNLOCK(targetp);
288 cputick2timespec(runtime, ats);
292 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
301 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
302 tid = clock_id & CPUCLOCK_ID_MASK;
303 td2 = tdfind(tid, p->p_pid);
306 kern_thread_cputime(td2, ats);
307 PROC_UNLOCK(td2->td_proc);
309 pid = clock_id & CPUCLOCK_ID_MASK;
310 error = pget(pid, PGET_CANSEE, &p2);
313 kern_process_cputime(p2, ats);
320 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
322 struct timeval sys, user;
327 case CLOCK_REALTIME: /* Default to precise. */
328 case CLOCK_REALTIME_PRECISE:
331 case CLOCK_REALTIME_FAST:
337 calcru(p, &user, &sys);
340 TIMEVAL_TO_TIMESPEC(&user, ats);
345 calcru(p, &user, &sys);
348 timevaladd(&user, &sys);
349 TIMEVAL_TO_TIMESPEC(&user, ats);
351 case CLOCK_MONOTONIC: /* Default to precise. */
352 case CLOCK_MONOTONIC_PRECISE:
354 case CLOCK_UPTIME_PRECISE:
357 case CLOCK_UPTIME_FAST:
358 case CLOCK_MONOTONIC_FAST:
362 ats->tv_sec = time_second;
365 case CLOCK_THREAD_CPUTIME_ID:
366 kern_thread_cputime(NULL, ats);
368 case CLOCK_PROCESS_CPUTIME_ID:
370 kern_process_cputime(p, ats);
374 if ((int)clock_id >= 0)
376 return (get_cputime(td, clock_id, ats));
381 #ifndef _SYS_SYSPROTO_H_
382 struct clock_settime_args {
384 const struct timespec *tp;
389 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
394 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
396 return (kern_clock_settime(td, uap->clock_id, &ats));
399 static int allow_insane_settime = 0;
400 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
401 &allow_insane_settime, 0,
402 "do not perform possibly restrictive checks on settime(2) args");
405 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
410 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
412 if (clock_id != CLOCK_REALTIME)
414 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
417 if (!allow_insane_settime && ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60)
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 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
633 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
634 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
641 #ifndef _SYS_SYSPROTO_H_
642 struct gettimeofday_args {
644 struct timezone *tzp;
649 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
657 error = copyout(&atv, uap->tp, sizeof (atv));
659 if (error == 0 && uap->tzp != NULL) {
660 rtz.tz_minuteswest = tz_minuteswest;
661 rtz.tz_dsttime = tz_dsttime;
662 error = copyout(&rtz, uap->tzp, sizeof (rtz));
667 #ifndef _SYS_SYSPROTO_H_
668 struct settimeofday_args {
670 struct timezone *tzp;
675 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
677 struct timeval atv, *tvp;
678 struct timezone atz, *tzp;
682 error = copyin(uap->tv, &atv, sizeof(atv));
689 error = copyin(uap->tzp, &atz, sizeof(atz));
695 return (kern_settimeofday(td, tvp, tzp));
699 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
703 error = priv_check(td, PRIV_SETTIMEOFDAY);
706 /* Verify all parameters before changing time. */
708 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
711 error = settime(td, tv);
713 if (tzp && error == 0) {
714 tz_minuteswest = tzp->tz_minuteswest;
715 tz_dsttime = tzp->tz_dsttime;
721 * Get value of an interval timer. The process virtual and profiling virtual
722 * time timers are kept in the p_stats area, since they can be swapped out.
723 * These are kept internally in the way they are specified externally: in
724 * time until they expire.
726 * The real time interval timer is kept in the process table slot for the
727 * process, and its value (it_value) is kept as an absolute time rather than
728 * as a delta, so that it is easy to keep periodic real-time signals from
731 * Virtual time timers are processed in the hardclock() routine of
732 * kern_clock.c. The real time timer is processed by a timeout routine,
733 * called from the softclock() routine. Since a callout may be delayed in
734 * real time due to interrupt processing in the system, it is possible for
735 * the real time timeout routine (realitexpire, given below), to be delayed
736 * in real time past when it is supposed to occur. It does not suffice,
737 * therefore, to reload the real timer .it_value from the real time timers
738 * .it_interval. Rather, we compute the next time in absolute time the timer
741 #ifndef _SYS_SYSPROTO_H_
742 struct getitimer_args {
744 struct itimerval *itv;
748 sys_getitimer(struct thread *td, struct getitimer_args *uap)
750 struct itimerval aitv;
753 error = kern_getitimer(td, uap->which, &aitv);
756 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
760 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
762 struct proc *p = td->td_proc;
765 if (which > ITIMER_PROF)
768 if (which == ITIMER_REAL) {
770 * Convert from absolute to relative time in .it_value
771 * part of real time timer. If time for real time timer
772 * has passed return 0, else return difference between
773 * current time and time for the timer to go off.
776 *aitv = p->p_realtimer;
778 if (timevalisset(&aitv->it_value)) {
780 if (timevalcmp(&aitv->it_value, &ctv, <))
781 timevalclear(&aitv->it_value);
783 timevalsub(&aitv->it_value, &ctv);
787 *aitv = p->p_stats->p_timer[which];
791 if (KTRPOINT(td, KTR_STRUCT))
797 #ifndef _SYS_SYSPROTO_H_
798 struct setitimer_args {
800 struct itimerval *itv, *oitv;
804 sys_setitimer(struct thread *td, struct setitimer_args *uap)
806 struct itimerval aitv, oitv;
809 if (uap->itv == NULL) {
810 uap->itv = uap->oitv;
811 return (sys_getitimer(td, (struct getitimer_args *)uap));
814 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
816 error = kern_setitimer(td, uap->which, &aitv, &oitv);
817 if (error != 0 || uap->oitv == NULL)
819 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
823 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
824 struct itimerval *oitv)
826 struct proc *p = td->td_proc;
831 return (kern_getitimer(td, which, oitv));
833 if (which > ITIMER_PROF)
836 if (KTRPOINT(td, KTR_STRUCT))
839 if (itimerfix(&aitv->it_value) ||
840 aitv->it_value.tv_sec > INT32_MAX / 2)
842 if (!timevalisset(&aitv->it_value))
843 timevalclear(&aitv->it_interval);
844 else if (itimerfix(&aitv->it_interval) ||
845 aitv->it_interval.tv_sec > INT32_MAX / 2)
848 if (which == ITIMER_REAL) {
850 if (timevalisset(&p->p_realtimer.it_value))
851 callout_stop(&p->p_itcallout);
853 if (timevalisset(&aitv->it_value)) {
854 pr = tvtosbt(aitv->it_value) >> tc_precexp;
855 timevaladd(&aitv->it_value, &ctv);
856 sbt = tvtosbt(aitv->it_value);
857 callout_reset_sbt(&p->p_itcallout, sbt, pr,
858 realitexpire, p, C_ABSOLUTE);
860 *oitv = p->p_realtimer;
861 p->p_realtimer = *aitv;
863 if (timevalisset(&oitv->it_value)) {
864 if (timevalcmp(&oitv->it_value, &ctv, <))
865 timevalclear(&oitv->it_value);
867 timevalsub(&oitv->it_value, &ctv);
870 if (aitv->it_interval.tv_sec == 0 &&
871 aitv->it_interval.tv_usec != 0 &&
872 aitv->it_interval.tv_usec < tick)
873 aitv->it_interval.tv_usec = tick;
874 if (aitv->it_value.tv_sec == 0 &&
875 aitv->it_value.tv_usec != 0 &&
876 aitv->it_value.tv_usec < tick)
877 aitv->it_value.tv_usec = tick;
879 *oitv = p->p_stats->p_timer[which];
880 p->p_stats->p_timer[which] = *aitv;
884 if (KTRPOINT(td, KTR_STRUCT))
891 * Real interval timer expired:
892 * send process whose timer expired an alarm signal.
893 * If time is not set up to reload, then just return.
894 * Else compute next time timer should go off which is > current time.
895 * This is where delay in processing this timeout causes multiple
896 * SIGALRM calls to be compressed into one.
897 * tvtohz() always adds 1 to allow for the time until the next clock
898 * interrupt being strictly less than 1 clock tick, but we don't want
899 * that here since we want to appear to be in sync with the clock
900 * interrupt even when we're delayed.
903 realitexpire(void *arg)
909 p = (struct proc *)arg;
910 kern_psignal(p, SIGALRM);
911 if (!timevalisset(&p->p_realtimer.it_interval)) {
912 timevalclear(&p->p_realtimer.it_value);
913 if (p->p_flag & P_WEXIT)
914 wakeup(&p->p_itcallout);
917 isbt = tvtosbt(p->p_realtimer.it_interval);
918 if (isbt >= sbt_timethreshold)
919 getmicrouptime(&ctv);
923 timevaladd(&p->p_realtimer.it_value,
924 &p->p_realtimer.it_interval);
925 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
926 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
927 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
931 * Check that a proposed value to load into the .it_value or
932 * .it_interval part of an interval timer is acceptable, and
933 * fix it to have at least minimal value (i.e. if it is less
934 * than the resolution of the clock, round it up.)
937 itimerfix(struct timeval *tv)
940 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
942 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
943 tv->tv_usec < (u_int)tick / 16)
944 tv->tv_usec = (u_int)tick / 16;
949 * Decrement an interval timer by a specified number
950 * of microseconds, which must be less than a second,
951 * i.e. < 1000000. If the timer expires, then reload
952 * it. In this case, carry over (usec - old value) to
953 * reduce the value reloaded into the timer so that
954 * the timer does not drift. This routine assumes
955 * that it is called in a context where the timers
956 * on which it is operating cannot change in value.
959 itimerdecr(struct itimerval *itp, int usec)
962 if (itp->it_value.tv_usec < usec) {
963 if (itp->it_value.tv_sec == 0) {
964 /* expired, and already in next interval */
965 usec -= itp->it_value.tv_usec;
968 itp->it_value.tv_usec += 1000000;
969 itp->it_value.tv_sec--;
971 itp->it_value.tv_usec -= usec;
973 if (timevalisset(&itp->it_value))
975 /* expired, exactly at end of interval */
977 if (timevalisset(&itp->it_interval)) {
978 itp->it_value = itp->it_interval;
979 itp->it_value.tv_usec -= usec;
980 if (itp->it_value.tv_usec < 0) {
981 itp->it_value.tv_usec += 1000000;
982 itp->it_value.tv_sec--;
985 itp->it_value.tv_usec = 0; /* sec is already 0 */
990 * Add and subtract routines for timevals.
991 * N.B.: subtract routine doesn't deal with
992 * results which are before the beginning,
993 * it just gets very confused in this case.
997 timevaladd(struct timeval *t1, const struct timeval *t2)
1000 t1->tv_sec += t2->tv_sec;
1001 t1->tv_usec += t2->tv_usec;
1006 timevalsub(struct timeval *t1, const struct timeval *t2)
1009 t1->tv_sec -= t2->tv_sec;
1010 t1->tv_usec -= t2->tv_usec;
1015 timevalfix(struct timeval *t1)
1018 if (t1->tv_usec < 0) {
1020 t1->tv_usec += 1000000;
1022 if (t1->tv_usec >= 1000000) {
1024 t1->tv_usec -= 1000000;
1029 * ratecheck(): simple time-based rate-limit checking.
1032 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1034 struct timeval tv, delta;
1037 getmicrouptime(&tv); /* NB: 10ms precision */
1039 timevalsub(&delta, lasttime);
1042 * check for 0,0 is so that the message will be seen at least once,
1043 * even if interval is huge.
1045 if (timevalcmp(&delta, mininterval, >=) ||
1046 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1055 * ppsratecheck(): packets (or events) per second limitation.
1057 * Return 0 if the limit is to be enforced (e.g. the caller
1058 * should drop a packet because of the rate limitation).
1060 * maxpps of 0 always causes zero to be returned. maxpps of -1
1061 * always causes 1 to be returned; this effectively defeats rate
1064 * Note that we maintain the struct timeval for compatibility
1065 * with other bsd systems. We reuse the storage and just monitor
1066 * clock ticks for minimal overhead.
1069 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1074 * Reset the last time and counter if this is the first call
1075 * or more than a second has passed since the last update of
1079 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1080 lasttime->tv_sec = now;
1082 return (maxpps != 0);
1084 (*curpps)++; /* NB: ignore potential overflow */
1085 return (maxpps < 0 || *curpps <= maxpps);
1092 struct kclock rt_clock = {
1093 .timer_create = realtimer_create,
1094 .timer_delete = realtimer_delete,
1095 .timer_settime = realtimer_settime,
1096 .timer_gettime = realtimer_gettime,
1100 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1101 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1102 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1103 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1104 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1105 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1106 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1107 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1108 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1109 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1110 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1114 register_posix_clock(int clockid, struct kclock *clk)
1116 if ((unsigned)clockid >= MAX_CLOCKS) {
1117 printf("%s: invalid clockid\n", __func__);
1120 posix_clocks[clockid] = *clk;
1125 itimer_init(void *mem, int size, int flags)
1129 it = (struct itimer *)mem;
1130 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1135 itimer_fini(void *mem, int size)
1139 it = (struct itimer *)mem;
1140 mtx_destroy(&it->it_mtx);
1144 itimer_enter(struct itimer *it)
1147 mtx_assert(&it->it_mtx, MA_OWNED);
1152 itimer_leave(struct itimer *it)
1155 mtx_assert(&it->it_mtx, MA_OWNED);
1156 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1158 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1162 #ifndef _SYS_SYSPROTO_H_
1163 struct ktimer_create_args {
1165 struct sigevent * evp;
1170 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1172 struct sigevent *evp, ev;
1176 if (uap->evp == NULL) {
1179 error = copyin(uap->evp, &ev, sizeof(ev));
1184 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1186 error = copyout(&id, uap->timerid, sizeof(int));
1188 kern_ktimer_delete(td, id);
1194 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1195 int *timerid, int preset_id)
1197 struct proc *p = td->td_proc;
1202 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1205 if (posix_clocks[clock_id].timer_create == NULL)
1209 if (evp->sigev_notify != SIGEV_NONE &&
1210 evp->sigev_notify != SIGEV_SIGNAL &&
1211 evp->sigev_notify != SIGEV_THREAD_ID)
1213 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1214 evp->sigev_notify == SIGEV_THREAD_ID) &&
1215 !_SIG_VALID(evp->sigev_signo))
1219 if (p->p_itimers == NULL)
1222 it = uma_zalloc(itimer_zone, M_WAITOK);
1224 it->it_usecount = 0;
1226 timespecclear(&it->it_time.it_value);
1227 timespecclear(&it->it_time.it_interval);
1229 it->it_overrun_last = 0;
1230 it->it_clockid = clock_id;
1231 it->it_timerid = -1;
1233 ksiginfo_init(&it->it_ksi);
1234 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1235 error = CLOCK_CALL(clock_id, timer_create, (it));
1240 if (preset_id != -1) {
1241 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1243 if (p->p_itimers->its_timers[id] != NULL) {
1250 * Find a free timer slot, skipping those reserved
1253 for (id = 3; id < TIMER_MAX; id++)
1254 if (p->p_itimers->its_timers[id] == NULL)
1256 if (id == TIMER_MAX) {
1262 it->it_timerid = id;
1263 p->p_itimers->its_timers[id] = it;
1265 it->it_sigev = *evp;
1267 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1270 case CLOCK_REALTIME:
1271 it->it_sigev.sigev_signo = SIGALRM;
1274 it->it_sigev.sigev_signo = SIGVTALRM;
1277 it->it_sigev.sigev_signo = SIGPROF;
1280 it->it_sigev.sigev_value.sival_int = id;
1283 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1284 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1285 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1286 it->it_ksi.ksi_code = SI_TIMER;
1287 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1288 it->it_ksi.ksi_timerid = id;
1296 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1298 uma_zfree(itimer_zone, it);
1302 #ifndef _SYS_SYSPROTO_H_
1303 struct ktimer_delete_args {
1308 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1311 return (kern_ktimer_delete(td, uap->timerid));
1314 static struct itimer *
1315 itimer_find(struct proc *p, int timerid)
1319 PROC_LOCK_ASSERT(p, MA_OWNED);
1320 if ((p->p_itimers == NULL) ||
1321 (timerid < 0) || (timerid >= TIMER_MAX) ||
1322 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1326 if ((it->it_flags & ITF_DELETING) != 0) {
1334 kern_ktimer_delete(struct thread *td, int timerid)
1336 struct proc *p = td->td_proc;
1340 it = itimer_find(p, timerid);
1347 it->it_flags |= ITF_DELETING;
1348 while (it->it_usecount > 0) {
1349 it->it_flags |= ITF_WANTED;
1350 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1352 it->it_flags &= ~ITF_WANTED;
1353 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1357 if (KSI_ONQ(&it->it_ksi))
1358 sigqueue_take(&it->it_ksi);
1359 p->p_itimers->its_timers[timerid] = NULL;
1361 uma_zfree(itimer_zone, it);
1365 #ifndef _SYS_SYSPROTO_H_
1366 struct ktimer_settime_args {
1369 const struct itimerspec * value;
1370 struct itimerspec * ovalue;
1374 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1376 struct itimerspec val, oval, *ovalp;
1379 error = copyin(uap->value, &val, sizeof(val));
1382 ovalp = uap->ovalue != NULL ? &oval : NULL;
1383 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1384 if (error == 0 && uap->ovalue != NULL)
1385 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1390 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1391 struct itimerspec *val, struct itimerspec *oval)
1399 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1405 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1413 #ifndef _SYS_SYSPROTO_H_
1414 struct ktimer_gettime_args {
1416 struct itimerspec * value;
1420 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1422 struct itimerspec val;
1425 error = kern_ktimer_gettime(td, uap->timerid, &val);
1427 error = copyout(&val, uap->value, sizeof(val));
1432 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1440 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1446 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1453 #ifndef _SYS_SYSPROTO_H_
1454 struct timer_getoverrun_args {
1459 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1462 return (kern_ktimer_getoverrun(td, uap->timerid));
1466 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1468 struct proc *p = td->td_proc;
1474 (it = itimer_find(p, timer_id)) == NULL) {
1478 td->td_retval[0] = it->it_overrun_last;
1487 realtimer_create(struct itimer *it)
1489 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1494 realtimer_delete(struct itimer *it)
1496 mtx_assert(&it->it_mtx, MA_OWNED);
1499 * clear timer's value and interval to tell realtimer_expire
1500 * to not rearm the timer.
1502 timespecclear(&it->it_time.it_value);
1503 timespecclear(&it->it_time.it_interval);
1505 callout_drain(&it->it_callout);
1511 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1513 struct timespec cts;
1515 mtx_assert(&it->it_mtx, MA_OWNED);
1517 realtimer_clocktime(it->it_clockid, &cts);
1518 *ovalue = it->it_time;
1519 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1520 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1521 if (ovalue->it_value.tv_sec < 0 ||
1522 (ovalue->it_value.tv_sec == 0 &&
1523 ovalue->it_value.tv_nsec == 0)) {
1524 ovalue->it_value.tv_sec = 0;
1525 ovalue->it_value.tv_nsec = 1;
1532 realtimer_settime(struct itimer *it, int flags,
1533 struct itimerspec *value, struct itimerspec *ovalue)
1535 struct timespec cts, ts;
1537 struct itimerspec val;
1539 mtx_assert(&it->it_mtx, MA_OWNED);
1542 if (itimespecfix(&val.it_value))
1545 if (timespecisset(&val.it_value)) {
1546 if (itimespecfix(&val.it_interval))
1549 timespecclear(&val.it_interval);
1553 realtimer_gettime(it, ovalue);
1556 if (timespecisset(&val.it_value)) {
1557 realtimer_clocktime(it->it_clockid, &cts);
1559 if ((flags & TIMER_ABSTIME) == 0) {
1560 /* Convert to absolute time. */
1561 timespecadd(&it->it_time.it_value, &cts,
1562 &it->it_time.it_value);
1564 timespecsub(&ts, &cts, &ts);
1566 * We don't care if ts is negative, tztohz will
1570 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1571 callout_reset(&it->it_callout, tvtohz(&tv),
1572 realtimer_expire, it);
1574 callout_stop(&it->it_callout);
1581 realtimer_clocktime(clockid_t id, struct timespec *ts)
1583 if (id == CLOCK_REALTIME)
1585 else /* CLOCK_MONOTONIC */
1590 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1594 PROC_LOCK_ASSERT(p, MA_OWNED);
1595 it = itimer_find(p, timerid);
1597 ksi->ksi_overrun = it->it_overrun;
1598 it->it_overrun_last = it->it_overrun;
1607 itimespecfix(struct timespec *ts)
1610 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1612 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1613 ts->tv_nsec = tick * 1000;
1617 /* Timeout callback for realtime timer */
1619 realtimer_expire(void *arg)
1621 struct timespec cts, ts;
1625 it = (struct itimer *)arg;
1627 realtimer_clocktime(it->it_clockid, &cts);
1628 /* Only fire if time is reached. */
1629 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1630 if (timespecisset(&it->it_time.it_interval)) {
1631 timespecadd(&it->it_time.it_value,
1632 &it->it_time.it_interval,
1633 &it->it_time.it_value);
1634 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1635 if (it->it_overrun < INT_MAX)
1638 it->it_ksi.ksi_errno = ERANGE;
1639 timespecadd(&it->it_time.it_value,
1640 &it->it_time.it_interval,
1641 &it->it_time.it_value);
1644 /* single shot timer ? */
1645 timespecclear(&it->it_time.it_value);
1647 if (timespecisset(&it->it_time.it_value)) {
1648 timespecsub(&it->it_time.it_value, &cts, &ts);
1649 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1650 callout_reset(&it->it_callout, tvtohz(&tv),
1651 realtimer_expire, it);
1658 } else if (timespecisset(&it->it_time.it_value)) {
1659 ts = it->it_time.it_value;
1660 timespecsub(&ts, &cts, &ts);
1661 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1662 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1668 itimer_fire(struct itimer *it)
1670 struct proc *p = it->it_proc;
1673 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1674 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1675 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1677 timespecclear(&it->it_time.it_value);
1678 timespecclear(&it->it_time.it_interval);
1679 callout_stop(&it->it_callout);
1683 if (!KSI_ONQ(&it->it_ksi)) {
1684 it->it_ksi.ksi_errno = 0;
1685 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1686 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1688 if (it->it_overrun < INT_MAX)
1691 it->it_ksi.ksi_errno = ERANGE;
1698 itimers_alloc(struct proc *p)
1700 struct itimers *its;
1703 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1704 LIST_INIT(&its->its_virtual);
1705 LIST_INIT(&its->its_prof);
1706 TAILQ_INIT(&its->its_worklist);
1707 for (i = 0; i < TIMER_MAX; i++)
1708 its->its_timers[i] = NULL;
1710 if (p->p_itimers == NULL) {
1716 free(its, M_SUBPROC);
1721 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1723 itimers_event_hook_exit(arg, p);
1726 /* Clean up timers when some process events are being triggered. */
1728 itimers_event_hook_exit(void *arg, struct proc *p)
1730 struct itimers *its;
1732 int event = (int)(intptr_t)arg;
1735 if (p->p_itimers != NULL) {
1737 for (i = 0; i < MAX_CLOCKS; ++i) {
1738 if (posix_clocks[i].event_hook != NULL)
1739 CLOCK_CALL(i, event_hook, (p, i, event));
1742 * According to susv3, XSI interval timers should be inherited
1745 if (event == ITIMER_EV_EXEC)
1747 else if (event == ITIMER_EV_EXIT)
1750 panic("unhandled event");
1751 for (; i < TIMER_MAX; ++i) {
1752 if ((it = its->its_timers[i]) != NULL)
1753 kern_ktimer_delete(curthread, i);
1755 if (its->its_timers[0] == NULL &&
1756 its->its_timers[1] == NULL &&
1757 its->its_timers[2] == NULL) {
1758 free(its, M_SUBPROC);
1759 p->p_itimers = NULL;