2 * Copyright (c) 1982, 1986, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)kern_time.c 8.1 (Berkeley) 6/10/93
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/limits.h>
38 #include <sys/clock.h>
40 #include <sys/mutex.h>
41 #include <sys/sysproto.h>
42 #include <sys/eventhandler.h>
43 #include <sys/resourcevar.h>
44 #include <sys/signalvar.h>
45 #include <sys/kernel.h>
46 #include <sys/sleepqueue.h>
47 #include <sys/syscallsubr.h>
48 #include <sys/sysctl.h>
49 #include <sys/sysent.h>
52 #include <sys/posix4.h>
54 #include <sys/timers.h>
55 #include <sys/timetc.h>
56 #include <sys/vnode.h>
59 #include <vm/vm_extern.h>
61 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
62 #define CPUCLOCK_BIT 0x80000000
63 #define CPUCLOCK_PROCESS_BIT 0x40000000
64 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
65 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
66 #define MAKE_PROCESS_CPUCLOCK(pid) \
67 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
69 static struct kclock posix_clocks[MAX_CLOCKS];
70 static uma_zone_t itimer_zone = NULL;
73 * Time of day and interval timer support.
75 * These routines provide the kernel entry points to get and set
76 * the time-of-day and per-process interval timers. Subroutines
77 * here provide support for adding and subtracting timeval structures
78 * and decrementing interval timers, optionally reloading the interval
79 * timers when they expire.
82 static int settime(struct thread *, struct timeval *);
83 static void timevalfix(struct timeval *);
85 static void itimer_start(void);
86 static int itimer_init(void *, int, int);
87 static void itimer_fini(void *, int);
88 static void itimer_enter(struct itimer *);
89 static void itimer_leave(struct itimer *);
90 static struct itimer *itimer_find(struct proc *, int);
91 static void itimers_alloc(struct proc *);
92 static void itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
93 static void itimers_event_hook_exit(void *arg, struct proc *p);
94 static int realtimer_create(struct itimer *);
95 static int realtimer_gettime(struct itimer *, struct itimerspec *);
96 static int realtimer_settime(struct itimer *, int,
97 struct itimerspec *, struct itimerspec *);
98 static int realtimer_delete(struct itimer *);
99 static void realtimer_clocktime(clockid_t, struct timespec *);
100 static void realtimer_expire(void *);
102 int register_posix_clock(int, struct kclock *);
103 void itimer_fire(struct itimer *it);
104 int itimespecfix(struct timespec *ts);
106 #define CLOCK_CALL(clock, call, arglist) \
107 ((*posix_clocks[clock].call) arglist)
109 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
113 settime(struct thread *td, struct timeval *tv)
115 struct timeval delta, tv1, tv2;
116 static struct timeval maxtime, laststep;
123 timevalsub(&delta, &tv1);
126 * If the system is secure, we do not allow the time to be
127 * set to a value earlier than 1 second less than the highest
128 * time we have yet seen. The worst a miscreant can do in
129 * this circumstance is "freeze" time. He couldn't go
132 * We similarly do not allow the clock to be stepped more
133 * than one second, nor more than once per second. This allows
134 * a miscreant to make the clock march double-time, but no worse.
136 if (securelevel_gt(td->td_ucred, 1) != 0) {
137 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
139 * Update maxtime to latest time we've seen.
141 if (tv1.tv_sec > maxtime.tv_sec)
144 timevalsub(&tv2, &maxtime);
145 if (tv2.tv_sec < -1) {
146 tv->tv_sec = maxtime.tv_sec - 1;
147 printf("Time adjustment clamped to -1 second\n");
150 if (tv1.tv_sec == laststep.tv_sec) {
154 if (delta.tv_sec > 1) {
155 tv->tv_sec = tv1.tv_sec + 1;
156 printf("Time adjustment clamped to +1 second\n");
162 ts.tv_sec = tv->tv_sec;
163 ts.tv_nsec = tv->tv_usec * 1000;
171 #ifndef _SYS_SYSPROTO_H_
172 struct clock_getcpuclockid2_args {
180 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
185 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
187 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
192 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
201 case CPUCLOCK_WHICH_PID:
206 error = p_cansee(td, 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 get_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 thread_lock(targettd);
267 runtime = targettd->td_runtime;
268 thread_unlock(targettd);
270 cputick2timespec(runtime, ats);
274 get_process_cputime(struct proc *targetp, struct timespec *ats)
280 rufetch(targetp, &ru);
281 runtime = targetp->p_rux.rux_runtime;
282 PROC_SUNLOCK(targetp);
283 cputick2timespec(runtime, ats);
287 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
296 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
297 tid = clock_id & CPUCLOCK_ID_MASK;
298 td2 = tdfind(tid, p->p_pid);
301 get_thread_cputime(td2, ats);
302 PROC_UNLOCK(td2->td_proc);
304 pid = clock_id & CPUCLOCK_ID_MASK;
305 error = pget(pid, PGET_CANSEE, &p2);
308 get_process_cputime(p2, ats);
315 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
317 struct timeval sys, user;
322 case CLOCK_REALTIME: /* Default to precise. */
323 case CLOCK_REALTIME_PRECISE:
326 case CLOCK_REALTIME_FAST:
332 calcru(p, &user, &sys);
335 TIMEVAL_TO_TIMESPEC(&user, ats);
340 calcru(p, &user, &sys);
343 timevaladd(&user, &sys);
344 TIMEVAL_TO_TIMESPEC(&user, ats);
346 case CLOCK_MONOTONIC: /* Default to precise. */
347 case CLOCK_MONOTONIC_PRECISE:
349 case CLOCK_UPTIME_PRECISE:
352 case CLOCK_UPTIME_FAST:
353 case CLOCK_MONOTONIC_FAST:
357 ats->tv_sec = time_second;
360 case CLOCK_THREAD_CPUTIME_ID:
361 get_thread_cputime(NULL, ats);
363 case CLOCK_PROCESS_CPUTIME_ID:
365 get_process_cputime(p, ats);
369 if ((int)clock_id >= 0)
371 return (get_cputime(td, clock_id, ats));
376 #ifndef _SYS_SYSPROTO_H_
377 struct clock_settime_args {
379 const struct timespec *tp;
384 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
389 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
391 return (kern_clock_settime(td, uap->clock_id, &ats));
395 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
400 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
402 if (clock_id != CLOCK_REALTIME)
404 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
406 /* XXX Don't convert nsec->usec and back */
407 TIMESPEC_TO_TIMEVAL(&atv, ats);
408 error = settime(td, &atv);
412 #ifndef _SYS_SYSPROTO_H_
413 struct clock_getres_args {
419 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
427 error = kern_clock_getres(td, uap->clock_id, &ts);
429 error = copyout(&ts, uap->tp, sizeof(ts));
434 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
440 case CLOCK_REALTIME_FAST:
441 case CLOCK_REALTIME_PRECISE:
442 case CLOCK_MONOTONIC:
443 case CLOCK_MONOTONIC_FAST:
444 case CLOCK_MONOTONIC_PRECISE:
446 case CLOCK_UPTIME_FAST:
447 case CLOCK_UPTIME_PRECISE:
449 * Round up the result of the division cheaply by adding 1.
450 * Rounding up is especially important if rounding down
451 * would give 0. Perfect rounding is unimportant.
453 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
457 /* Accurately round up here because we can do so cheaply. */
458 ts->tv_nsec = (1000000000 + hz - 1) / hz;
464 case CLOCK_THREAD_CPUTIME_ID:
465 case CLOCK_PROCESS_CPUTIME_ID:
467 /* sync with cputick2usec */
468 ts->tv_nsec = 1000000 / cpu_tickrate();
469 if (ts->tv_nsec == 0)
473 if ((int)clock_id < 0)
480 static uint8_t nanowait[MAXCPU];
483 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
486 sbintime_t sbt, sbtt, prec, tmp;
490 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
492 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
495 if (ts.tv_sec > INT32_MAX / 2) {
496 over = ts.tv_sec - INT32_MAX / 2;
503 if (TIMESEL(&sbt, tmp))
506 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
507 sbt, prec, C_ABSOLUTE);
508 if (error != EWOULDBLOCK) {
509 if (error == ERESTART)
513 ts = sbttots(sbt - sbtt);
526 #ifndef _SYS_SYSPROTO_H_
527 struct nanosleep_args {
528 struct timespec *rqtp;
529 struct timespec *rmtp;
534 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
536 struct timespec rmt, rqt;
539 error = copyin(uap->rqtp, &rqt, sizeof(rqt));
544 !useracc((caddr_t)uap->rmtp, sizeof(rmt), VM_PROT_WRITE))
546 error = kern_nanosleep(td, &rqt, &rmt);
547 if (error && uap->rmtp) {
550 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
557 #ifndef _SYS_SYSPROTO_H_
558 struct gettimeofday_args {
560 struct timezone *tzp;
565 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
573 error = copyout(&atv, uap->tp, sizeof (atv));
575 if (error == 0 && uap->tzp != NULL) {
576 rtz.tz_minuteswest = tz_minuteswest;
577 rtz.tz_dsttime = tz_dsttime;
578 error = copyout(&rtz, uap->tzp, sizeof (rtz));
583 #ifndef _SYS_SYSPROTO_H_
584 struct settimeofday_args {
586 struct timezone *tzp;
591 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
593 struct timeval atv, *tvp;
594 struct timezone atz, *tzp;
598 error = copyin(uap->tv, &atv, sizeof(atv));
605 error = copyin(uap->tzp, &atz, sizeof(atz));
611 return (kern_settimeofday(td, tvp, tzp));
615 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
619 error = priv_check(td, PRIV_SETTIMEOFDAY);
622 /* Verify all parameters before changing time. */
624 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
626 error = settime(td, tv);
628 if (tzp && error == 0) {
629 tz_minuteswest = tzp->tz_minuteswest;
630 tz_dsttime = tzp->tz_dsttime;
636 * Get value of an interval timer. The process virtual and profiling virtual
637 * time timers are kept in the p_stats area, since they can be swapped out.
638 * These are kept internally in the way they are specified externally: in
639 * time until they expire.
641 * The real time interval timer is kept in the process table slot for the
642 * process, and its value (it_value) is kept as an absolute time rather than
643 * as a delta, so that it is easy to keep periodic real-time signals from
646 * Virtual time timers are processed in the hardclock() routine of
647 * kern_clock.c. The real time timer is processed by a timeout routine,
648 * called from the softclock() routine. Since a callout may be delayed in
649 * real time due to interrupt processing in the system, it is possible for
650 * the real time timeout routine (realitexpire, given below), to be delayed
651 * in real time past when it is supposed to occur. It does not suffice,
652 * therefore, to reload the real timer .it_value from the real time timers
653 * .it_interval. Rather, we compute the next time in absolute time the timer
656 #ifndef _SYS_SYSPROTO_H_
657 struct getitimer_args {
659 struct itimerval *itv;
663 sys_getitimer(struct thread *td, struct getitimer_args *uap)
665 struct itimerval aitv;
668 error = kern_getitimer(td, uap->which, &aitv);
671 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
675 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
677 struct proc *p = td->td_proc;
680 if (which > ITIMER_PROF)
683 if (which == ITIMER_REAL) {
685 * Convert from absolute to relative time in .it_value
686 * part of real time timer. If time for real time timer
687 * has passed return 0, else return difference between
688 * current time and time for the timer to go off.
691 *aitv = p->p_realtimer;
693 if (timevalisset(&aitv->it_value)) {
695 if (timevalcmp(&aitv->it_value, &ctv, <))
696 timevalclear(&aitv->it_value);
698 timevalsub(&aitv->it_value, &ctv);
702 *aitv = p->p_stats->p_timer[which];
708 #ifndef _SYS_SYSPROTO_H_
709 struct setitimer_args {
711 struct itimerval *itv, *oitv;
715 sys_setitimer(struct thread *td, struct setitimer_args *uap)
717 struct itimerval aitv, oitv;
720 if (uap->itv == NULL) {
721 uap->itv = uap->oitv;
722 return (sys_getitimer(td, (struct getitimer_args *)uap));
725 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
727 error = kern_setitimer(td, uap->which, &aitv, &oitv);
728 if (error != 0 || uap->oitv == NULL)
730 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
734 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
735 struct itimerval *oitv)
737 struct proc *p = td->td_proc;
742 return (kern_getitimer(td, which, oitv));
744 if (which > ITIMER_PROF)
746 if (itimerfix(&aitv->it_value) ||
747 aitv->it_value.tv_sec > INT32_MAX / 2)
749 if (!timevalisset(&aitv->it_value))
750 timevalclear(&aitv->it_interval);
751 else if (itimerfix(&aitv->it_interval) ||
752 aitv->it_interval.tv_sec > INT32_MAX / 2)
755 if (which == ITIMER_REAL) {
757 if (timevalisset(&p->p_realtimer.it_value))
758 callout_stop(&p->p_itcallout);
760 if (timevalisset(&aitv->it_value)) {
761 pr = tvtosbt(aitv->it_value) >> tc_precexp;
762 timevaladd(&aitv->it_value, &ctv);
763 sbt = tvtosbt(aitv->it_value);
764 callout_reset_sbt(&p->p_itcallout, sbt, pr,
765 realitexpire, p, C_ABSOLUTE);
767 *oitv = p->p_realtimer;
768 p->p_realtimer = *aitv;
770 if (timevalisset(&oitv->it_value)) {
771 if (timevalcmp(&oitv->it_value, &ctv, <))
772 timevalclear(&oitv->it_value);
774 timevalsub(&oitv->it_value, &ctv);
778 *oitv = p->p_stats->p_timer[which];
779 p->p_stats->p_timer[which] = *aitv;
786 * Real interval timer expired:
787 * send process whose timer expired an alarm signal.
788 * If time is not set up to reload, then just return.
789 * Else compute next time timer should go off which is > current time.
790 * This is where delay in processing this timeout causes multiple
791 * SIGALRM calls to be compressed into one.
792 * tvtohz() always adds 1 to allow for the time until the next clock
793 * interrupt being strictly less than 1 clock tick, but we don't want
794 * that here since we want to appear to be in sync with the clock
795 * interrupt even when we're delayed.
798 realitexpire(void *arg)
804 p = (struct proc *)arg;
805 kern_psignal(p, SIGALRM);
806 if (!timevalisset(&p->p_realtimer.it_interval)) {
807 timevalclear(&p->p_realtimer.it_value);
808 if (p->p_flag & P_WEXIT)
809 wakeup(&p->p_itcallout);
812 isbt = tvtosbt(p->p_realtimer.it_interval);
813 if (isbt >= sbt_timethreshold)
814 getmicrouptime(&ctv);
818 timevaladd(&p->p_realtimer.it_value,
819 &p->p_realtimer.it_interval);
820 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
821 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
822 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
826 * Check that a proposed value to load into the .it_value or
827 * .it_interval part of an interval timer is acceptable, and
828 * fix it to have at least minimal value (i.e. if it is less
829 * than the resolution of the clock, round it up.)
832 itimerfix(struct timeval *tv)
835 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
837 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
838 tv->tv_usec < (u_int)tick / 16)
839 tv->tv_usec = (u_int)tick / 16;
844 * Decrement an interval timer by a specified number
845 * of microseconds, which must be less than a second,
846 * i.e. < 1000000. If the timer expires, then reload
847 * it. In this case, carry over (usec - old value) to
848 * reduce the value reloaded into the timer so that
849 * the timer does not drift. This routine assumes
850 * that it is called in a context where the timers
851 * on which it is operating cannot change in value.
854 itimerdecr(struct itimerval *itp, int usec)
857 if (itp->it_value.tv_usec < usec) {
858 if (itp->it_value.tv_sec == 0) {
859 /* expired, and already in next interval */
860 usec -= itp->it_value.tv_usec;
863 itp->it_value.tv_usec += 1000000;
864 itp->it_value.tv_sec--;
866 itp->it_value.tv_usec -= usec;
868 if (timevalisset(&itp->it_value))
870 /* expired, exactly at end of interval */
872 if (timevalisset(&itp->it_interval)) {
873 itp->it_value = itp->it_interval;
874 itp->it_value.tv_usec -= usec;
875 if (itp->it_value.tv_usec < 0) {
876 itp->it_value.tv_usec += 1000000;
877 itp->it_value.tv_sec--;
880 itp->it_value.tv_usec = 0; /* sec is already 0 */
885 * Add and subtract routines for timevals.
886 * N.B.: subtract routine doesn't deal with
887 * results which are before the beginning,
888 * it just gets very confused in this case.
892 timevaladd(struct timeval *t1, const struct timeval *t2)
895 t1->tv_sec += t2->tv_sec;
896 t1->tv_usec += t2->tv_usec;
901 timevalsub(struct timeval *t1, const struct timeval *t2)
904 t1->tv_sec -= t2->tv_sec;
905 t1->tv_usec -= t2->tv_usec;
910 timevalfix(struct timeval *t1)
913 if (t1->tv_usec < 0) {
915 t1->tv_usec += 1000000;
917 if (t1->tv_usec >= 1000000) {
919 t1->tv_usec -= 1000000;
924 * ratecheck(): simple time-based rate-limit checking.
927 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
929 struct timeval tv, delta;
932 getmicrouptime(&tv); /* NB: 10ms precision */
934 timevalsub(&delta, lasttime);
937 * check for 0,0 is so that the message will be seen at least once,
938 * even if interval is huge.
940 if (timevalcmp(&delta, mininterval, >=) ||
941 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
950 * ppsratecheck(): packets (or events) per second limitation.
952 * Return 0 if the limit is to be enforced (e.g. the caller
953 * should drop a packet because of the rate limitation).
955 * maxpps of 0 always causes zero to be returned. maxpps of -1
956 * always causes 1 to be returned; this effectively defeats rate
959 * Note that we maintain the struct timeval for compatibility
960 * with other bsd systems. We reuse the storage and just monitor
961 * clock ticks for minimal overhead.
964 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
969 * Reset the last time and counter if this is the first call
970 * or more than a second has passed since the last update of
974 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
975 lasttime->tv_sec = now;
977 return (maxpps != 0);
979 (*curpps)++; /* NB: ignore potential overflow */
980 return (maxpps < 0 || *curpps < maxpps);
987 struct kclock rt_clock = {
988 .timer_create = realtimer_create,
989 .timer_delete = realtimer_delete,
990 .timer_settime = realtimer_settime,
991 .timer_gettime = realtimer_gettime,
995 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
996 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
997 register_posix_clock(CLOCK_REALTIME, &rt_clock);
998 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
999 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1000 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1001 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1002 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1003 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1004 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1005 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1009 register_posix_clock(int clockid, struct kclock *clk)
1011 if ((unsigned)clockid >= MAX_CLOCKS) {
1012 printf("%s: invalid clockid\n", __func__);
1015 posix_clocks[clockid] = *clk;
1020 itimer_init(void *mem, int size, int flags)
1024 it = (struct itimer *)mem;
1025 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1030 itimer_fini(void *mem, int size)
1034 it = (struct itimer *)mem;
1035 mtx_destroy(&it->it_mtx);
1039 itimer_enter(struct itimer *it)
1042 mtx_assert(&it->it_mtx, MA_OWNED);
1047 itimer_leave(struct itimer *it)
1050 mtx_assert(&it->it_mtx, MA_OWNED);
1051 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1053 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1057 #ifndef _SYS_SYSPROTO_H_
1058 struct ktimer_create_args {
1060 struct sigevent * evp;
1065 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1067 struct sigevent *evp, ev;
1071 if (uap->evp == NULL) {
1074 error = copyin(uap->evp, &ev, sizeof(ev));
1079 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1081 error = copyout(&id, uap->timerid, sizeof(int));
1083 kern_ktimer_delete(td, id);
1089 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1090 int *timerid, int preset_id)
1092 struct proc *p = td->td_proc;
1097 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1100 if (posix_clocks[clock_id].timer_create == NULL)
1104 if (evp->sigev_notify != SIGEV_NONE &&
1105 evp->sigev_notify != SIGEV_SIGNAL &&
1106 evp->sigev_notify != SIGEV_THREAD_ID)
1108 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1109 evp->sigev_notify == SIGEV_THREAD_ID) &&
1110 !_SIG_VALID(evp->sigev_signo))
1114 if (p->p_itimers == NULL)
1117 it = uma_zalloc(itimer_zone, M_WAITOK);
1119 it->it_usecount = 0;
1121 timespecclear(&it->it_time.it_value);
1122 timespecclear(&it->it_time.it_interval);
1124 it->it_overrun_last = 0;
1125 it->it_clockid = clock_id;
1126 it->it_timerid = -1;
1128 ksiginfo_init(&it->it_ksi);
1129 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1130 error = CLOCK_CALL(clock_id, timer_create, (it));
1135 if (preset_id != -1) {
1136 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1138 if (p->p_itimers->its_timers[id] != NULL) {
1145 * Find a free timer slot, skipping those reserved
1148 for (id = 3; id < TIMER_MAX; id++)
1149 if (p->p_itimers->its_timers[id] == NULL)
1151 if (id == TIMER_MAX) {
1157 it->it_timerid = id;
1158 p->p_itimers->its_timers[id] = it;
1160 it->it_sigev = *evp;
1162 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1165 case CLOCK_REALTIME:
1166 it->it_sigev.sigev_signo = SIGALRM;
1169 it->it_sigev.sigev_signo = SIGVTALRM;
1172 it->it_sigev.sigev_signo = SIGPROF;
1175 it->it_sigev.sigev_value.sival_int = id;
1178 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1179 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1180 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1181 it->it_ksi.ksi_code = SI_TIMER;
1182 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1183 it->it_ksi.ksi_timerid = id;
1191 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1193 uma_zfree(itimer_zone, it);
1197 #ifndef _SYS_SYSPROTO_H_
1198 struct ktimer_delete_args {
1203 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1206 return (kern_ktimer_delete(td, uap->timerid));
1209 static struct itimer *
1210 itimer_find(struct proc *p, int timerid)
1214 PROC_LOCK_ASSERT(p, MA_OWNED);
1215 if ((p->p_itimers == NULL) ||
1216 (timerid < 0) || (timerid >= TIMER_MAX) ||
1217 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1221 if ((it->it_flags & ITF_DELETING) != 0) {
1229 kern_ktimer_delete(struct thread *td, int timerid)
1231 struct proc *p = td->td_proc;
1235 it = itimer_find(p, timerid);
1242 it->it_flags |= ITF_DELETING;
1243 while (it->it_usecount > 0) {
1244 it->it_flags |= ITF_WANTED;
1245 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1247 it->it_flags &= ~ITF_WANTED;
1248 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1252 if (KSI_ONQ(&it->it_ksi))
1253 sigqueue_take(&it->it_ksi);
1254 p->p_itimers->its_timers[timerid] = NULL;
1256 uma_zfree(itimer_zone, it);
1260 #ifndef _SYS_SYSPROTO_H_
1261 struct ktimer_settime_args {
1264 const struct itimerspec * value;
1265 struct itimerspec * ovalue;
1269 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1271 struct itimerspec val, oval, *ovalp;
1274 error = copyin(uap->value, &val, sizeof(val));
1277 ovalp = uap->ovalue != NULL ? &oval : NULL;
1278 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1279 if (error == 0 && uap->ovalue != NULL)
1280 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1285 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1286 struct itimerspec *val, struct itimerspec *oval)
1294 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1300 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1308 #ifndef _SYS_SYSPROTO_H_
1309 struct ktimer_gettime_args {
1311 struct itimerspec * value;
1315 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1317 struct itimerspec val;
1320 error = kern_ktimer_gettime(td, uap->timerid, &val);
1322 error = copyout(&val, uap->value, sizeof(val));
1327 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1335 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1341 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1348 #ifndef _SYS_SYSPROTO_H_
1349 struct timer_getoverrun_args {
1354 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1356 struct proc *p = td->td_proc;
1361 if (uap->timerid < 3 ||
1362 (it = itimer_find(p, uap->timerid)) == NULL) {
1366 td->td_retval[0] = it->it_overrun_last;
1375 realtimer_create(struct itimer *it)
1377 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1382 realtimer_delete(struct itimer *it)
1384 mtx_assert(&it->it_mtx, MA_OWNED);
1387 * clear timer's value and interval to tell realtimer_expire
1388 * to not rearm the timer.
1390 timespecclear(&it->it_time.it_value);
1391 timespecclear(&it->it_time.it_interval);
1393 callout_drain(&it->it_callout);
1399 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1401 struct timespec cts;
1403 mtx_assert(&it->it_mtx, MA_OWNED);
1405 realtimer_clocktime(it->it_clockid, &cts);
1406 *ovalue = it->it_time;
1407 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1408 timespecsub(&ovalue->it_value, &cts);
1409 if (ovalue->it_value.tv_sec < 0 ||
1410 (ovalue->it_value.tv_sec == 0 &&
1411 ovalue->it_value.tv_nsec == 0)) {
1412 ovalue->it_value.tv_sec = 0;
1413 ovalue->it_value.tv_nsec = 1;
1420 realtimer_settime(struct itimer *it, int flags,
1421 struct itimerspec *value, struct itimerspec *ovalue)
1423 struct timespec cts, ts;
1425 struct itimerspec val;
1427 mtx_assert(&it->it_mtx, MA_OWNED);
1430 if (itimespecfix(&val.it_value))
1433 if (timespecisset(&val.it_value)) {
1434 if (itimespecfix(&val.it_interval))
1437 timespecclear(&val.it_interval);
1441 realtimer_gettime(it, ovalue);
1444 if (timespecisset(&val.it_value)) {
1445 realtimer_clocktime(it->it_clockid, &cts);
1447 if ((flags & TIMER_ABSTIME) == 0) {
1448 /* Convert to absolute time. */
1449 timespecadd(&it->it_time.it_value, &cts);
1451 timespecsub(&ts, &cts);
1453 * We don't care if ts is negative, tztohz will
1457 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1458 callout_reset(&it->it_callout, tvtohz(&tv),
1459 realtimer_expire, it);
1461 callout_stop(&it->it_callout);
1468 realtimer_clocktime(clockid_t id, struct timespec *ts)
1470 if (id == CLOCK_REALTIME)
1472 else /* CLOCK_MONOTONIC */
1477 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1481 PROC_LOCK_ASSERT(p, MA_OWNED);
1482 it = itimer_find(p, timerid);
1484 ksi->ksi_overrun = it->it_overrun;
1485 it->it_overrun_last = it->it_overrun;
1494 itimespecfix(struct timespec *ts)
1497 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1499 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1500 ts->tv_nsec = tick * 1000;
1504 /* Timeout callback for realtime timer */
1506 realtimer_expire(void *arg)
1508 struct timespec cts, ts;
1512 it = (struct itimer *)arg;
1514 realtimer_clocktime(it->it_clockid, &cts);
1515 /* Only fire if time is reached. */
1516 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1517 if (timespecisset(&it->it_time.it_interval)) {
1518 timespecadd(&it->it_time.it_value,
1519 &it->it_time.it_interval);
1520 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1521 if (it->it_overrun < INT_MAX)
1524 it->it_ksi.ksi_errno = ERANGE;
1525 timespecadd(&it->it_time.it_value,
1526 &it->it_time.it_interval);
1529 /* single shot timer ? */
1530 timespecclear(&it->it_time.it_value);
1532 if (timespecisset(&it->it_time.it_value)) {
1533 ts = it->it_time.it_value;
1534 timespecsub(&ts, &cts);
1535 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1536 callout_reset(&it->it_callout, tvtohz(&tv),
1537 realtimer_expire, it);
1544 } else if (timespecisset(&it->it_time.it_value)) {
1545 ts = it->it_time.it_value;
1546 timespecsub(&ts, &cts);
1547 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1548 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1554 itimer_fire(struct itimer *it)
1556 struct proc *p = it->it_proc;
1559 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1560 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1561 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1563 timespecclear(&it->it_time.it_value);
1564 timespecclear(&it->it_time.it_interval);
1565 callout_stop(&it->it_callout);
1569 if (!KSI_ONQ(&it->it_ksi)) {
1570 it->it_ksi.ksi_errno = 0;
1571 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1572 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1574 if (it->it_overrun < INT_MAX)
1577 it->it_ksi.ksi_errno = ERANGE;
1584 itimers_alloc(struct proc *p)
1586 struct itimers *its;
1589 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1590 LIST_INIT(&its->its_virtual);
1591 LIST_INIT(&its->its_prof);
1592 TAILQ_INIT(&its->its_worklist);
1593 for (i = 0; i < TIMER_MAX; i++)
1594 its->its_timers[i] = NULL;
1596 if (p->p_itimers == NULL) {
1602 free(its, M_SUBPROC);
1607 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1609 itimers_event_hook_exit(arg, p);
1612 /* Clean up timers when some process events are being triggered. */
1614 itimers_event_hook_exit(void *arg, struct proc *p)
1616 struct itimers *its;
1618 int event = (int)(intptr_t)arg;
1621 if (p->p_itimers != NULL) {
1623 for (i = 0; i < MAX_CLOCKS; ++i) {
1624 if (posix_clocks[i].event_hook != NULL)
1625 CLOCK_CALL(i, event_hook, (p, i, event));
1628 * According to susv3, XSI interval timers should be inherited
1631 if (event == ITIMER_EV_EXEC)
1633 else if (event == ITIMER_EV_EXIT)
1636 panic("unhandled event");
1637 for (; i < TIMER_MAX; ++i) {
1638 if ((it = its->its_timers[i]) != NULL)
1639 kern_ktimer_delete(curthread, i);
1641 if (its->its_timers[0] == NULL &&
1642 its->its_timers[1] == NULL &&
1643 its->its_timers[2] == NULL) {
1644 free(its, M_SUBPROC);
1645 p->p_itimers = NULL;