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);
122 settime(struct thread *td, struct timeval *tv)
124 struct timeval delta, tv1, tv2;
125 static struct timeval maxtime, laststep;
130 timevalsub(&delta, &tv1);
133 * If the system is secure, we do not allow the time to be
134 * set to a value earlier than 1 second less than the highest
135 * time we have yet seen. The worst a miscreant can do in
136 * this circumstance is "freeze" time. He couldn't go
139 * We similarly do not allow the clock to be stepped more
140 * than one second, nor more than once per second. This allows
141 * a miscreant to make the clock march double-time, but no worse.
143 if (securelevel_gt(td->td_ucred, 1) != 0) {
144 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
146 * Update maxtime to latest time we've seen.
148 if (tv1.tv_sec > maxtime.tv_sec)
151 timevalsub(&tv2, &maxtime);
152 if (tv2.tv_sec < -1) {
153 tv->tv_sec = maxtime.tv_sec - 1;
154 printf("Time adjustment clamped to -1 second\n");
157 if (tv1.tv_sec == laststep.tv_sec)
159 if (delta.tv_sec > 1) {
160 tv->tv_sec = tv1.tv_sec + 1;
161 printf("Time adjustment clamped to +1 second\n");
167 ts.tv_sec = tv->tv_sec;
168 ts.tv_nsec = tv->tv_usec * 1000;
174 #ifndef _SYS_SYSPROTO_H_
175 struct clock_getcpuclockid2_args {
183 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
188 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
190 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
195 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
204 case CPUCLOCK_WHICH_PID:
206 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
212 pid = td->td_proc->p_pid;
214 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
216 case CPUCLOCK_WHICH_TID:
217 tid = id == 0 ? td->td_tid : id;
218 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
225 #ifndef _SYS_SYSPROTO_H_
226 struct clock_gettime_args {
233 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
238 error = kern_clock_gettime(td, uap->clock_id, &ats);
240 error = copyout(&ats, uap->tp, sizeof(ats));
246 cputick2timespec(uint64_t runtime, struct timespec *ats)
248 runtime = cputick2usec(runtime);
249 ats->tv_sec = runtime / 1000000;
250 ats->tv_nsec = runtime % 1000000 * 1000;
254 kern_thread_cputime(struct thread *targettd, struct timespec *ats)
256 uint64_t runtime, curtime, switchtime;
258 if (targettd == NULL) { /* current thread */
260 switchtime = PCPU_GET(switchtime);
261 curtime = cpu_ticks();
262 runtime = curthread->td_runtime;
264 runtime += curtime - switchtime;
266 PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
267 thread_lock(targettd);
268 runtime = targettd->td_runtime;
269 thread_unlock(targettd);
271 cputick2timespec(runtime, ats);
275 kern_process_cputime(struct proc *targetp, struct timespec *ats)
280 PROC_LOCK_ASSERT(targetp, MA_OWNED);
281 PROC_STATLOCK(targetp);
282 rufetch(targetp, &ru);
283 runtime = targetp->p_rux.rux_runtime;
284 if (curthread->td_proc == targetp)
285 runtime += cpu_ticks() - PCPU_GET(switchtime);
286 PROC_STATUNLOCK(targetp);
287 cputick2timespec(runtime, ats);
291 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
300 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
301 tid = clock_id & CPUCLOCK_ID_MASK;
302 td2 = tdfind(tid, p->p_pid);
305 kern_thread_cputime(td2, ats);
306 PROC_UNLOCK(td2->td_proc);
308 pid = clock_id & CPUCLOCK_ID_MASK;
309 error = pget(pid, PGET_CANSEE, &p2);
312 kern_process_cputime(p2, ats);
319 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
321 struct timeval sys, user;
326 case CLOCK_REALTIME: /* Default to precise. */
327 case CLOCK_REALTIME_PRECISE:
330 case CLOCK_REALTIME_FAST:
336 calcru(p, &user, &sys);
339 TIMEVAL_TO_TIMESPEC(&user, ats);
344 calcru(p, &user, &sys);
347 timevaladd(&user, &sys);
348 TIMEVAL_TO_TIMESPEC(&user, ats);
350 case CLOCK_MONOTONIC: /* Default to precise. */
351 case CLOCK_MONOTONIC_PRECISE:
353 case CLOCK_UPTIME_PRECISE:
356 case CLOCK_UPTIME_FAST:
357 case CLOCK_MONOTONIC_FAST:
361 ats->tv_sec = time_second;
364 case CLOCK_THREAD_CPUTIME_ID:
365 kern_thread_cputime(NULL, ats);
367 case CLOCK_PROCESS_CPUTIME_ID:
369 kern_process_cputime(p, ats);
373 if ((int)clock_id >= 0)
375 return (get_cputime(td, clock_id, ats));
380 #ifndef _SYS_SYSPROTO_H_
381 struct clock_settime_args {
383 const struct timespec *tp;
388 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
393 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
395 return (kern_clock_settime(td, uap->clock_id, &ats));
398 static int allow_insane_settime = 0;
399 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
400 &allow_insane_settime, 0,
401 "do not perform possibly restrictive checks on settime(2) args");
404 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
409 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
411 if (clock_id != CLOCK_REALTIME)
413 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
416 if (!allow_insane_settime &&
417 (ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60 ||
418 ats->tv_sec < utc_offset()))
420 /* XXX Don't convert nsec->usec and back */
421 TIMESPEC_TO_TIMEVAL(&atv, ats);
422 error = settime(td, &atv);
426 #ifndef _SYS_SYSPROTO_H_
427 struct clock_getres_args {
433 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
441 error = kern_clock_getres(td, uap->clock_id, &ts);
443 error = copyout(&ts, uap->tp, sizeof(ts));
448 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
454 case CLOCK_REALTIME_FAST:
455 case CLOCK_REALTIME_PRECISE:
456 case CLOCK_MONOTONIC:
457 case CLOCK_MONOTONIC_FAST:
458 case CLOCK_MONOTONIC_PRECISE:
460 case CLOCK_UPTIME_FAST:
461 case CLOCK_UPTIME_PRECISE:
463 * Round up the result of the division cheaply by adding 1.
464 * Rounding up is especially important if rounding down
465 * would give 0. Perfect rounding is unimportant.
467 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
471 /* Accurately round up here because we can do so cheaply. */
472 ts->tv_nsec = howmany(1000000000, hz);
478 case CLOCK_THREAD_CPUTIME_ID:
479 case CLOCK_PROCESS_CPUTIME_ID:
481 /* sync with cputick2usec */
482 ts->tv_nsec = 1000000 / cpu_tickrate();
483 if (ts->tv_nsec == 0)
487 if ((int)clock_id < 0)
495 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
498 return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
502 static uint8_t nanowait[MAXCPU];
505 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
506 const struct timespec *rqt, struct timespec *rmt)
508 struct timespec ts, now;
509 sbintime_t sbt, sbtt, prec, tmp;
514 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
516 if ((flags & ~TIMER_ABSTIME) != 0)
520 case CLOCK_REALTIME_PRECISE:
521 case CLOCK_REALTIME_FAST:
523 is_abs_real = (flags & TIMER_ABSTIME) != 0;
525 case CLOCK_MONOTONIC:
526 case CLOCK_MONOTONIC_PRECISE:
527 case CLOCK_MONOTONIC_FAST:
529 case CLOCK_UPTIME_PRECISE:
530 case CLOCK_UPTIME_FAST:
535 case CLOCK_PROCESS_CPUTIME_ID:
537 case CLOCK_THREAD_CPUTIME_ID:
543 if ((flags & TIMER_ABSTIME) != 0) {
546 atomic_load_acq_int(&rtc_generation);
547 error = kern_clock_gettime(td, clock_id, &now);
548 KASSERT(error == 0, ("kern_clock_gettime: %d", error));
549 timespecsub(&ts, &now, &ts);
551 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
555 if (ts.tv_sec > INT32_MAX / 2) {
556 over = ts.tv_sec - INT32_MAX / 2;
563 if (TIMESEL(&sbt, tmp))
566 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
567 sbt, prec, C_ABSOLUTE);
568 } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
570 if (error != EWOULDBLOCK) {
571 if (TIMESEL(&sbtt, tmp))
575 if (error == ERESTART)
577 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
578 ts = sbttots(sbt - sbtt);
589 #ifndef _SYS_SYSPROTO_H_
590 struct nanosleep_args {
591 struct timespec *rqtp;
592 struct timespec *rmtp;
597 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
600 return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
601 uap->rqtp, uap->rmtp));
604 #ifndef _SYS_SYSPROTO_H_
605 struct clock_nanosleep_args {
608 struct timespec *rqtp;
609 struct timespec *rmtp;
614 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
618 error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
620 return (kern_posix_error(td, error));
624 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
625 const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
627 struct timespec rmt, rqt;
630 error = copyin(ua_rqtp, &rqt, sizeof(rqt));
633 error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
634 if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
635 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
642 #ifndef _SYS_SYSPROTO_H_
643 struct gettimeofday_args {
645 struct timezone *tzp;
650 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
658 error = copyout(&atv, uap->tp, sizeof (atv));
660 if (error == 0 && uap->tzp != NULL) {
661 rtz.tz_minuteswest = 0;
663 error = copyout(&rtz, uap->tzp, sizeof (rtz));
668 #ifndef _SYS_SYSPROTO_H_
669 struct settimeofday_args {
671 struct timezone *tzp;
676 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
678 struct timeval atv, *tvp;
679 struct timezone atz, *tzp;
683 error = copyin(uap->tv, &atv, sizeof(atv));
690 error = copyin(uap->tzp, &atz, sizeof(atz));
696 return (kern_settimeofday(td, tvp, tzp));
700 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
704 error = priv_check(td, PRIV_SETTIMEOFDAY);
707 /* Verify all parameters before changing time. */
709 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
712 error = settime(td, tv);
718 * Get value of an interval timer. The process virtual and profiling virtual
719 * time timers are kept in the p_stats area, since they can be swapped out.
720 * These are kept internally in the way they are specified externally: in
721 * time until they expire.
723 * The real time interval timer is kept in the process table slot for the
724 * process, and its value (it_value) is kept as an absolute time rather than
725 * as a delta, so that it is easy to keep periodic real-time signals from
728 * Virtual time timers are processed in the hardclock() routine of
729 * kern_clock.c. The real time timer is processed by a timeout routine,
730 * called from the softclock() routine. Since a callout may be delayed in
731 * real time due to interrupt processing in the system, it is possible for
732 * the real time timeout routine (realitexpire, given below), to be delayed
733 * in real time past when it is supposed to occur. It does not suffice,
734 * therefore, to reload the real timer .it_value from the real time timers
735 * .it_interval. Rather, we compute the next time in absolute time the timer
738 #ifndef _SYS_SYSPROTO_H_
739 struct getitimer_args {
741 struct itimerval *itv;
745 sys_getitimer(struct thread *td, struct getitimer_args *uap)
747 struct itimerval aitv;
750 error = kern_getitimer(td, uap->which, &aitv);
753 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
757 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
759 struct proc *p = td->td_proc;
762 if (which > ITIMER_PROF)
765 if (which == ITIMER_REAL) {
767 * Convert from absolute to relative time in .it_value
768 * part of real time timer. If time for real time timer
769 * has passed return 0, else return difference between
770 * current time and time for the timer to go off.
773 *aitv = p->p_realtimer;
775 if (timevalisset(&aitv->it_value)) {
777 if (timevalcmp(&aitv->it_value, &ctv, <))
778 timevalclear(&aitv->it_value);
780 timevalsub(&aitv->it_value, &ctv);
784 *aitv = p->p_stats->p_timer[which];
788 if (KTRPOINT(td, KTR_STRUCT))
794 #ifndef _SYS_SYSPROTO_H_
795 struct setitimer_args {
797 struct itimerval *itv, *oitv;
801 sys_setitimer(struct thread *td, struct setitimer_args *uap)
803 struct itimerval aitv, oitv;
806 if (uap->itv == NULL) {
807 uap->itv = uap->oitv;
808 return (sys_getitimer(td, (struct getitimer_args *)uap));
811 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
813 error = kern_setitimer(td, uap->which, &aitv, &oitv);
814 if (error != 0 || uap->oitv == NULL)
816 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
820 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
821 struct itimerval *oitv)
823 struct proc *p = td->td_proc;
828 return (kern_getitimer(td, which, oitv));
830 if (which > ITIMER_PROF)
833 if (KTRPOINT(td, KTR_STRUCT))
836 if (itimerfix(&aitv->it_value) ||
837 aitv->it_value.tv_sec > INT32_MAX / 2)
839 if (!timevalisset(&aitv->it_value))
840 timevalclear(&aitv->it_interval);
841 else if (itimerfix(&aitv->it_interval) ||
842 aitv->it_interval.tv_sec > INT32_MAX / 2)
845 if (which == ITIMER_REAL) {
847 if (timevalisset(&p->p_realtimer.it_value))
848 callout_stop(&p->p_itcallout);
850 if (timevalisset(&aitv->it_value)) {
851 pr = tvtosbt(aitv->it_value) >> tc_precexp;
852 timevaladd(&aitv->it_value, &ctv);
853 sbt = tvtosbt(aitv->it_value);
854 callout_reset_sbt(&p->p_itcallout, sbt, pr,
855 realitexpire, p, C_ABSOLUTE);
857 *oitv = p->p_realtimer;
858 p->p_realtimer = *aitv;
860 if (timevalisset(&oitv->it_value)) {
861 if (timevalcmp(&oitv->it_value, &ctv, <))
862 timevalclear(&oitv->it_value);
864 timevalsub(&oitv->it_value, &ctv);
867 if (aitv->it_interval.tv_sec == 0 &&
868 aitv->it_interval.tv_usec != 0 &&
869 aitv->it_interval.tv_usec < tick)
870 aitv->it_interval.tv_usec = tick;
871 if (aitv->it_value.tv_sec == 0 &&
872 aitv->it_value.tv_usec != 0 &&
873 aitv->it_value.tv_usec < tick)
874 aitv->it_value.tv_usec = tick;
876 *oitv = p->p_stats->p_timer[which];
877 p->p_stats->p_timer[which] = *aitv;
881 if (KTRPOINT(td, KTR_STRUCT))
888 * Real interval timer expired:
889 * send process whose timer expired an alarm signal.
890 * If time is not set up to reload, then just return.
891 * Else compute next time timer should go off which is > current time.
892 * This is where delay in processing this timeout causes multiple
893 * SIGALRM calls to be compressed into one.
894 * tvtohz() always adds 1 to allow for the time until the next clock
895 * interrupt being strictly less than 1 clock tick, but we don't want
896 * that here since we want to appear to be in sync with the clock
897 * interrupt even when we're delayed.
900 realitexpire(void *arg)
906 p = (struct proc *)arg;
907 kern_psignal(p, SIGALRM);
908 if (!timevalisset(&p->p_realtimer.it_interval)) {
909 timevalclear(&p->p_realtimer.it_value);
910 if (p->p_flag & P_WEXIT)
911 wakeup(&p->p_itcallout);
914 isbt = tvtosbt(p->p_realtimer.it_interval);
915 if (isbt >= sbt_timethreshold)
916 getmicrouptime(&ctv);
920 timevaladd(&p->p_realtimer.it_value,
921 &p->p_realtimer.it_interval);
922 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
923 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
924 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
928 * Check that a proposed value to load into the .it_value or
929 * .it_interval part of an interval timer is acceptable, and
930 * fix it to have at least minimal value (i.e. if it is less
931 * than the resolution of the clock, round it up.)
934 itimerfix(struct timeval *tv)
937 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
939 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
940 tv->tv_usec < (u_int)tick / 16)
941 tv->tv_usec = (u_int)tick / 16;
946 * Decrement an interval timer by a specified number
947 * of microseconds, which must be less than a second,
948 * i.e. < 1000000. If the timer expires, then reload
949 * it. In this case, carry over (usec - old value) to
950 * reduce the value reloaded into the timer so that
951 * the timer does not drift. This routine assumes
952 * that it is called in a context where the timers
953 * on which it is operating cannot change in value.
956 itimerdecr(struct itimerval *itp, int usec)
959 if (itp->it_value.tv_usec < usec) {
960 if (itp->it_value.tv_sec == 0) {
961 /* expired, and already in next interval */
962 usec -= itp->it_value.tv_usec;
965 itp->it_value.tv_usec += 1000000;
966 itp->it_value.tv_sec--;
968 itp->it_value.tv_usec -= usec;
970 if (timevalisset(&itp->it_value))
972 /* expired, exactly at end of interval */
974 if (timevalisset(&itp->it_interval)) {
975 itp->it_value = itp->it_interval;
976 itp->it_value.tv_usec -= usec;
977 if (itp->it_value.tv_usec < 0) {
978 itp->it_value.tv_usec += 1000000;
979 itp->it_value.tv_sec--;
982 itp->it_value.tv_usec = 0; /* sec is already 0 */
987 * Add and subtract routines for timevals.
988 * N.B.: subtract routine doesn't deal with
989 * results which are before the beginning,
990 * it just gets very confused in this case.
994 timevaladd(struct timeval *t1, const struct timeval *t2)
997 t1->tv_sec += t2->tv_sec;
998 t1->tv_usec += t2->tv_usec;
1003 timevalsub(struct timeval *t1, const struct timeval *t2)
1006 t1->tv_sec -= t2->tv_sec;
1007 t1->tv_usec -= t2->tv_usec;
1012 timevalfix(struct timeval *t1)
1015 if (t1->tv_usec < 0) {
1017 t1->tv_usec += 1000000;
1019 if (t1->tv_usec >= 1000000) {
1021 t1->tv_usec -= 1000000;
1026 * ratecheck(): simple time-based rate-limit checking.
1029 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1031 struct timeval tv, delta;
1034 getmicrouptime(&tv); /* NB: 10ms precision */
1036 timevalsub(&delta, lasttime);
1039 * check for 0,0 is so that the message will be seen at least once,
1040 * even if interval is huge.
1042 if (timevalcmp(&delta, mininterval, >=) ||
1043 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1052 * ppsratecheck(): packets (or events) per second limitation.
1054 * Return 0 if the limit is to be enforced (e.g. the caller
1055 * should drop a packet because of the rate limitation).
1057 * maxpps of 0 always causes zero to be returned. maxpps of -1
1058 * always causes 1 to be returned; this effectively defeats rate
1061 * Note that we maintain the struct timeval for compatibility
1062 * with other bsd systems. We reuse the storage and just monitor
1063 * clock ticks for minimal overhead.
1066 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1071 * Reset the last time and counter if this is the first call
1072 * or more than a second has passed since the last update of
1076 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1077 lasttime->tv_sec = now;
1079 return (maxpps != 0);
1081 (*curpps)++; /* NB: ignore potential overflow */
1082 return (maxpps < 0 || *curpps <= maxpps);
1089 struct kclock rt_clock = {
1090 .timer_create = realtimer_create,
1091 .timer_delete = realtimer_delete,
1092 .timer_settime = realtimer_settime,
1093 .timer_gettime = realtimer_gettime,
1097 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1098 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1099 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1100 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1101 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1102 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1103 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1104 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1105 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1106 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1107 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1111 register_posix_clock(int clockid, struct kclock *clk)
1113 if ((unsigned)clockid >= MAX_CLOCKS) {
1114 printf("%s: invalid clockid\n", __func__);
1117 posix_clocks[clockid] = *clk;
1122 itimer_init(void *mem, int size, int flags)
1126 it = (struct itimer *)mem;
1127 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1132 itimer_fini(void *mem, int size)
1136 it = (struct itimer *)mem;
1137 mtx_destroy(&it->it_mtx);
1141 itimer_enter(struct itimer *it)
1144 mtx_assert(&it->it_mtx, MA_OWNED);
1149 itimer_leave(struct itimer *it)
1152 mtx_assert(&it->it_mtx, MA_OWNED);
1153 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1155 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1159 #ifndef _SYS_SYSPROTO_H_
1160 struct ktimer_create_args {
1162 struct sigevent * evp;
1167 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1169 struct sigevent *evp, ev;
1173 if (uap->evp == NULL) {
1176 error = copyin(uap->evp, &ev, sizeof(ev));
1181 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1183 error = copyout(&id, uap->timerid, sizeof(int));
1185 kern_ktimer_delete(td, id);
1191 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1192 int *timerid, int preset_id)
1194 struct proc *p = td->td_proc;
1199 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1202 if (posix_clocks[clock_id].timer_create == NULL)
1206 if (evp->sigev_notify != SIGEV_NONE &&
1207 evp->sigev_notify != SIGEV_SIGNAL &&
1208 evp->sigev_notify != SIGEV_THREAD_ID)
1210 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1211 evp->sigev_notify == SIGEV_THREAD_ID) &&
1212 !_SIG_VALID(evp->sigev_signo))
1216 if (p->p_itimers == NULL)
1219 it = uma_zalloc(itimer_zone, M_WAITOK);
1221 it->it_usecount = 0;
1223 timespecclear(&it->it_time.it_value);
1224 timespecclear(&it->it_time.it_interval);
1226 it->it_overrun_last = 0;
1227 it->it_clockid = clock_id;
1228 it->it_timerid = -1;
1230 ksiginfo_init(&it->it_ksi);
1231 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1232 error = CLOCK_CALL(clock_id, timer_create, (it));
1237 if (preset_id != -1) {
1238 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1240 if (p->p_itimers->its_timers[id] != NULL) {
1247 * Find a free timer slot, skipping those reserved
1250 for (id = 3; id < TIMER_MAX; id++)
1251 if (p->p_itimers->its_timers[id] == NULL)
1253 if (id == TIMER_MAX) {
1259 it->it_timerid = id;
1260 p->p_itimers->its_timers[id] = it;
1262 it->it_sigev = *evp;
1264 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1267 case CLOCK_REALTIME:
1268 it->it_sigev.sigev_signo = SIGALRM;
1271 it->it_sigev.sigev_signo = SIGVTALRM;
1274 it->it_sigev.sigev_signo = SIGPROF;
1277 it->it_sigev.sigev_value.sival_int = id;
1280 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1281 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1282 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1283 it->it_ksi.ksi_code = SI_TIMER;
1284 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1285 it->it_ksi.ksi_timerid = id;
1293 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1295 uma_zfree(itimer_zone, it);
1299 #ifndef _SYS_SYSPROTO_H_
1300 struct ktimer_delete_args {
1305 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1308 return (kern_ktimer_delete(td, uap->timerid));
1311 static struct itimer *
1312 itimer_find(struct proc *p, int timerid)
1316 PROC_LOCK_ASSERT(p, MA_OWNED);
1317 if ((p->p_itimers == NULL) ||
1318 (timerid < 0) || (timerid >= TIMER_MAX) ||
1319 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1323 if ((it->it_flags & ITF_DELETING) != 0) {
1331 kern_ktimer_delete(struct thread *td, int timerid)
1333 struct proc *p = td->td_proc;
1337 it = itimer_find(p, timerid);
1344 it->it_flags |= ITF_DELETING;
1345 while (it->it_usecount > 0) {
1346 it->it_flags |= ITF_WANTED;
1347 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1349 it->it_flags &= ~ITF_WANTED;
1350 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1354 if (KSI_ONQ(&it->it_ksi))
1355 sigqueue_take(&it->it_ksi);
1356 p->p_itimers->its_timers[timerid] = NULL;
1358 uma_zfree(itimer_zone, it);
1362 #ifndef _SYS_SYSPROTO_H_
1363 struct ktimer_settime_args {
1366 const struct itimerspec * value;
1367 struct itimerspec * ovalue;
1371 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1373 struct itimerspec val, oval, *ovalp;
1376 error = copyin(uap->value, &val, sizeof(val));
1379 ovalp = uap->ovalue != NULL ? &oval : NULL;
1380 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1381 if (error == 0 && uap->ovalue != NULL)
1382 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1387 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1388 struct itimerspec *val, struct itimerspec *oval)
1396 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1402 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1410 #ifndef _SYS_SYSPROTO_H_
1411 struct ktimer_gettime_args {
1413 struct itimerspec * value;
1417 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1419 struct itimerspec val;
1422 error = kern_ktimer_gettime(td, uap->timerid, &val);
1424 error = copyout(&val, uap->value, sizeof(val));
1429 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1437 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1443 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1450 #ifndef _SYS_SYSPROTO_H_
1451 struct timer_getoverrun_args {
1456 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1459 return (kern_ktimer_getoverrun(td, uap->timerid));
1463 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1465 struct proc *p = td->td_proc;
1471 (it = itimer_find(p, timer_id)) == NULL) {
1475 td->td_retval[0] = it->it_overrun_last;
1484 realtimer_create(struct itimer *it)
1486 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1491 realtimer_delete(struct itimer *it)
1493 mtx_assert(&it->it_mtx, MA_OWNED);
1496 * clear timer's value and interval to tell realtimer_expire
1497 * to not rearm the timer.
1499 timespecclear(&it->it_time.it_value);
1500 timespecclear(&it->it_time.it_interval);
1502 callout_drain(&it->it_callout);
1508 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1510 struct timespec cts;
1512 mtx_assert(&it->it_mtx, MA_OWNED);
1514 realtimer_clocktime(it->it_clockid, &cts);
1515 *ovalue = it->it_time;
1516 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1517 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1518 if (ovalue->it_value.tv_sec < 0 ||
1519 (ovalue->it_value.tv_sec == 0 &&
1520 ovalue->it_value.tv_nsec == 0)) {
1521 ovalue->it_value.tv_sec = 0;
1522 ovalue->it_value.tv_nsec = 1;
1529 realtimer_settime(struct itimer *it, int flags,
1530 struct itimerspec *value, struct itimerspec *ovalue)
1532 struct timespec cts, ts;
1534 struct itimerspec val;
1536 mtx_assert(&it->it_mtx, MA_OWNED);
1539 if (itimespecfix(&val.it_value))
1542 if (timespecisset(&val.it_value)) {
1543 if (itimespecfix(&val.it_interval))
1546 timespecclear(&val.it_interval);
1550 realtimer_gettime(it, ovalue);
1553 if (timespecisset(&val.it_value)) {
1554 realtimer_clocktime(it->it_clockid, &cts);
1556 if ((flags & TIMER_ABSTIME) == 0) {
1557 /* Convert to absolute time. */
1558 timespecadd(&it->it_time.it_value, &cts,
1559 &it->it_time.it_value);
1561 timespecsub(&ts, &cts, &ts);
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 &it->it_time.it_value);
1631 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1632 if (it->it_overrun < INT_MAX)
1635 it->it_ksi.ksi_errno = ERANGE;
1636 timespecadd(&it->it_time.it_value,
1637 &it->it_time.it_interval,
1638 &it->it_time.it_value);
1641 /* single shot timer ? */
1642 timespecclear(&it->it_time.it_value);
1644 if (timespecisset(&it->it_time.it_value)) {
1645 timespecsub(&it->it_time.it_value, &cts, &ts);
1646 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1647 callout_reset(&it->it_callout, tvtohz(&tv),
1648 realtimer_expire, it);
1655 } else if (timespecisset(&it->it_time.it_value)) {
1656 ts = it->it_time.it_value;
1657 timespecsub(&ts, &cts, &ts);
1658 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1659 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1665 itimer_fire(struct itimer *it)
1667 struct proc *p = it->it_proc;
1670 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1671 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1672 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1674 timespecclear(&it->it_time.it_value);
1675 timespecclear(&it->it_time.it_interval);
1676 callout_stop(&it->it_callout);
1680 if (!KSI_ONQ(&it->it_ksi)) {
1681 it->it_ksi.ksi_errno = 0;
1682 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1683 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1685 if (it->it_overrun < INT_MAX)
1688 it->it_ksi.ksi_errno = ERANGE;
1695 itimers_alloc(struct proc *p)
1697 struct itimers *its;
1700 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1701 LIST_INIT(&its->its_virtual);
1702 LIST_INIT(&its->its_prof);
1703 TAILQ_INIT(&its->its_worklist);
1704 for (i = 0; i < TIMER_MAX; i++)
1705 its->its_timers[i] = NULL;
1707 if (p->p_itimers == NULL) {
1713 free(its, M_SUBPROC);
1718 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1720 itimers_event_hook_exit(arg, p);
1723 /* Clean up timers when some process events are being triggered. */
1725 itimers_event_hook_exit(void *arg, struct proc *p)
1727 struct itimers *its;
1729 int event = (int)(intptr_t)arg;
1732 if (p->p_itimers != NULL) {
1734 for (i = 0; i < MAX_CLOCKS; ++i) {
1735 if (posix_clocks[i].event_hook != NULL)
1736 CLOCK_CALL(i, event_hook, (p, i, event));
1739 * According to susv3, XSI interval timers should be inherited
1742 if (event == ITIMER_EV_EXEC)
1744 else if (event == ITIMER_EV_EXIT)
1747 panic("unhandled event");
1748 for (; i < TIMER_MAX; ++i) {
1749 if ((it = its->its_timers[i]) != NULL)
1750 kern_ktimer_delete(curthread, i);
1752 if (its->its_timers[0] == NULL &&
1753 its->its_timers[1] == NULL &&
1754 its->its_timers[2] == NULL) {
1755 free(its, M_SUBPROC);
1756 p->p_itimers = NULL;