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 "opt_ktrace.h"
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/limits.h>
40 #include <sys/clock.h>
42 #include <sys/mutex.h>
43 #include <sys/sysproto.h>
44 #include <sys/eventhandler.h>
45 #include <sys/resourcevar.h>
46 #include <sys/signalvar.h>
47 #include <sys/kernel.h>
48 #include <sys/sleepqueue.h>
49 #include <sys/syscallsubr.h>
50 #include <sys/sysctl.h>
51 #include <sys/sysent.h>
54 #include <sys/posix4.h>
56 #include <sys/timers.h>
57 #include <sys/timetc.h>
58 #include <sys/vnode.h>
60 #include <sys/ktrace.h>
64 #include <vm/vm_extern.h>
66 #define MAX_CLOCKS (CLOCK_MONOTONIC+1)
67 #define CPUCLOCK_BIT 0x80000000
68 #define CPUCLOCK_PROCESS_BIT 0x40000000
69 #define CPUCLOCK_ID_MASK (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
70 #define MAKE_THREAD_CPUCLOCK(tid) (CPUCLOCK_BIT|(tid))
71 #define MAKE_PROCESS_CPUCLOCK(pid) \
72 (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
74 static struct kclock posix_clocks[MAX_CLOCKS];
75 static uma_zone_t itimer_zone = NULL;
78 * Time of day and interval timer support.
80 * These routines provide the kernel entry points to get and set
81 * the time-of-day and per-process interval timers. Subroutines
82 * here provide support for adding and subtracting timeval structures
83 * and decrementing interval timers, optionally reloading the interval
84 * timers when they expire.
87 static int settime(struct thread *, struct timeval *);
88 static void timevalfix(struct timeval *);
90 static void itimer_start(void);
91 static int itimer_init(void *, int, int);
92 static void itimer_fini(void *, int);
93 static void itimer_enter(struct itimer *);
94 static void itimer_leave(struct itimer *);
95 static struct itimer *itimer_find(struct proc *, int);
96 static void itimers_alloc(struct proc *);
97 static void itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
98 static void itimers_event_hook_exit(void *arg, struct proc *p);
99 static int realtimer_create(struct itimer *);
100 static int realtimer_gettime(struct itimer *, struct itimerspec *);
101 static int realtimer_settime(struct itimer *, int,
102 struct itimerspec *, struct itimerspec *);
103 static int realtimer_delete(struct itimer *);
104 static void realtimer_clocktime(clockid_t, struct timespec *);
105 static void realtimer_expire(void *);
107 int register_posix_clock(int, struct kclock *);
108 void itimer_fire(struct itimer *it);
109 int itimespecfix(struct timespec *ts);
111 #define CLOCK_CALL(clock, call, arglist) \
112 ((*posix_clocks[clock].call) arglist)
114 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
118 settime(struct thread *td, struct timeval *tv)
120 struct timeval delta, tv1, tv2;
121 static struct timeval maxtime, laststep;
128 timevalsub(&delta, &tv1);
131 * If the system is secure, we do not allow the time to be
132 * set to a value earlier than 1 second less than the highest
133 * time we have yet seen. The worst a miscreant can do in
134 * this circumstance is "freeze" time. He couldn't go
137 * We similarly do not allow the clock to be stepped more
138 * than one second, nor more than once per second. This allows
139 * a miscreant to make the clock march double-time, but no worse.
141 if (securelevel_gt(td->td_ucred, 1) != 0) {
142 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
144 * Update maxtime to latest time we've seen.
146 if (tv1.tv_sec > maxtime.tv_sec)
149 timevalsub(&tv2, &maxtime);
150 if (tv2.tv_sec < -1) {
151 tv->tv_sec = maxtime.tv_sec - 1;
152 printf("Time adjustment clamped to -1 second\n");
155 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;
176 #ifndef _SYS_SYSPROTO_H_
177 struct clock_getcpuclockid2_args {
185 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
190 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
192 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
197 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
206 case CPUCLOCK_WHICH_PID:
208 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
214 pid = td->td_proc->p_pid;
216 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
218 case CPUCLOCK_WHICH_TID:
219 tid = id == 0 ? td->td_tid : id;
220 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
227 #ifndef _SYS_SYSPROTO_H_
228 struct clock_gettime_args {
235 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
240 error = kern_clock_gettime(td, uap->clock_id, &ats);
242 error = copyout(&ats, uap->tp, sizeof(ats));
248 cputick2timespec(uint64_t runtime, struct timespec *ats)
250 runtime = cputick2usec(runtime);
251 ats->tv_sec = runtime / 1000000;
252 ats->tv_nsec = runtime % 1000000 * 1000;
256 get_thread_cputime(struct thread *targettd, struct timespec *ats)
258 uint64_t runtime, curtime, switchtime;
260 if (targettd == NULL) { /* current thread */
262 switchtime = PCPU_GET(switchtime);
263 curtime = cpu_ticks();
264 runtime = curthread->td_runtime;
266 runtime += curtime - switchtime;
268 thread_lock(targettd);
269 runtime = targettd->td_runtime;
270 thread_unlock(targettd);
272 cputick2timespec(runtime, ats);
276 get_process_cputime(struct proc *targetp, struct timespec *ats)
281 PROC_STATLOCK(targetp);
282 rufetch(targetp, &ru);
283 runtime = targetp->p_rux.rux_runtime;
284 PROC_STATUNLOCK(targetp);
285 cputick2timespec(runtime, ats);
289 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
298 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
299 tid = clock_id & CPUCLOCK_ID_MASK;
300 td2 = tdfind(tid, p->p_pid);
303 get_thread_cputime(td2, ats);
304 PROC_UNLOCK(td2->td_proc);
306 pid = clock_id & CPUCLOCK_ID_MASK;
307 error = pget(pid, PGET_CANSEE, &p2);
310 get_process_cputime(p2, ats);
317 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
319 struct timeval sys, user;
324 case CLOCK_REALTIME: /* Default to precise. */
325 case CLOCK_REALTIME_PRECISE:
328 case CLOCK_REALTIME_FAST:
334 calcru(p, &user, &sys);
337 TIMEVAL_TO_TIMESPEC(&user, ats);
342 calcru(p, &user, &sys);
345 timevaladd(&user, &sys);
346 TIMEVAL_TO_TIMESPEC(&user, ats);
348 case CLOCK_MONOTONIC: /* Default to precise. */
349 case CLOCK_MONOTONIC_PRECISE:
351 case CLOCK_UPTIME_PRECISE:
354 case CLOCK_UPTIME_FAST:
355 case CLOCK_MONOTONIC_FAST:
359 ats->tv_sec = time_second;
362 case CLOCK_THREAD_CPUTIME_ID:
363 get_thread_cputime(NULL, ats);
365 case CLOCK_PROCESS_CPUTIME_ID:
367 get_process_cputime(p, ats);
371 if ((int)clock_id >= 0)
373 return (get_cputime(td, clock_id, ats));
378 #ifndef _SYS_SYSPROTO_H_
379 struct clock_settime_args {
381 const struct timespec *tp;
386 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
391 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
393 return (kern_clock_settime(td, uap->clock_id, &ats));
397 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
402 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
404 if (clock_id != CLOCK_REALTIME)
406 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
408 /* XXX Don't convert nsec->usec and back */
409 TIMESPEC_TO_TIMEVAL(&atv, ats);
410 error = settime(td, &atv);
414 #ifndef _SYS_SYSPROTO_H_
415 struct clock_getres_args {
421 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
429 error = kern_clock_getres(td, uap->clock_id, &ts);
431 error = copyout(&ts, uap->tp, sizeof(ts));
436 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
442 case CLOCK_REALTIME_FAST:
443 case CLOCK_REALTIME_PRECISE:
444 case CLOCK_MONOTONIC:
445 case CLOCK_MONOTONIC_FAST:
446 case CLOCK_MONOTONIC_PRECISE:
448 case CLOCK_UPTIME_FAST:
449 case CLOCK_UPTIME_PRECISE:
451 * Round up the result of the division cheaply by adding 1.
452 * Rounding up is especially important if rounding down
453 * would give 0. Perfect rounding is unimportant.
455 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
459 /* Accurately round up here because we can do so cheaply. */
460 ts->tv_nsec = (1000000000 + hz - 1) / hz;
466 case CLOCK_THREAD_CPUTIME_ID:
467 case CLOCK_PROCESS_CPUTIME_ID:
469 /* sync with cputick2usec */
470 ts->tv_nsec = 1000000 / cpu_tickrate();
471 if (ts->tv_nsec == 0)
475 if ((int)clock_id < 0)
482 static uint8_t nanowait[MAXCPU];
485 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
488 sbintime_t sbt, sbtt, prec, tmp;
492 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
494 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
497 if (ts.tv_sec > INT32_MAX / 2) {
498 over = ts.tv_sec - INT32_MAX / 2;
505 if (TIMESEL(&sbt, tmp))
508 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
509 sbt, prec, C_ABSOLUTE);
510 if (error != EWOULDBLOCK) {
511 if (error == ERESTART)
513 if (TIMESEL(&sbtt, tmp))
516 ts = sbttots(sbt - sbtt);
529 #ifndef _SYS_SYSPROTO_H_
530 struct nanosleep_args {
531 struct timespec *rqtp;
532 struct timespec *rmtp;
537 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
539 struct timespec rmt, rqt;
542 error = copyin(uap->rqtp, &rqt, sizeof(rqt));
547 !useracc((caddr_t)uap->rmtp, sizeof(rmt), VM_PROT_WRITE))
549 error = kern_nanosleep(td, &rqt, &rmt);
550 if (error == EINTR && uap->rmtp) {
553 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
560 #ifndef _SYS_SYSPROTO_H_
561 struct gettimeofday_args {
563 struct timezone *tzp;
568 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
576 error = copyout(&atv, uap->tp, sizeof (atv));
578 if (error == 0 && uap->tzp != NULL) {
579 rtz.tz_minuteswest = tz_minuteswest;
580 rtz.tz_dsttime = tz_dsttime;
581 error = copyout(&rtz, uap->tzp, sizeof (rtz));
586 #ifndef _SYS_SYSPROTO_H_
587 struct settimeofday_args {
589 struct timezone *tzp;
594 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
596 struct timeval atv, *tvp;
597 struct timezone atz, *tzp;
601 error = copyin(uap->tv, &atv, sizeof(atv));
608 error = copyin(uap->tzp, &atz, sizeof(atz));
614 return (kern_settimeofday(td, tvp, tzp));
618 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
622 error = priv_check(td, PRIV_SETTIMEOFDAY);
625 /* Verify all parameters before changing time. */
627 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
629 error = settime(td, tv);
631 if (tzp && error == 0) {
632 tz_minuteswest = tzp->tz_minuteswest;
633 tz_dsttime = tzp->tz_dsttime;
639 * Get value of an interval timer. The process virtual and profiling virtual
640 * time timers are kept in the p_stats area, since they can be swapped out.
641 * These are kept internally in the way they are specified externally: in
642 * time until they expire.
644 * The real time interval timer is kept in the process table slot for the
645 * process, and its value (it_value) is kept as an absolute time rather than
646 * as a delta, so that it is easy to keep periodic real-time signals from
649 * Virtual time timers are processed in the hardclock() routine of
650 * kern_clock.c. The real time timer is processed by a timeout routine,
651 * called from the softclock() routine. Since a callout may be delayed in
652 * real time due to interrupt processing in the system, it is possible for
653 * the real time timeout routine (realitexpire, given below), to be delayed
654 * in real time past when it is supposed to occur. It does not suffice,
655 * therefore, to reload the real timer .it_value from the real time timers
656 * .it_interval. Rather, we compute the next time in absolute time the timer
659 #ifndef _SYS_SYSPROTO_H_
660 struct getitimer_args {
662 struct itimerval *itv;
666 sys_getitimer(struct thread *td, struct getitimer_args *uap)
668 struct itimerval aitv;
671 error = kern_getitimer(td, uap->which, &aitv);
674 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
678 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
680 struct proc *p = td->td_proc;
683 if (which > ITIMER_PROF)
686 if (which == ITIMER_REAL) {
688 * Convert from absolute to relative time in .it_value
689 * part of real time timer. If time for real time timer
690 * has passed return 0, else return difference between
691 * current time and time for the timer to go off.
694 *aitv = p->p_realtimer;
696 if (timevalisset(&aitv->it_value)) {
698 if (timevalcmp(&aitv->it_value, &ctv, <))
699 timevalclear(&aitv->it_value);
701 timevalsub(&aitv->it_value, &ctv);
705 *aitv = p->p_stats->p_timer[which];
709 if (KTRPOINT(td, KTR_STRUCT))
715 #ifndef _SYS_SYSPROTO_H_
716 struct setitimer_args {
718 struct itimerval *itv, *oitv;
722 sys_setitimer(struct thread *td, struct setitimer_args *uap)
724 struct itimerval aitv, oitv;
727 if (uap->itv == NULL) {
728 uap->itv = uap->oitv;
729 return (sys_getitimer(td, (struct getitimer_args *)uap));
732 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
734 error = kern_setitimer(td, uap->which, &aitv, &oitv);
735 if (error != 0 || uap->oitv == NULL)
737 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
741 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
742 struct itimerval *oitv)
744 struct proc *p = td->td_proc;
749 return (kern_getitimer(td, which, oitv));
751 if (which > ITIMER_PROF)
754 if (KTRPOINT(td, KTR_STRUCT))
757 if (itimerfix(&aitv->it_value) ||
758 aitv->it_value.tv_sec > INT32_MAX / 2)
760 if (!timevalisset(&aitv->it_value))
761 timevalclear(&aitv->it_interval);
762 else if (itimerfix(&aitv->it_interval) ||
763 aitv->it_interval.tv_sec > INT32_MAX / 2)
766 if (which == ITIMER_REAL) {
768 if (timevalisset(&p->p_realtimer.it_value))
769 callout_stop(&p->p_itcallout);
771 if (timevalisset(&aitv->it_value)) {
772 pr = tvtosbt(aitv->it_value) >> tc_precexp;
773 timevaladd(&aitv->it_value, &ctv);
774 sbt = tvtosbt(aitv->it_value);
775 callout_reset_sbt(&p->p_itcallout, sbt, pr,
776 realitexpire, p, C_ABSOLUTE);
778 *oitv = p->p_realtimer;
779 p->p_realtimer = *aitv;
781 if (timevalisset(&oitv->it_value)) {
782 if (timevalcmp(&oitv->it_value, &ctv, <))
783 timevalclear(&oitv->it_value);
785 timevalsub(&oitv->it_value, &ctv);
788 if (aitv->it_interval.tv_sec == 0 &&
789 aitv->it_interval.tv_usec != 0 &&
790 aitv->it_interval.tv_usec < tick)
791 aitv->it_interval.tv_usec = tick;
792 if (aitv->it_value.tv_sec == 0 &&
793 aitv->it_value.tv_usec != 0 &&
794 aitv->it_value.tv_usec < tick)
795 aitv->it_value.tv_usec = tick;
797 *oitv = p->p_stats->p_timer[which];
798 p->p_stats->p_timer[which] = *aitv;
802 if (KTRPOINT(td, KTR_STRUCT))
809 * Real interval timer expired:
810 * send process whose timer expired an alarm signal.
811 * If time is not set up to reload, then just return.
812 * Else compute next time timer should go off which is > current time.
813 * This is where delay in processing this timeout causes multiple
814 * SIGALRM calls to be compressed into one.
815 * tvtohz() always adds 1 to allow for the time until the next clock
816 * interrupt being strictly less than 1 clock tick, but we don't want
817 * that here since we want to appear to be in sync with the clock
818 * interrupt even when we're delayed.
821 realitexpire(void *arg)
827 p = (struct proc *)arg;
828 kern_psignal(p, SIGALRM);
829 if (!timevalisset(&p->p_realtimer.it_interval)) {
830 timevalclear(&p->p_realtimer.it_value);
831 if (p->p_flag & P_WEXIT)
832 wakeup(&p->p_itcallout);
835 isbt = tvtosbt(p->p_realtimer.it_interval);
836 if (isbt >= sbt_timethreshold)
837 getmicrouptime(&ctv);
841 timevaladd(&p->p_realtimer.it_value,
842 &p->p_realtimer.it_interval);
843 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
844 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
845 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
849 * Check that a proposed value to load into the .it_value or
850 * .it_interval part of an interval timer is acceptable, and
851 * fix it to have at least minimal value (i.e. if it is less
852 * than the resolution of the clock, round it up.)
855 itimerfix(struct timeval *tv)
858 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
860 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
861 tv->tv_usec < (u_int)tick / 16)
862 tv->tv_usec = (u_int)tick / 16;
867 * Decrement an interval timer by a specified number
868 * of microseconds, which must be less than a second,
869 * i.e. < 1000000. If the timer expires, then reload
870 * it. In this case, carry over (usec - old value) to
871 * reduce the value reloaded into the timer so that
872 * the timer does not drift. This routine assumes
873 * that it is called in a context where the timers
874 * on which it is operating cannot change in value.
877 itimerdecr(struct itimerval *itp, int usec)
880 if (itp->it_value.tv_usec < usec) {
881 if (itp->it_value.tv_sec == 0) {
882 /* expired, and already in next interval */
883 usec -= itp->it_value.tv_usec;
886 itp->it_value.tv_usec += 1000000;
887 itp->it_value.tv_sec--;
889 itp->it_value.tv_usec -= usec;
891 if (timevalisset(&itp->it_value))
893 /* expired, exactly at end of interval */
895 if (timevalisset(&itp->it_interval)) {
896 itp->it_value = itp->it_interval;
897 itp->it_value.tv_usec -= usec;
898 if (itp->it_value.tv_usec < 0) {
899 itp->it_value.tv_usec += 1000000;
900 itp->it_value.tv_sec--;
903 itp->it_value.tv_usec = 0; /* sec is already 0 */
908 * Add and subtract routines for timevals.
909 * N.B.: subtract routine doesn't deal with
910 * results which are before the beginning,
911 * it just gets very confused in this case.
915 timevaladd(struct timeval *t1, const struct timeval *t2)
918 t1->tv_sec += t2->tv_sec;
919 t1->tv_usec += t2->tv_usec;
924 timevalsub(struct timeval *t1, const struct timeval *t2)
927 t1->tv_sec -= t2->tv_sec;
928 t1->tv_usec -= t2->tv_usec;
933 timevalfix(struct timeval *t1)
936 if (t1->tv_usec < 0) {
938 t1->tv_usec += 1000000;
940 if (t1->tv_usec >= 1000000) {
942 t1->tv_usec -= 1000000;
947 * ratecheck(): simple time-based rate-limit checking.
950 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
952 struct timeval tv, delta;
955 getmicrouptime(&tv); /* NB: 10ms precision */
957 timevalsub(&delta, lasttime);
960 * check for 0,0 is so that the message will be seen at least once,
961 * even if interval is huge.
963 if (timevalcmp(&delta, mininterval, >=) ||
964 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
973 * ppsratecheck(): packets (or events) per second limitation.
975 * Return 0 if the limit is to be enforced (e.g. the caller
976 * should drop a packet because of the rate limitation).
978 * maxpps of 0 always causes zero to be returned. maxpps of -1
979 * always causes 1 to be returned; this effectively defeats rate
982 * Note that we maintain the struct timeval for compatibility
983 * with other bsd systems. We reuse the storage and just monitor
984 * clock ticks for minimal overhead.
987 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
992 * Reset the last time and counter if this is the first call
993 * or more than a second has passed since the last update of
997 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
998 lasttime->tv_sec = now;
1000 return (maxpps != 0);
1002 (*curpps)++; /* NB: ignore potential overflow */
1003 return (maxpps < 0 || *curpps <= maxpps);
1010 struct kclock rt_clock = {
1011 .timer_create = realtimer_create,
1012 .timer_delete = realtimer_delete,
1013 .timer_settime = realtimer_settime,
1014 .timer_gettime = realtimer_gettime,
1018 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1019 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1020 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1021 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1022 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1023 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1024 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1025 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1026 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1027 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1028 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1032 register_posix_clock(int clockid, struct kclock *clk)
1034 if ((unsigned)clockid >= MAX_CLOCKS) {
1035 printf("%s: invalid clockid\n", __func__);
1038 posix_clocks[clockid] = *clk;
1043 itimer_init(void *mem, int size, int flags)
1047 it = (struct itimer *)mem;
1048 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1053 itimer_fini(void *mem, int size)
1057 it = (struct itimer *)mem;
1058 mtx_destroy(&it->it_mtx);
1062 itimer_enter(struct itimer *it)
1065 mtx_assert(&it->it_mtx, MA_OWNED);
1070 itimer_leave(struct itimer *it)
1073 mtx_assert(&it->it_mtx, MA_OWNED);
1074 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1076 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1080 #ifndef _SYS_SYSPROTO_H_
1081 struct ktimer_create_args {
1083 struct sigevent * evp;
1088 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1090 struct sigevent *evp, ev;
1094 if (uap->evp == NULL) {
1097 error = copyin(uap->evp, &ev, sizeof(ev));
1102 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1104 error = copyout(&id, uap->timerid, sizeof(int));
1106 kern_ktimer_delete(td, id);
1112 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1113 int *timerid, int preset_id)
1115 struct proc *p = td->td_proc;
1120 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1123 if (posix_clocks[clock_id].timer_create == NULL)
1127 if (evp->sigev_notify != SIGEV_NONE &&
1128 evp->sigev_notify != SIGEV_SIGNAL &&
1129 evp->sigev_notify != SIGEV_THREAD_ID)
1131 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1132 evp->sigev_notify == SIGEV_THREAD_ID) &&
1133 !_SIG_VALID(evp->sigev_signo))
1137 if (p->p_itimers == NULL)
1140 it = uma_zalloc(itimer_zone, M_WAITOK);
1142 it->it_usecount = 0;
1144 timespecclear(&it->it_time.it_value);
1145 timespecclear(&it->it_time.it_interval);
1147 it->it_overrun_last = 0;
1148 it->it_clockid = clock_id;
1149 it->it_timerid = -1;
1151 ksiginfo_init(&it->it_ksi);
1152 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1153 error = CLOCK_CALL(clock_id, timer_create, (it));
1158 if (preset_id != -1) {
1159 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1161 if (p->p_itimers->its_timers[id] != NULL) {
1168 * Find a free timer slot, skipping those reserved
1171 for (id = 3; id < TIMER_MAX; id++)
1172 if (p->p_itimers->its_timers[id] == NULL)
1174 if (id == TIMER_MAX) {
1180 it->it_timerid = id;
1181 p->p_itimers->its_timers[id] = it;
1183 it->it_sigev = *evp;
1185 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1188 case CLOCK_REALTIME:
1189 it->it_sigev.sigev_signo = SIGALRM;
1192 it->it_sigev.sigev_signo = SIGVTALRM;
1195 it->it_sigev.sigev_signo = SIGPROF;
1198 it->it_sigev.sigev_value.sival_int = id;
1201 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1202 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1203 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1204 it->it_ksi.ksi_code = SI_TIMER;
1205 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1206 it->it_ksi.ksi_timerid = id;
1214 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1216 uma_zfree(itimer_zone, it);
1220 #ifndef _SYS_SYSPROTO_H_
1221 struct ktimer_delete_args {
1226 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1229 return (kern_ktimer_delete(td, uap->timerid));
1232 static struct itimer *
1233 itimer_find(struct proc *p, int timerid)
1237 PROC_LOCK_ASSERT(p, MA_OWNED);
1238 if ((p->p_itimers == NULL) ||
1239 (timerid < 0) || (timerid >= TIMER_MAX) ||
1240 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1244 if ((it->it_flags & ITF_DELETING) != 0) {
1252 kern_ktimer_delete(struct thread *td, int timerid)
1254 struct proc *p = td->td_proc;
1258 it = itimer_find(p, timerid);
1265 it->it_flags |= ITF_DELETING;
1266 while (it->it_usecount > 0) {
1267 it->it_flags |= ITF_WANTED;
1268 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1270 it->it_flags &= ~ITF_WANTED;
1271 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1275 if (KSI_ONQ(&it->it_ksi))
1276 sigqueue_take(&it->it_ksi);
1277 p->p_itimers->its_timers[timerid] = NULL;
1279 uma_zfree(itimer_zone, it);
1283 #ifndef _SYS_SYSPROTO_H_
1284 struct ktimer_settime_args {
1287 const struct itimerspec * value;
1288 struct itimerspec * ovalue;
1292 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1294 struct itimerspec val, oval, *ovalp;
1297 error = copyin(uap->value, &val, sizeof(val));
1300 ovalp = uap->ovalue != NULL ? &oval : NULL;
1301 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1302 if (error == 0 && uap->ovalue != NULL)
1303 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1308 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1309 struct itimerspec *val, struct itimerspec *oval)
1317 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1323 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1331 #ifndef _SYS_SYSPROTO_H_
1332 struct ktimer_gettime_args {
1334 struct itimerspec * value;
1338 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1340 struct itimerspec val;
1343 error = kern_ktimer_gettime(td, uap->timerid, &val);
1345 error = copyout(&val, uap->value, sizeof(val));
1350 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1358 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1364 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1371 #ifndef _SYS_SYSPROTO_H_
1372 struct timer_getoverrun_args {
1377 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1380 return (kern_ktimer_getoverrun(td, uap->timerid));
1384 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1386 struct proc *p = td->td_proc;
1392 (it = itimer_find(p, timer_id)) == NULL) {
1396 td->td_retval[0] = it->it_overrun_last;
1405 realtimer_create(struct itimer *it)
1407 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1412 realtimer_delete(struct itimer *it)
1414 mtx_assert(&it->it_mtx, MA_OWNED);
1417 * clear timer's value and interval to tell realtimer_expire
1418 * to not rearm the timer.
1420 timespecclear(&it->it_time.it_value);
1421 timespecclear(&it->it_time.it_interval);
1423 callout_drain(&it->it_callout);
1429 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1431 struct timespec cts;
1433 mtx_assert(&it->it_mtx, MA_OWNED);
1435 realtimer_clocktime(it->it_clockid, &cts);
1436 *ovalue = it->it_time;
1437 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1438 timespecsub(&ovalue->it_value, &cts);
1439 if (ovalue->it_value.tv_sec < 0 ||
1440 (ovalue->it_value.tv_sec == 0 &&
1441 ovalue->it_value.tv_nsec == 0)) {
1442 ovalue->it_value.tv_sec = 0;
1443 ovalue->it_value.tv_nsec = 1;
1450 realtimer_settime(struct itimer *it, int flags,
1451 struct itimerspec *value, struct itimerspec *ovalue)
1453 struct timespec cts, ts;
1455 struct itimerspec val;
1457 mtx_assert(&it->it_mtx, MA_OWNED);
1460 if (itimespecfix(&val.it_value))
1463 if (timespecisset(&val.it_value)) {
1464 if (itimespecfix(&val.it_interval))
1467 timespecclear(&val.it_interval);
1471 realtimer_gettime(it, ovalue);
1474 if (timespecisset(&val.it_value)) {
1475 realtimer_clocktime(it->it_clockid, &cts);
1477 if ((flags & TIMER_ABSTIME) == 0) {
1478 /* Convert to absolute time. */
1479 timespecadd(&it->it_time.it_value, &cts);
1481 timespecsub(&ts, &cts);
1483 * We don't care if ts is negative, tztohz will
1487 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1488 callout_reset(&it->it_callout, tvtohz(&tv),
1489 realtimer_expire, it);
1491 callout_stop(&it->it_callout);
1498 realtimer_clocktime(clockid_t id, struct timespec *ts)
1500 if (id == CLOCK_REALTIME)
1502 else /* CLOCK_MONOTONIC */
1507 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1511 PROC_LOCK_ASSERT(p, MA_OWNED);
1512 it = itimer_find(p, timerid);
1514 ksi->ksi_overrun = it->it_overrun;
1515 it->it_overrun_last = it->it_overrun;
1524 itimespecfix(struct timespec *ts)
1527 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1529 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1530 ts->tv_nsec = tick * 1000;
1534 /* Timeout callback for realtime timer */
1536 realtimer_expire(void *arg)
1538 struct timespec cts, ts;
1542 it = (struct itimer *)arg;
1544 realtimer_clocktime(it->it_clockid, &cts);
1545 /* Only fire if time is reached. */
1546 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1547 if (timespecisset(&it->it_time.it_interval)) {
1548 timespecadd(&it->it_time.it_value,
1549 &it->it_time.it_interval);
1550 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1551 if (it->it_overrun < INT_MAX)
1554 it->it_ksi.ksi_errno = ERANGE;
1555 timespecadd(&it->it_time.it_value,
1556 &it->it_time.it_interval);
1559 /* single shot timer ? */
1560 timespecclear(&it->it_time.it_value);
1562 if (timespecisset(&it->it_time.it_value)) {
1563 ts = it->it_time.it_value;
1564 timespecsub(&ts, &cts);
1565 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1566 callout_reset(&it->it_callout, tvtohz(&tv),
1567 realtimer_expire, it);
1574 } else if (timespecisset(&it->it_time.it_value)) {
1575 ts = it->it_time.it_value;
1576 timespecsub(&ts, &cts);
1577 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1578 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1584 itimer_fire(struct itimer *it)
1586 struct proc *p = it->it_proc;
1589 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1590 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1591 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1593 timespecclear(&it->it_time.it_value);
1594 timespecclear(&it->it_time.it_interval);
1595 callout_stop(&it->it_callout);
1599 if (!KSI_ONQ(&it->it_ksi)) {
1600 it->it_ksi.ksi_errno = 0;
1601 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1602 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1604 if (it->it_overrun < INT_MAX)
1607 it->it_ksi.ksi_errno = ERANGE;
1614 itimers_alloc(struct proc *p)
1616 struct itimers *its;
1619 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1620 LIST_INIT(&its->its_virtual);
1621 LIST_INIT(&its->its_prof);
1622 TAILQ_INIT(&its->its_worklist);
1623 for (i = 0; i < TIMER_MAX; i++)
1624 its->its_timers[i] = NULL;
1626 if (p->p_itimers == NULL) {
1632 free(its, M_SUBPROC);
1637 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1639 itimers_event_hook_exit(arg, p);
1642 /* Clean up timers when some process events are being triggered. */
1644 itimers_event_hook_exit(void *arg, struct proc *p)
1646 struct itimers *its;
1648 int event = (int)(intptr_t)arg;
1651 if (p->p_itimers != NULL) {
1653 for (i = 0; i < MAX_CLOCKS; ++i) {
1654 if (posix_clocks[i].event_hook != NULL)
1655 CLOCK_CALL(i, event_hook, (p, i, event));
1658 * According to susv3, XSI interval timers should be inherited
1661 if (event == ITIMER_EV_EXEC)
1663 else if (event == ITIMER_EV_EXIT)
1666 panic("unhandled event");
1667 for (; i < TIMER_MAX; ++i) {
1668 if ((it = its->its_timers[i]) != NULL)
1669 kern_ktimer_delete(curthread, i);
1671 if (its->its_timers[0] == NULL &&
1672 its->its_timers[1] == NULL &&
1673 its->its_timers[2] == NULL) {
1674 free(its, M_SUBPROC);
1675 p->p_itimers = NULL;