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 ||
409 /* XXX Don't convert nsec->usec and back */
410 TIMESPEC_TO_TIMEVAL(&atv, ats);
411 error = settime(td, &atv);
415 #ifndef _SYS_SYSPROTO_H_
416 struct clock_getres_args {
422 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
430 error = kern_clock_getres(td, uap->clock_id, &ts);
432 error = copyout(&ts, uap->tp, sizeof(ts));
437 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
443 case CLOCK_REALTIME_FAST:
444 case CLOCK_REALTIME_PRECISE:
445 case CLOCK_MONOTONIC:
446 case CLOCK_MONOTONIC_FAST:
447 case CLOCK_MONOTONIC_PRECISE:
449 case CLOCK_UPTIME_FAST:
450 case CLOCK_UPTIME_PRECISE:
452 * Round up the result of the division cheaply by adding 1.
453 * Rounding up is especially important if rounding down
454 * would give 0. Perfect rounding is unimportant.
456 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
460 /* Accurately round up here because we can do so cheaply. */
461 ts->tv_nsec = howmany(1000000000, hz);
467 case CLOCK_THREAD_CPUTIME_ID:
468 case CLOCK_PROCESS_CPUTIME_ID:
470 /* sync with cputick2usec */
471 ts->tv_nsec = 1000000 / cpu_tickrate();
472 if (ts->tv_nsec == 0)
476 if ((int)clock_id < 0)
483 static uint8_t nanowait[MAXCPU];
486 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
489 sbintime_t sbt, sbtt, prec, tmp;
493 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
495 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
498 if (ts.tv_sec > INT32_MAX / 2) {
499 over = ts.tv_sec - INT32_MAX / 2;
506 if (TIMESEL(&sbt, tmp))
509 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
510 sbt, prec, C_ABSOLUTE);
511 if (error != EWOULDBLOCK) {
512 if (error == ERESTART)
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 && 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 ||
630 error = settime(td, tv);
632 if (tzp && error == 0) {
633 tz_minuteswest = tzp->tz_minuteswest;
634 tz_dsttime = tzp->tz_dsttime;
640 * Get value of an interval timer. The process virtual and profiling virtual
641 * time timers are kept in the p_stats area, since they can be swapped out.
642 * These are kept internally in the way they are specified externally: in
643 * time until they expire.
645 * The real time interval timer is kept in the process table slot for the
646 * process, and its value (it_value) is kept as an absolute time rather than
647 * as a delta, so that it is easy to keep periodic real-time signals from
650 * Virtual time timers are processed in the hardclock() routine of
651 * kern_clock.c. The real time timer is processed by a timeout routine,
652 * called from the softclock() routine. Since a callout may be delayed in
653 * real time due to interrupt processing in the system, it is possible for
654 * the real time timeout routine (realitexpire, given below), to be delayed
655 * in real time past when it is supposed to occur. It does not suffice,
656 * therefore, to reload the real timer .it_value from the real time timers
657 * .it_interval. Rather, we compute the next time in absolute time the timer
660 #ifndef _SYS_SYSPROTO_H_
661 struct getitimer_args {
663 struct itimerval *itv;
667 sys_getitimer(struct thread *td, struct getitimer_args *uap)
669 struct itimerval aitv;
672 error = kern_getitimer(td, uap->which, &aitv);
675 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
679 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
681 struct proc *p = td->td_proc;
684 if (which > ITIMER_PROF)
687 if (which == ITIMER_REAL) {
689 * Convert from absolute to relative time in .it_value
690 * part of real time timer. If time for real time timer
691 * has passed return 0, else return difference between
692 * current time and time for the timer to go off.
695 *aitv = p->p_realtimer;
697 if (timevalisset(&aitv->it_value)) {
699 if (timevalcmp(&aitv->it_value, &ctv, <))
700 timevalclear(&aitv->it_value);
702 timevalsub(&aitv->it_value, &ctv);
706 *aitv = p->p_stats->p_timer[which];
710 if (KTRPOINT(td, KTR_STRUCT))
716 #ifndef _SYS_SYSPROTO_H_
717 struct setitimer_args {
719 struct itimerval *itv, *oitv;
723 sys_setitimer(struct thread *td, struct setitimer_args *uap)
725 struct itimerval aitv, oitv;
728 if (uap->itv == NULL) {
729 uap->itv = uap->oitv;
730 return (sys_getitimer(td, (struct getitimer_args *)uap));
733 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
735 error = kern_setitimer(td, uap->which, &aitv, &oitv);
736 if (error != 0 || uap->oitv == NULL)
738 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
742 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
743 struct itimerval *oitv)
745 struct proc *p = td->td_proc;
750 return (kern_getitimer(td, which, oitv));
752 if (which > ITIMER_PROF)
755 if (KTRPOINT(td, KTR_STRUCT))
758 if (itimerfix(&aitv->it_value) ||
759 aitv->it_value.tv_sec > INT32_MAX / 2)
761 if (!timevalisset(&aitv->it_value))
762 timevalclear(&aitv->it_interval);
763 else if (itimerfix(&aitv->it_interval) ||
764 aitv->it_interval.tv_sec > INT32_MAX / 2)
767 if (which == ITIMER_REAL) {
769 if (timevalisset(&p->p_realtimer.it_value))
770 callout_stop(&p->p_itcallout);
772 if (timevalisset(&aitv->it_value)) {
773 pr = tvtosbt(aitv->it_value) >> tc_precexp;
774 timevaladd(&aitv->it_value, &ctv);
775 sbt = tvtosbt(aitv->it_value);
776 callout_reset_sbt(&p->p_itcallout, sbt, pr,
777 realitexpire, p, C_ABSOLUTE);
779 *oitv = p->p_realtimer;
780 p->p_realtimer = *aitv;
782 if (timevalisset(&oitv->it_value)) {
783 if (timevalcmp(&oitv->it_value, &ctv, <))
784 timevalclear(&oitv->it_value);
786 timevalsub(&oitv->it_value, &ctv);
789 if (aitv->it_interval.tv_sec == 0 &&
790 aitv->it_interval.tv_usec != 0 &&
791 aitv->it_interval.tv_usec < tick)
792 aitv->it_interval.tv_usec = tick;
793 if (aitv->it_value.tv_sec == 0 &&
794 aitv->it_value.tv_usec != 0 &&
795 aitv->it_value.tv_usec < tick)
796 aitv->it_value.tv_usec = tick;
798 *oitv = p->p_stats->p_timer[which];
799 p->p_stats->p_timer[which] = *aitv;
803 if (KTRPOINT(td, KTR_STRUCT))
810 * Real interval timer expired:
811 * send process whose timer expired an alarm signal.
812 * If time is not set up to reload, then just return.
813 * Else compute next time timer should go off which is > current time.
814 * This is where delay in processing this timeout causes multiple
815 * SIGALRM calls to be compressed into one.
816 * tvtohz() always adds 1 to allow for the time until the next clock
817 * interrupt being strictly less than 1 clock tick, but we don't want
818 * that here since we want to appear to be in sync with the clock
819 * interrupt even when we're delayed.
822 realitexpire(void *arg)
828 p = (struct proc *)arg;
829 kern_psignal(p, SIGALRM);
830 if (!timevalisset(&p->p_realtimer.it_interval)) {
831 timevalclear(&p->p_realtimer.it_value);
832 if (p->p_flag & P_WEXIT)
833 wakeup(&p->p_itcallout);
836 isbt = tvtosbt(p->p_realtimer.it_interval);
837 if (isbt >= sbt_timethreshold)
838 getmicrouptime(&ctv);
842 timevaladd(&p->p_realtimer.it_value,
843 &p->p_realtimer.it_interval);
844 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
845 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
846 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
850 * Check that a proposed value to load into the .it_value or
851 * .it_interval part of an interval timer is acceptable, and
852 * fix it to have at least minimal value (i.e. if it is less
853 * than the resolution of the clock, round it up.)
856 itimerfix(struct timeval *tv)
859 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
861 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
862 tv->tv_usec < (u_int)tick / 16)
863 tv->tv_usec = (u_int)tick / 16;
868 * Decrement an interval timer by a specified number
869 * of microseconds, which must be less than a second,
870 * i.e. < 1000000. If the timer expires, then reload
871 * it. In this case, carry over (usec - old value) to
872 * reduce the value reloaded into the timer so that
873 * the timer does not drift. This routine assumes
874 * that it is called in a context where the timers
875 * on which it is operating cannot change in value.
878 itimerdecr(struct itimerval *itp, int usec)
881 if (itp->it_value.tv_usec < usec) {
882 if (itp->it_value.tv_sec == 0) {
883 /* expired, and already in next interval */
884 usec -= itp->it_value.tv_usec;
887 itp->it_value.tv_usec += 1000000;
888 itp->it_value.tv_sec--;
890 itp->it_value.tv_usec -= usec;
892 if (timevalisset(&itp->it_value))
894 /* expired, exactly at end of interval */
896 if (timevalisset(&itp->it_interval)) {
897 itp->it_value = itp->it_interval;
898 itp->it_value.tv_usec -= usec;
899 if (itp->it_value.tv_usec < 0) {
900 itp->it_value.tv_usec += 1000000;
901 itp->it_value.tv_sec--;
904 itp->it_value.tv_usec = 0; /* sec is already 0 */
909 * Add and subtract routines for timevals.
910 * N.B.: subtract routine doesn't deal with
911 * results which are before the beginning,
912 * it just gets very confused in this case.
916 timevaladd(struct timeval *t1, const struct timeval *t2)
919 t1->tv_sec += t2->tv_sec;
920 t1->tv_usec += t2->tv_usec;
925 timevalsub(struct timeval *t1, const struct timeval *t2)
928 t1->tv_sec -= t2->tv_sec;
929 t1->tv_usec -= t2->tv_usec;
934 timevalfix(struct timeval *t1)
937 if (t1->tv_usec < 0) {
939 t1->tv_usec += 1000000;
941 if (t1->tv_usec >= 1000000) {
943 t1->tv_usec -= 1000000;
948 * ratecheck(): simple time-based rate-limit checking.
951 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
953 struct timeval tv, delta;
956 getmicrouptime(&tv); /* NB: 10ms precision */
958 timevalsub(&delta, lasttime);
961 * check for 0,0 is so that the message will be seen at least once,
962 * even if interval is huge.
964 if (timevalcmp(&delta, mininterval, >=) ||
965 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
974 * ppsratecheck(): packets (or events) per second limitation.
976 * Return 0 if the limit is to be enforced (e.g. the caller
977 * should drop a packet because of the rate limitation).
979 * maxpps of 0 always causes zero to be returned. maxpps of -1
980 * always causes 1 to be returned; this effectively defeats rate
983 * Note that we maintain the struct timeval for compatibility
984 * with other bsd systems. We reuse the storage and just monitor
985 * clock ticks for minimal overhead.
988 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
993 * Reset the last time and counter if this is the first call
994 * or more than a second has passed since the last update of
998 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
999 lasttime->tv_sec = now;
1001 return (maxpps != 0);
1003 (*curpps)++; /* NB: ignore potential overflow */
1004 return (maxpps < 0 || *curpps <= maxpps);
1011 struct kclock rt_clock = {
1012 .timer_create = realtimer_create,
1013 .timer_delete = realtimer_delete,
1014 .timer_settime = realtimer_settime,
1015 .timer_gettime = realtimer_gettime,
1019 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1020 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1021 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1022 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1023 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1024 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1025 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1026 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1027 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1028 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1029 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1033 register_posix_clock(int clockid, struct kclock *clk)
1035 if ((unsigned)clockid >= MAX_CLOCKS) {
1036 printf("%s: invalid clockid\n", __func__);
1039 posix_clocks[clockid] = *clk;
1044 itimer_init(void *mem, int size, int flags)
1048 it = (struct itimer *)mem;
1049 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1054 itimer_fini(void *mem, int size)
1058 it = (struct itimer *)mem;
1059 mtx_destroy(&it->it_mtx);
1063 itimer_enter(struct itimer *it)
1066 mtx_assert(&it->it_mtx, MA_OWNED);
1071 itimer_leave(struct itimer *it)
1074 mtx_assert(&it->it_mtx, MA_OWNED);
1075 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1077 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1081 #ifndef _SYS_SYSPROTO_H_
1082 struct ktimer_create_args {
1084 struct sigevent * evp;
1089 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1091 struct sigevent *evp, ev;
1095 if (uap->evp == NULL) {
1098 error = copyin(uap->evp, &ev, sizeof(ev));
1103 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1105 error = copyout(&id, uap->timerid, sizeof(int));
1107 kern_ktimer_delete(td, id);
1113 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1114 int *timerid, int preset_id)
1116 struct proc *p = td->td_proc;
1121 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1124 if (posix_clocks[clock_id].timer_create == NULL)
1128 if (evp->sigev_notify != SIGEV_NONE &&
1129 evp->sigev_notify != SIGEV_SIGNAL &&
1130 evp->sigev_notify != SIGEV_THREAD_ID)
1132 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1133 evp->sigev_notify == SIGEV_THREAD_ID) &&
1134 !_SIG_VALID(evp->sigev_signo))
1138 if (p->p_itimers == NULL)
1141 it = uma_zalloc(itimer_zone, M_WAITOK);
1143 it->it_usecount = 0;
1145 timespecclear(&it->it_time.it_value);
1146 timespecclear(&it->it_time.it_interval);
1148 it->it_overrun_last = 0;
1149 it->it_clockid = clock_id;
1150 it->it_timerid = -1;
1152 ksiginfo_init(&it->it_ksi);
1153 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1154 error = CLOCK_CALL(clock_id, timer_create, (it));
1159 if (preset_id != -1) {
1160 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1162 if (p->p_itimers->its_timers[id] != NULL) {
1169 * Find a free timer slot, skipping those reserved
1172 for (id = 3; id < TIMER_MAX; id++)
1173 if (p->p_itimers->its_timers[id] == NULL)
1175 if (id == TIMER_MAX) {
1181 it->it_timerid = id;
1182 p->p_itimers->its_timers[id] = it;
1184 it->it_sigev = *evp;
1186 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1189 case CLOCK_REALTIME:
1190 it->it_sigev.sigev_signo = SIGALRM;
1193 it->it_sigev.sigev_signo = SIGVTALRM;
1196 it->it_sigev.sigev_signo = SIGPROF;
1199 it->it_sigev.sigev_value.sival_int = id;
1202 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1203 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1204 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1205 it->it_ksi.ksi_code = SI_TIMER;
1206 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1207 it->it_ksi.ksi_timerid = id;
1215 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1217 uma_zfree(itimer_zone, it);
1221 #ifndef _SYS_SYSPROTO_H_
1222 struct ktimer_delete_args {
1227 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1230 return (kern_ktimer_delete(td, uap->timerid));
1233 static struct itimer *
1234 itimer_find(struct proc *p, int timerid)
1238 PROC_LOCK_ASSERT(p, MA_OWNED);
1239 if ((p->p_itimers == NULL) ||
1240 (timerid < 0) || (timerid >= TIMER_MAX) ||
1241 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1245 if ((it->it_flags & ITF_DELETING) != 0) {
1253 kern_ktimer_delete(struct thread *td, int timerid)
1255 struct proc *p = td->td_proc;
1259 it = itimer_find(p, timerid);
1266 it->it_flags |= ITF_DELETING;
1267 while (it->it_usecount > 0) {
1268 it->it_flags |= ITF_WANTED;
1269 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1271 it->it_flags &= ~ITF_WANTED;
1272 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1276 if (KSI_ONQ(&it->it_ksi))
1277 sigqueue_take(&it->it_ksi);
1278 p->p_itimers->its_timers[timerid] = NULL;
1280 uma_zfree(itimer_zone, it);
1284 #ifndef _SYS_SYSPROTO_H_
1285 struct ktimer_settime_args {
1288 const struct itimerspec * value;
1289 struct itimerspec * ovalue;
1293 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1295 struct itimerspec val, oval, *ovalp;
1298 error = copyin(uap->value, &val, sizeof(val));
1301 ovalp = uap->ovalue != NULL ? &oval : NULL;
1302 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1303 if (error == 0 && uap->ovalue != NULL)
1304 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1309 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1310 struct itimerspec *val, struct itimerspec *oval)
1318 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1324 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1332 #ifndef _SYS_SYSPROTO_H_
1333 struct ktimer_gettime_args {
1335 struct itimerspec * value;
1339 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1341 struct itimerspec val;
1344 error = kern_ktimer_gettime(td, uap->timerid, &val);
1346 error = copyout(&val, uap->value, sizeof(val));
1351 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1359 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1365 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1372 #ifndef _SYS_SYSPROTO_H_
1373 struct timer_getoverrun_args {
1378 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1381 return (kern_ktimer_getoverrun(td, uap->timerid));
1385 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1387 struct proc *p = td->td_proc;
1393 (it = itimer_find(p, timer_id)) == NULL) {
1397 td->td_retval[0] = it->it_overrun_last;
1406 realtimer_create(struct itimer *it)
1408 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1413 realtimer_delete(struct itimer *it)
1415 mtx_assert(&it->it_mtx, MA_OWNED);
1418 * clear timer's value and interval to tell realtimer_expire
1419 * to not rearm the timer.
1421 timespecclear(&it->it_time.it_value);
1422 timespecclear(&it->it_time.it_interval);
1424 callout_drain(&it->it_callout);
1430 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1432 struct timespec cts;
1434 mtx_assert(&it->it_mtx, MA_OWNED);
1436 realtimer_clocktime(it->it_clockid, &cts);
1437 *ovalue = it->it_time;
1438 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1439 timespecsub(&ovalue->it_value, &cts);
1440 if (ovalue->it_value.tv_sec < 0 ||
1441 (ovalue->it_value.tv_sec == 0 &&
1442 ovalue->it_value.tv_nsec == 0)) {
1443 ovalue->it_value.tv_sec = 0;
1444 ovalue->it_value.tv_nsec = 1;
1451 realtimer_settime(struct itimer *it, int flags,
1452 struct itimerspec *value, struct itimerspec *ovalue)
1454 struct timespec cts, ts;
1456 struct itimerspec val;
1458 mtx_assert(&it->it_mtx, MA_OWNED);
1461 if (itimespecfix(&val.it_value))
1464 if (timespecisset(&val.it_value)) {
1465 if (itimespecfix(&val.it_interval))
1468 timespecclear(&val.it_interval);
1472 realtimer_gettime(it, ovalue);
1475 if (timespecisset(&val.it_value)) {
1476 realtimer_clocktime(it->it_clockid, &cts);
1478 if ((flags & TIMER_ABSTIME) == 0) {
1479 /* Convert to absolute time. */
1480 timespecadd(&it->it_time.it_value, &cts);
1482 timespecsub(&ts, &cts);
1484 * We don't care if ts is negative, tztohz will
1488 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1489 callout_reset(&it->it_callout, tvtohz(&tv),
1490 realtimer_expire, it);
1492 callout_stop(&it->it_callout);
1499 realtimer_clocktime(clockid_t id, struct timespec *ts)
1501 if (id == CLOCK_REALTIME)
1503 else /* CLOCK_MONOTONIC */
1508 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1512 PROC_LOCK_ASSERT(p, MA_OWNED);
1513 it = itimer_find(p, timerid);
1515 ksi->ksi_overrun = it->it_overrun;
1516 it->it_overrun_last = it->it_overrun;
1525 itimespecfix(struct timespec *ts)
1528 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1530 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1531 ts->tv_nsec = tick * 1000;
1535 /* Timeout callback for realtime timer */
1537 realtimer_expire(void *arg)
1539 struct timespec cts, ts;
1543 it = (struct itimer *)arg;
1545 realtimer_clocktime(it->it_clockid, &cts);
1546 /* Only fire if time is reached. */
1547 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1548 if (timespecisset(&it->it_time.it_interval)) {
1549 timespecadd(&it->it_time.it_value,
1550 &it->it_time.it_interval);
1551 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1552 if (it->it_overrun < INT_MAX)
1555 it->it_ksi.ksi_errno = ERANGE;
1556 timespecadd(&it->it_time.it_value,
1557 &it->it_time.it_interval);
1560 /* single shot timer ? */
1561 timespecclear(&it->it_time.it_value);
1563 if (timespecisset(&it->it_time.it_value)) {
1564 ts = it->it_time.it_value;
1565 timespecsub(&ts, &cts);
1566 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1567 callout_reset(&it->it_callout, tvtohz(&tv),
1568 realtimer_expire, it);
1575 } else if (timespecisset(&it->it_time.it_value)) {
1576 ts = it->it_time.it_value;
1577 timespecsub(&ts, &cts);
1578 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1579 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1585 itimer_fire(struct itimer *it)
1587 struct proc *p = it->it_proc;
1590 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1591 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1592 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1594 timespecclear(&it->it_time.it_value);
1595 timespecclear(&it->it_time.it_interval);
1596 callout_stop(&it->it_callout);
1600 if (!KSI_ONQ(&it->it_ksi)) {
1601 it->it_ksi.ksi_errno = 0;
1602 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1603 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1605 if (it->it_overrun < INT_MAX)
1608 it->it_ksi.ksi_errno = ERANGE;
1615 itimers_alloc(struct proc *p)
1617 struct itimers *its;
1620 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1621 LIST_INIT(&its->its_virtual);
1622 LIST_INIT(&its->its_prof);
1623 TAILQ_INIT(&its->its_worklist);
1624 for (i = 0; i < TIMER_MAX; i++)
1625 its->its_timers[i] = NULL;
1627 if (p->p_itimers == NULL) {
1633 free(its, M_SUBPROC);
1638 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1640 itimers_event_hook_exit(arg, p);
1643 /* Clean up timers when some process events are being triggered. */
1645 itimers_event_hook_exit(void *arg, struct proc *p)
1647 struct itimers *its;
1649 int event = (int)(intptr_t)arg;
1652 if (p->p_itimers != NULL) {
1654 for (i = 0; i < MAX_CLOCKS; ++i) {
1655 if (posix_clocks[i].event_hook != NULL)
1656 CLOCK_CALL(i, event_hook, (p, i, event));
1659 * According to susv3, XSI interval timers should be inherited
1662 if (event == ITIMER_EV_EXEC)
1664 else if (event == ITIMER_EV_EXIT)
1667 panic("unhandled event");
1668 for (; i < TIMER_MAX; ++i) {
1669 if ((it = its->its_timers[i]) != NULL)
1670 kern_ktimer_delete(curthread, i);
1672 if (its->its_timers[0] == NULL &&
1673 its->its_timers[1] == NULL &&
1674 its->its_timers[2] == NULL) {
1675 free(its, M_SUBPROC);
1676 p->p_itimers = NULL;