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/resourcevar.h>
47 #include <sys/signalvar.h>
48 #include <sys/kernel.h>
49 #include <sys/sleepqueue.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysctl.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 #define NS_PER_SEC 1000000000
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 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 *);
109 static void realtimer_expire_l(struct itimer *it, bool proc_locked);
111 static void realitexpire(void *arg);
113 static int register_posix_clock(int, const struct kclock *);
114 static void itimer_fire(struct itimer *it);
115 static int itimespecfix(struct timespec *ts);
117 #define CLOCK_CALL(clock, call, arglist) \
118 ((*posix_clocks[clock].call) arglist)
120 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 (!timespecvalid_interval(ats))
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 = NS_PER_SEC / tc_getfrequency() + 1;
471 /* Accurately round up here because we can do so cheaply. */
472 ts->tv_nsec = howmany(NS_PER_SEC, 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 >= NS_PER_SEC)
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 realitexpire_reset_callout(struct proc *p, sbintime_t *isbtp)
892 prec = isbtp == NULL ? tvtosbt(p->p_realtimer.it_interval) : *isbtp;
893 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
894 prec >> tc_precexp, realitexpire, p, C_ABSOLUTE);
898 itimer_proc_continue(struct proc *p)
904 PROC_LOCK_ASSERT(p, MA_OWNED);
906 if ((p->p_flag2 & P2_ITSTOPPED) != 0) {
907 p->p_flag2 &= ~P2_ITSTOPPED;
909 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >=))
912 realitexpire_reset_callout(p, NULL);
915 if (p->p_itimers != NULL) {
916 for (id = 3; id < TIMER_MAX; id++) {
917 it = p->p_itimers->its_timers[id];
920 if ((it->it_flags & ITF_PSTOPPED) != 0) {
922 if ((it->it_flags & ITF_PSTOPPED) != 0) {
923 it->it_flags &= ~ITF_PSTOPPED;
924 if ((it->it_flags & ITF_DELETING) == 0)
925 realtimer_expire_l(it, true);
934 * Real interval timer expired:
935 * send process whose timer expired an alarm signal.
936 * If time is not set up to reload, then just return.
937 * Else compute next time timer should go off which is > current time.
938 * This is where delay in processing this timeout causes multiple
939 * SIGALRM calls to be compressed into one.
940 * tvtohz() always adds 1 to allow for the time until the next clock
941 * interrupt being strictly less than 1 clock tick, but we don't want
942 * that here since we want to appear to be in sync with the clock
943 * interrupt even when we're delayed.
946 realitexpire(void *arg)
952 p = (struct proc *)arg;
953 kern_psignal(p, SIGALRM);
954 if (!timevalisset(&p->p_realtimer.it_interval)) {
955 timevalclear(&p->p_realtimer.it_value);
959 isbt = tvtosbt(p->p_realtimer.it_interval);
960 if (isbt >= sbt_timethreshold)
961 getmicrouptime(&ctv);
965 timevaladd(&p->p_realtimer.it_value,
966 &p->p_realtimer.it_interval);
967 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
969 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
970 p->p_flag2 |= P2_ITSTOPPED;
974 p->p_flag2 &= ~P2_ITSTOPPED;
975 realitexpire_reset_callout(p, &isbt);
979 * Check that a proposed value to load into the .it_value or
980 * .it_interval part of an interval timer is acceptable, and
981 * fix it to have at least minimal value (i.e. if it is less
982 * than the resolution of the clock, round it up.)
985 itimerfix(struct timeval *tv)
988 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
990 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
991 tv->tv_usec < (u_int)tick / 16)
992 tv->tv_usec = (u_int)tick / 16;
997 * Decrement an interval timer by a specified number
998 * of microseconds, which must be less than a second,
999 * i.e. < 1000000. If the timer expires, then reload
1000 * it. In this case, carry over (usec - old value) to
1001 * reduce the value reloaded into the timer so that
1002 * the timer does not drift. This routine assumes
1003 * that it is called in a context where the timers
1004 * on which it is operating cannot change in value.
1007 itimerdecr(struct itimerval *itp, int usec)
1010 if (itp->it_value.tv_usec < usec) {
1011 if (itp->it_value.tv_sec == 0) {
1012 /* expired, and already in next interval */
1013 usec -= itp->it_value.tv_usec;
1016 itp->it_value.tv_usec += 1000000;
1017 itp->it_value.tv_sec--;
1019 itp->it_value.tv_usec -= usec;
1021 if (timevalisset(&itp->it_value))
1023 /* expired, exactly at end of interval */
1025 if (timevalisset(&itp->it_interval)) {
1026 itp->it_value = itp->it_interval;
1027 itp->it_value.tv_usec -= usec;
1028 if (itp->it_value.tv_usec < 0) {
1029 itp->it_value.tv_usec += 1000000;
1030 itp->it_value.tv_sec--;
1033 itp->it_value.tv_usec = 0; /* sec is already 0 */
1038 * Add and subtract routines for timevals.
1039 * N.B.: subtract routine doesn't deal with
1040 * results which are before the beginning,
1041 * it just gets very confused in this case.
1045 timevaladd(struct timeval *t1, const struct timeval *t2)
1048 t1->tv_sec += t2->tv_sec;
1049 t1->tv_usec += t2->tv_usec;
1054 timevalsub(struct timeval *t1, const struct timeval *t2)
1057 t1->tv_sec -= t2->tv_sec;
1058 t1->tv_usec -= t2->tv_usec;
1063 timevalfix(struct timeval *t1)
1066 if (t1->tv_usec < 0) {
1068 t1->tv_usec += 1000000;
1070 if (t1->tv_usec >= 1000000) {
1072 t1->tv_usec -= 1000000;
1077 * ratecheck(): simple time-based rate-limit checking.
1080 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1082 struct timeval tv, delta;
1085 getmicrouptime(&tv); /* NB: 10ms precision */
1087 timevalsub(&delta, lasttime);
1090 * check for 0,0 is so that the message will be seen at least once,
1091 * even if interval is huge.
1093 if (timevalcmp(&delta, mininterval, >=) ||
1094 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1103 * ppsratecheck(): packets (or events) per second limitation.
1105 * Return 0 if the limit is to be enforced (e.g. the caller
1106 * should drop a packet because of the rate limitation).
1108 * maxpps of 0 always causes zero to be returned. maxpps of -1
1109 * always causes 1 to be returned; this effectively defeats rate
1112 * Note that we maintain the struct timeval for compatibility
1113 * with other bsd systems. We reuse the storage and just monitor
1114 * clock ticks for minimal overhead.
1117 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1122 * Reset the last time and counter if this is the first call
1123 * or more than a second has passed since the last update of
1127 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1128 lasttime->tv_sec = now;
1130 return (maxpps != 0);
1132 (*curpps)++; /* NB: ignore potential overflow */
1133 return (maxpps < 0 || *curpps <= maxpps);
1140 static const struct kclock rt_clock = {
1141 .timer_create = realtimer_create,
1142 .timer_delete = realtimer_delete,
1143 .timer_settime = realtimer_settime,
1144 .timer_gettime = realtimer_gettime,
1147 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1148 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1149 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1150 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1151 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1152 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1153 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1157 register_posix_clock(int clockid, const struct kclock *clk)
1159 if ((unsigned)clockid >= MAX_CLOCKS) {
1160 printf("%s: invalid clockid\n", __func__);
1163 posix_clocks[clockid] = *clk;
1168 itimer_init(void *mem, int size, int flags)
1172 it = (struct itimer *)mem;
1173 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1178 itimer_fini(void *mem, int size)
1182 it = (struct itimer *)mem;
1183 mtx_destroy(&it->it_mtx);
1187 itimer_enter(struct itimer *it)
1190 mtx_assert(&it->it_mtx, MA_OWNED);
1195 itimer_leave(struct itimer *it)
1198 mtx_assert(&it->it_mtx, MA_OWNED);
1199 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1201 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1205 #ifndef _SYS_SYSPROTO_H_
1206 struct ktimer_create_args {
1208 struct sigevent * evp;
1213 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1215 struct sigevent *evp, ev;
1219 if (uap->evp == NULL) {
1222 error = copyin(uap->evp, &ev, sizeof(ev));
1227 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1229 error = copyout(&id, uap->timerid, sizeof(int));
1231 kern_ktimer_delete(td, id);
1237 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1238 int *timerid, int preset_id)
1240 struct proc *p = td->td_proc;
1245 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1248 if (posix_clocks[clock_id].timer_create == NULL)
1252 if (evp->sigev_notify != SIGEV_NONE &&
1253 evp->sigev_notify != SIGEV_SIGNAL &&
1254 evp->sigev_notify != SIGEV_THREAD_ID)
1256 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1257 evp->sigev_notify == SIGEV_THREAD_ID) &&
1258 !_SIG_VALID(evp->sigev_signo))
1262 if (p->p_itimers == NULL)
1265 it = uma_zalloc(itimer_zone, M_WAITOK);
1267 it->it_usecount = 0;
1268 timespecclear(&it->it_time.it_value);
1269 timespecclear(&it->it_time.it_interval);
1271 it->it_overrun_last = 0;
1272 it->it_clockid = clock_id;
1274 ksiginfo_init(&it->it_ksi);
1275 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1276 error = CLOCK_CALL(clock_id, timer_create, (it));
1281 if (preset_id != -1) {
1282 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1284 if (p->p_itimers->its_timers[id] != NULL) {
1291 * Find a free timer slot, skipping those reserved
1294 for (id = 3; id < TIMER_MAX; id++)
1295 if (p->p_itimers->its_timers[id] == NULL)
1297 if (id == TIMER_MAX) {
1303 p->p_itimers->its_timers[id] = it;
1305 it->it_sigev = *evp;
1307 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1310 case CLOCK_REALTIME:
1311 it->it_sigev.sigev_signo = SIGALRM;
1314 it->it_sigev.sigev_signo = SIGVTALRM;
1317 it->it_sigev.sigev_signo = SIGPROF;
1320 it->it_sigev.sigev_value.sival_int = id;
1323 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1324 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1325 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1326 it->it_ksi.ksi_code = SI_TIMER;
1327 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1328 it->it_ksi.ksi_timerid = id;
1336 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1338 uma_zfree(itimer_zone, it);
1342 #ifndef _SYS_SYSPROTO_H_
1343 struct ktimer_delete_args {
1348 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1351 return (kern_ktimer_delete(td, uap->timerid));
1354 static struct itimer *
1355 itimer_find(struct proc *p, int timerid)
1359 PROC_LOCK_ASSERT(p, MA_OWNED);
1360 if ((p->p_itimers == NULL) ||
1361 (timerid < 0) || (timerid >= TIMER_MAX) ||
1362 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1366 if ((it->it_flags & ITF_DELETING) != 0) {
1374 kern_ktimer_delete(struct thread *td, int timerid)
1376 struct proc *p = td->td_proc;
1380 it = itimer_find(p, timerid);
1387 it->it_flags |= ITF_DELETING;
1388 while (it->it_usecount > 0) {
1389 it->it_flags |= ITF_WANTED;
1390 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1392 it->it_flags &= ~ITF_WANTED;
1393 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1397 if (KSI_ONQ(&it->it_ksi))
1398 sigqueue_take(&it->it_ksi);
1399 p->p_itimers->its_timers[timerid] = NULL;
1401 uma_zfree(itimer_zone, it);
1405 #ifndef _SYS_SYSPROTO_H_
1406 struct ktimer_settime_args {
1409 const struct itimerspec * value;
1410 struct itimerspec * ovalue;
1414 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1416 struct itimerspec val, oval, *ovalp;
1419 error = copyin(uap->value, &val, sizeof(val));
1422 ovalp = uap->ovalue != NULL ? &oval : NULL;
1423 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1424 if (error == 0 && uap->ovalue != NULL)
1425 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1430 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1431 struct itimerspec *val, struct itimerspec *oval)
1439 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1445 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1453 #ifndef _SYS_SYSPROTO_H_
1454 struct ktimer_gettime_args {
1456 struct itimerspec * value;
1460 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1462 struct itimerspec val;
1465 error = kern_ktimer_gettime(td, uap->timerid, &val);
1467 error = copyout(&val, uap->value, sizeof(val));
1472 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1480 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1486 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1493 #ifndef _SYS_SYSPROTO_H_
1494 struct timer_getoverrun_args {
1499 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1502 return (kern_ktimer_getoverrun(td, uap->timerid));
1506 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1508 struct proc *p = td->td_proc;
1514 (it = itimer_find(p, timer_id)) == NULL) {
1518 td->td_retval[0] = it->it_overrun_last;
1527 realtimer_create(struct itimer *it)
1529 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1534 realtimer_delete(struct itimer *it)
1536 mtx_assert(&it->it_mtx, MA_OWNED);
1539 * clear timer's value and interval to tell realtimer_expire
1540 * to not rearm the timer.
1542 timespecclear(&it->it_time.it_value);
1543 timespecclear(&it->it_time.it_interval);
1545 callout_drain(&it->it_callout);
1551 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1553 struct timespec cts;
1555 mtx_assert(&it->it_mtx, MA_OWNED);
1557 realtimer_clocktime(it->it_clockid, &cts);
1558 *ovalue = it->it_time;
1559 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1560 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1561 if (ovalue->it_value.tv_sec < 0 ||
1562 (ovalue->it_value.tv_sec == 0 &&
1563 ovalue->it_value.tv_nsec == 0)) {
1564 ovalue->it_value.tv_sec = 0;
1565 ovalue->it_value.tv_nsec = 1;
1572 realtimer_settime(struct itimer *it, int flags, struct itimerspec *value,
1573 struct itimerspec *ovalue)
1575 struct timespec cts, ts;
1577 struct itimerspec val;
1579 mtx_assert(&it->it_mtx, MA_OWNED);
1582 if (itimespecfix(&val.it_value))
1585 if (timespecisset(&val.it_value)) {
1586 if (itimespecfix(&val.it_interval))
1589 timespecclear(&val.it_interval);
1593 realtimer_gettime(it, ovalue);
1596 if (timespecisset(&val.it_value)) {
1597 realtimer_clocktime(it->it_clockid, &cts);
1599 if ((flags & TIMER_ABSTIME) == 0) {
1600 /* Convert to absolute time. */
1601 timespecadd(&it->it_time.it_value, &cts,
1602 &it->it_time.it_value);
1604 timespecsub(&ts, &cts, &ts);
1606 * We don't care if ts is negative, tztohz will
1610 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1611 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1614 callout_stop(&it->it_callout);
1621 realtimer_clocktime(clockid_t id, struct timespec *ts)
1623 if (id == CLOCK_REALTIME)
1625 else /* CLOCK_MONOTONIC */
1630 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1634 PROC_LOCK_ASSERT(p, MA_OWNED);
1635 it = itimer_find(p, timerid);
1637 ksi->ksi_overrun = it->it_overrun;
1638 it->it_overrun_last = it->it_overrun;
1647 itimespecfix(struct timespec *ts)
1650 if (!timespecvalid_interval(ts))
1652 if ((UINT64_MAX - ts->tv_nsec) / NS_PER_SEC < ts->tv_sec)
1654 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1655 ts->tv_nsec = tick * 1000;
1659 #define timespectons(tsp) \
1660 ((uint64_t)(tsp)->tv_sec * NS_PER_SEC + (tsp)->tv_nsec)
1661 #define timespecfromns(ns) (struct timespec){ \
1662 .tv_sec = (ns) / NS_PER_SEC, \
1663 .tv_nsec = (ns) % NS_PER_SEC \
1667 realtimer_expire_l(struct itimer *it, bool proc_locked)
1669 struct timespec cts, ts;
1672 uint64_t interval, now, overruns, value;
1674 realtimer_clocktime(it->it_clockid, &cts);
1675 /* Only fire if time is reached. */
1676 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1677 if (timespecisset(&it->it_time.it_interval)) {
1678 timespecadd(&it->it_time.it_value,
1679 &it->it_time.it_interval,
1680 &it->it_time.it_value);
1682 interval = timespectons(&it->it_time.it_interval);
1683 value = timespectons(&it->it_time.it_value);
1684 now = timespectons(&cts);
1688 * We missed at least one period.
1690 overruns = howmany(now - value + 1, interval);
1691 if (it->it_overrun + overruns >=
1693 it->it_overrun + overruns <= INT_MAX) {
1694 it->it_overrun += (int)overruns;
1696 it->it_overrun = INT_MAX;
1697 it->it_ksi.ksi_errno = ERANGE;
1700 now + interval - (now - value) % interval;
1701 it->it_time.it_value = timespecfromns(value);
1704 /* single shot timer ? */
1705 timespecclear(&it->it_time.it_value);
1709 if (timespecisset(&it->it_time.it_value)) {
1710 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1711 it->it_flags |= ITF_PSTOPPED;
1713 timespecsub(&it->it_time.it_value, &cts, &ts);
1714 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1715 callout_reset(&it->it_callout, tvtohz(&tv),
1716 realtimer_expire, it);
1729 } else if (timespecisset(&it->it_time.it_value)) {
1731 if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1732 it->it_flags |= ITF_PSTOPPED;
1734 ts = it->it_time.it_value;
1735 timespecsub(&ts, &cts, &ts);
1736 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1737 callout_reset(&it->it_callout, tvtohz(&tv),
1738 realtimer_expire, it);
1743 /* Timeout callback for realtime timer */
1745 realtimer_expire(void *arg)
1747 realtimer_expire_l(arg, false);
1751 itimer_fire(struct itimer *it)
1753 struct proc *p = it->it_proc;
1756 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1757 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1758 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1760 timespecclear(&it->it_time.it_value);
1761 timespecclear(&it->it_time.it_interval);
1762 callout_stop(&it->it_callout);
1766 if (!KSI_ONQ(&it->it_ksi)) {
1767 it->it_ksi.ksi_errno = 0;
1768 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1769 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1771 if (it->it_overrun < INT_MAX)
1774 it->it_ksi.ksi_errno = ERANGE;
1781 itimers_alloc(struct proc *p)
1783 struct itimers *its;
1785 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1787 if (p->p_itimers == NULL) {
1793 free(its, M_SUBPROC);
1797 /* Clean up timers when some process events are being triggered. */
1799 itimers_event_exit_exec(int start_idx, struct proc *p)
1801 struct itimers *its;
1809 for (i = start_idx; i < TIMER_MAX; ++i) {
1810 if ((it = its->its_timers[i]) != NULL)
1811 kern_ktimer_delete(curthread, i);
1813 if (its->its_timers[0] == NULL && its->its_timers[1] == NULL &&
1814 its->its_timers[2] == NULL) {
1815 /* Synchronize with itimer_proc_continue(). */
1817 p->p_itimers = NULL;
1819 free(its, M_SUBPROC);
1824 itimers_exec(struct proc *p)
1827 * According to susv3, XSI interval timers should be inherited
1830 itimers_event_exit_exec(3, p);
1834 itimers_exit(struct proc *p)
1836 itimers_event_exit_exec(0, p);