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;
126 timevalsub(&delta, &tv1);
129 * If the system is secure, we do not allow the time to be
130 * set to a value earlier than 1 second less than the highest
131 * time we have yet seen. The worst a miscreant can do in
132 * this circumstance is "freeze" time. He couldn't go
135 * We similarly do not allow the clock to be stepped more
136 * than one second, nor more than once per second. This allows
137 * a miscreant to make the clock march double-time, but no worse.
139 if (securelevel_gt(td->td_ucred, 1) != 0) {
140 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
142 * Update maxtime to latest time we've seen.
144 if (tv1.tv_sec > maxtime.tv_sec)
147 timevalsub(&tv2, &maxtime);
148 if (tv2.tv_sec < -1) {
149 tv->tv_sec = maxtime.tv_sec - 1;
150 printf("Time adjustment clamped to -1 second\n");
153 if (tv1.tv_sec == laststep.tv_sec)
155 if (delta.tv_sec > 1) {
156 tv->tv_sec = tv1.tv_sec + 1;
157 printf("Time adjustment clamped to +1 second\n");
163 ts.tv_sec = tv->tv_sec;
164 ts.tv_nsec = tv->tv_usec * 1000;
170 #ifndef _SYS_SYSPROTO_H_
171 struct clock_getcpuclockid2_args {
179 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
184 error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
186 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
191 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
200 case CPUCLOCK_WHICH_PID:
202 error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
208 pid = td->td_proc->p_pid;
210 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
212 case CPUCLOCK_WHICH_TID:
213 tid = id == 0 ? td->td_tid : id;
214 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
221 #ifndef _SYS_SYSPROTO_H_
222 struct clock_gettime_args {
229 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
234 error = kern_clock_gettime(td, uap->clock_id, &ats);
236 error = copyout(&ats, uap->tp, sizeof(ats));
242 cputick2timespec(uint64_t runtime, struct timespec *ats)
244 runtime = cputick2usec(runtime);
245 ats->tv_sec = runtime / 1000000;
246 ats->tv_nsec = runtime % 1000000 * 1000;
250 get_thread_cputime(struct thread *targettd, struct timespec *ats)
252 uint64_t runtime, curtime, switchtime;
254 if (targettd == NULL) { /* current thread */
256 switchtime = PCPU_GET(switchtime);
257 curtime = cpu_ticks();
258 runtime = curthread->td_runtime;
260 runtime += curtime - switchtime;
262 thread_lock(targettd);
263 runtime = targettd->td_runtime;
264 thread_unlock(targettd);
266 cputick2timespec(runtime, ats);
270 get_process_cputime(struct proc *targetp, struct timespec *ats)
275 PROC_STATLOCK(targetp);
276 rufetch(targetp, &ru);
277 runtime = targetp->p_rux.rux_runtime;
278 PROC_STATUNLOCK(targetp);
279 cputick2timespec(runtime, ats);
283 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
292 if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
293 tid = clock_id & CPUCLOCK_ID_MASK;
294 td2 = tdfind(tid, p->p_pid);
297 get_thread_cputime(td2, ats);
298 PROC_UNLOCK(td2->td_proc);
300 pid = clock_id & CPUCLOCK_ID_MASK;
301 error = pget(pid, PGET_CANSEE, &p2);
304 get_process_cputime(p2, ats);
311 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
313 struct timeval sys, user;
318 case CLOCK_REALTIME: /* Default to precise. */
319 case CLOCK_REALTIME_PRECISE:
322 case CLOCK_REALTIME_FAST:
328 calcru(p, &user, &sys);
331 TIMEVAL_TO_TIMESPEC(&user, ats);
336 calcru(p, &user, &sys);
339 timevaladd(&user, &sys);
340 TIMEVAL_TO_TIMESPEC(&user, ats);
342 case CLOCK_MONOTONIC: /* Default to precise. */
343 case CLOCK_MONOTONIC_PRECISE:
345 case CLOCK_UPTIME_PRECISE:
348 case CLOCK_UPTIME_FAST:
349 case CLOCK_MONOTONIC_FAST:
353 ats->tv_sec = time_second;
356 case CLOCK_THREAD_CPUTIME_ID:
357 get_thread_cputime(NULL, ats);
359 case CLOCK_PROCESS_CPUTIME_ID:
361 get_process_cputime(p, ats);
365 if ((int)clock_id >= 0)
367 return (get_cputime(td, clock_id, ats));
372 #ifndef _SYS_SYSPROTO_H_
373 struct clock_settime_args {
375 const struct timespec *tp;
380 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
385 if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
387 return (kern_clock_settime(td, uap->clock_id, &ats));
391 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
396 if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
398 if (clock_id != CLOCK_REALTIME)
400 if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
403 /* XXX Don't convert nsec->usec and back */
404 TIMESPEC_TO_TIMEVAL(&atv, ats);
405 error = settime(td, &atv);
409 #ifndef _SYS_SYSPROTO_H_
410 struct clock_getres_args {
416 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
424 error = kern_clock_getres(td, uap->clock_id, &ts);
426 error = copyout(&ts, uap->tp, sizeof(ts));
431 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
437 case CLOCK_REALTIME_FAST:
438 case CLOCK_REALTIME_PRECISE:
439 case CLOCK_MONOTONIC:
440 case CLOCK_MONOTONIC_FAST:
441 case CLOCK_MONOTONIC_PRECISE:
443 case CLOCK_UPTIME_FAST:
444 case CLOCK_UPTIME_PRECISE:
446 * Round up the result of the division cheaply by adding 1.
447 * Rounding up is especially important if rounding down
448 * would give 0. Perfect rounding is unimportant.
450 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
454 /* Accurately round up here because we can do so cheaply. */
455 ts->tv_nsec = howmany(1000000000, hz);
461 case CLOCK_THREAD_CPUTIME_ID:
462 case CLOCK_PROCESS_CPUTIME_ID:
464 /* sync with cputick2usec */
465 ts->tv_nsec = 1000000 / cpu_tickrate();
466 if (ts->tv_nsec == 0)
470 if ((int)clock_id < 0)
477 static uint8_t nanowait[MAXCPU];
480 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
483 sbintime_t sbt, sbtt, prec, tmp;
487 if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
489 if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
492 if (ts.tv_sec > INT32_MAX / 2) {
493 over = ts.tv_sec - INT32_MAX / 2;
500 if (TIMESEL(&sbt, tmp))
503 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
504 sbt, prec, C_ABSOLUTE);
505 if (error != EWOULDBLOCK) {
506 if (error == ERESTART)
510 ts = sbttots(sbt - sbtt);
523 #ifndef _SYS_SYSPROTO_H_
524 struct nanosleep_args {
525 struct timespec *rqtp;
526 struct timespec *rmtp;
531 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
533 struct timespec rmt, rqt;
536 error = copyin(uap->rqtp, &rqt, sizeof(rqt));
541 !useracc((caddr_t)uap->rmtp, sizeof(rmt), VM_PROT_WRITE))
543 error = kern_nanosleep(td, &rqt, &rmt);
544 if (error && uap->rmtp) {
547 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
554 #ifndef _SYS_SYSPROTO_H_
555 struct gettimeofday_args {
557 struct timezone *tzp;
562 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
570 error = copyout(&atv, uap->tp, sizeof (atv));
572 if (error == 0 && uap->tzp != NULL) {
573 rtz.tz_minuteswest = tz_minuteswest;
574 rtz.tz_dsttime = tz_dsttime;
575 error = copyout(&rtz, uap->tzp, sizeof (rtz));
580 #ifndef _SYS_SYSPROTO_H_
581 struct settimeofday_args {
583 struct timezone *tzp;
588 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
590 struct timeval atv, *tvp;
591 struct timezone atz, *tzp;
595 error = copyin(uap->tv, &atv, sizeof(atv));
602 error = copyin(uap->tzp, &atz, sizeof(atz));
608 return (kern_settimeofday(td, tvp, tzp));
612 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
616 error = priv_check(td, PRIV_SETTIMEOFDAY);
619 /* Verify all parameters before changing time. */
621 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
624 error = settime(td, tv);
626 if (tzp && error == 0) {
627 tz_minuteswest = tzp->tz_minuteswest;
628 tz_dsttime = tzp->tz_dsttime;
634 * Get value of an interval timer. The process virtual and profiling virtual
635 * time timers are kept in the p_stats area, since they can be swapped out.
636 * These are kept internally in the way they are specified externally: in
637 * time until they expire.
639 * The real time interval timer is kept in the process table slot for the
640 * process, and its value (it_value) is kept as an absolute time rather than
641 * as a delta, so that it is easy to keep periodic real-time signals from
644 * Virtual time timers are processed in the hardclock() routine of
645 * kern_clock.c. The real time timer is processed by a timeout routine,
646 * called from the softclock() routine. Since a callout may be delayed in
647 * real time due to interrupt processing in the system, it is possible for
648 * the real time timeout routine (realitexpire, given below), to be delayed
649 * in real time past when it is supposed to occur. It does not suffice,
650 * therefore, to reload the real timer .it_value from the real time timers
651 * .it_interval. Rather, we compute the next time in absolute time the timer
654 #ifndef _SYS_SYSPROTO_H_
655 struct getitimer_args {
657 struct itimerval *itv;
661 sys_getitimer(struct thread *td, struct getitimer_args *uap)
663 struct itimerval aitv;
666 error = kern_getitimer(td, uap->which, &aitv);
669 return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
673 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
675 struct proc *p = td->td_proc;
678 if (which > ITIMER_PROF)
681 if (which == ITIMER_REAL) {
683 * Convert from absolute to relative time in .it_value
684 * part of real time timer. If time for real time timer
685 * has passed return 0, else return difference between
686 * current time and time for the timer to go off.
689 *aitv = p->p_realtimer;
691 if (timevalisset(&aitv->it_value)) {
693 if (timevalcmp(&aitv->it_value, &ctv, <))
694 timevalclear(&aitv->it_value);
696 timevalsub(&aitv->it_value, &ctv);
700 *aitv = p->p_stats->p_timer[which];
704 if (KTRPOINT(td, KTR_STRUCT))
710 #ifndef _SYS_SYSPROTO_H_
711 struct setitimer_args {
713 struct itimerval *itv, *oitv;
717 sys_setitimer(struct thread *td, struct setitimer_args *uap)
719 struct itimerval aitv, oitv;
722 if (uap->itv == NULL) {
723 uap->itv = uap->oitv;
724 return (sys_getitimer(td, (struct getitimer_args *)uap));
727 if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
729 error = kern_setitimer(td, uap->which, &aitv, &oitv);
730 if (error != 0 || uap->oitv == NULL)
732 return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
736 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
737 struct itimerval *oitv)
739 struct proc *p = td->td_proc;
744 return (kern_getitimer(td, which, oitv));
746 if (which > ITIMER_PROF)
749 if (KTRPOINT(td, KTR_STRUCT))
752 if (itimerfix(&aitv->it_value) ||
753 aitv->it_value.tv_sec > INT32_MAX / 2)
755 if (!timevalisset(&aitv->it_value))
756 timevalclear(&aitv->it_interval);
757 else if (itimerfix(&aitv->it_interval) ||
758 aitv->it_interval.tv_sec > INT32_MAX / 2)
761 if (which == ITIMER_REAL) {
763 if (timevalisset(&p->p_realtimer.it_value))
764 callout_stop(&p->p_itcallout);
766 if (timevalisset(&aitv->it_value)) {
767 pr = tvtosbt(aitv->it_value) >> tc_precexp;
768 timevaladd(&aitv->it_value, &ctv);
769 sbt = tvtosbt(aitv->it_value);
770 callout_reset_sbt(&p->p_itcallout, sbt, pr,
771 realitexpire, p, C_ABSOLUTE);
773 *oitv = p->p_realtimer;
774 p->p_realtimer = *aitv;
776 if (timevalisset(&oitv->it_value)) {
777 if (timevalcmp(&oitv->it_value, &ctv, <))
778 timevalclear(&oitv->it_value);
780 timevalsub(&oitv->it_value, &ctv);
783 if (aitv->it_interval.tv_sec == 0 &&
784 aitv->it_interval.tv_usec != 0 &&
785 aitv->it_interval.tv_usec < tick)
786 aitv->it_interval.tv_usec = tick;
787 if (aitv->it_value.tv_sec == 0 &&
788 aitv->it_value.tv_usec != 0 &&
789 aitv->it_value.tv_usec < tick)
790 aitv->it_value.tv_usec = tick;
792 *oitv = p->p_stats->p_timer[which];
793 p->p_stats->p_timer[which] = *aitv;
797 if (KTRPOINT(td, KTR_STRUCT))
804 * Real interval timer expired:
805 * send process whose timer expired an alarm signal.
806 * If time is not set up to reload, then just return.
807 * Else compute next time timer should go off which is > current time.
808 * This is where delay in processing this timeout causes multiple
809 * SIGALRM calls to be compressed into one.
810 * tvtohz() always adds 1 to allow for the time until the next clock
811 * interrupt being strictly less than 1 clock tick, but we don't want
812 * that here since we want to appear to be in sync with the clock
813 * interrupt even when we're delayed.
816 realitexpire(void *arg)
822 p = (struct proc *)arg;
823 kern_psignal(p, SIGALRM);
824 if (!timevalisset(&p->p_realtimer.it_interval)) {
825 timevalclear(&p->p_realtimer.it_value);
826 if (p->p_flag & P_WEXIT)
827 wakeup(&p->p_itcallout);
830 isbt = tvtosbt(p->p_realtimer.it_interval);
831 if (isbt >= sbt_timethreshold)
832 getmicrouptime(&ctv);
836 timevaladd(&p->p_realtimer.it_value,
837 &p->p_realtimer.it_interval);
838 } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
839 callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
840 isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
844 * Check that a proposed value to load into the .it_value or
845 * .it_interval part of an interval timer is acceptable, and
846 * fix it to have at least minimal value (i.e. if it is less
847 * than the resolution of the clock, round it up.)
850 itimerfix(struct timeval *tv)
853 if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
855 if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
856 tv->tv_usec < (u_int)tick / 16)
857 tv->tv_usec = (u_int)tick / 16;
862 * Decrement an interval timer by a specified number
863 * of microseconds, which must be less than a second,
864 * i.e. < 1000000. If the timer expires, then reload
865 * it. In this case, carry over (usec - old value) to
866 * reduce the value reloaded into the timer so that
867 * the timer does not drift. This routine assumes
868 * that it is called in a context where the timers
869 * on which it is operating cannot change in value.
872 itimerdecr(struct itimerval *itp, int usec)
875 if (itp->it_value.tv_usec < usec) {
876 if (itp->it_value.tv_sec == 0) {
877 /* expired, and already in next interval */
878 usec -= itp->it_value.tv_usec;
881 itp->it_value.tv_usec += 1000000;
882 itp->it_value.tv_sec--;
884 itp->it_value.tv_usec -= usec;
886 if (timevalisset(&itp->it_value))
888 /* expired, exactly at end of interval */
890 if (timevalisset(&itp->it_interval)) {
891 itp->it_value = itp->it_interval;
892 itp->it_value.tv_usec -= usec;
893 if (itp->it_value.tv_usec < 0) {
894 itp->it_value.tv_usec += 1000000;
895 itp->it_value.tv_sec--;
898 itp->it_value.tv_usec = 0; /* sec is already 0 */
903 * Add and subtract routines for timevals.
904 * N.B.: subtract routine doesn't deal with
905 * results which are before the beginning,
906 * it just gets very confused in this case.
910 timevaladd(struct timeval *t1, const struct timeval *t2)
913 t1->tv_sec += t2->tv_sec;
914 t1->tv_usec += t2->tv_usec;
919 timevalsub(struct timeval *t1, const struct timeval *t2)
922 t1->tv_sec -= t2->tv_sec;
923 t1->tv_usec -= t2->tv_usec;
928 timevalfix(struct timeval *t1)
931 if (t1->tv_usec < 0) {
933 t1->tv_usec += 1000000;
935 if (t1->tv_usec >= 1000000) {
937 t1->tv_usec -= 1000000;
942 * ratecheck(): simple time-based rate-limit checking.
945 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
947 struct timeval tv, delta;
950 getmicrouptime(&tv); /* NB: 10ms precision */
952 timevalsub(&delta, lasttime);
955 * check for 0,0 is so that the message will be seen at least once,
956 * even if interval is huge.
958 if (timevalcmp(&delta, mininterval, >=) ||
959 (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
968 * ppsratecheck(): packets (or events) per second limitation.
970 * Return 0 if the limit is to be enforced (e.g. the caller
971 * should drop a packet because of the rate limitation).
973 * maxpps of 0 always causes zero to be returned. maxpps of -1
974 * always causes 1 to be returned; this effectively defeats rate
977 * Note that we maintain the struct timeval for compatibility
978 * with other bsd systems. We reuse the storage and just monitor
979 * clock ticks for minimal overhead.
982 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
987 * Reset the last time and counter if this is the first call
988 * or more than a second has passed since the last update of
992 if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
993 lasttime->tv_sec = now;
995 return (maxpps != 0);
997 (*curpps)++; /* NB: ignore potential overflow */
998 return (maxpps < 0 || *curpps <= maxpps);
1005 struct kclock rt_clock = {
1006 .timer_create = realtimer_create,
1007 .timer_delete = realtimer_delete,
1008 .timer_settime = realtimer_settime,
1009 .timer_gettime = realtimer_gettime,
1013 itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1014 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1015 register_posix_clock(CLOCK_REALTIME, &rt_clock);
1016 register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1017 p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1018 p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1019 p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1020 EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1021 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1022 EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1023 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1027 register_posix_clock(int clockid, struct kclock *clk)
1029 if ((unsigned)clockid >= MAX_CLOCKS) {
1030 printf("%s: invalid clockid\n", __func__);
1033 posix_clocks[clockid] = *clk;
1038 itimer_init(void *mem, int size, int flags)
1042 it = (struct itimer *)mem;
1043 mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1048 itimer_fini(void *mem, int size)
1052 it = (struct itimer *)mem;
1053 mtx_destroy(&it->it_mtx);
1057 itimer_enter(struct itimer *it)
1060 mtx_assert(&it->it_mtx, MA_OWNED);
1065 itimer_leave(struct itimer *it)
1068 mtx_assert(&it->it_mtx, MA_OWNED);
1069 KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1071 if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1075 #ifndef _SYS_SYSPROTO_H_
1076 struct ktimer_create_args {
1078 struct sigevent * evp;
1083 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1085 struct sigevent *evp, ev;
1089 if (uap->evp == NULL) {
1092 error = copyin(uap->evp, &ev, sizeof(ev));
1097 error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1099 error = copyout(&id, uap->timerid, sizeof(int));
1101 kern_ktimer_delete(td, id);
1107 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1108 int *timerid, int preset_id)
1110 struct proc *p = td->td_proc;
1115 if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1118 if (posix_clocks[clock_id].timer_create == NULL)
1122 if (evp->sigev_notify != SIGEV_NONE &&
1123 evp->sigev_notify != SIGEV_SIGNAL &&
1124 evp->sigev_notify != SIGEV_THREAD_ID)
1126 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1127 evp->sigev_notify == SIGEV_THREAD_ID) &&
1128 !_SIG_VALID(evp->sigev_signo))
1132 if (p->p_itimers == NULL)
1135 it = uma_zalloc(itimer_zone, M_WAITOK);
1137 it->it_usecount = 0;
1139 timespecclear(&it->it_time.it_value);
1140 timespecclear(&it->it_time.it_interval);
1142 it->it_overrun_last = 0;
1143 it->it_clockid = clock_id;
1144 it->it_timerid = -1;
1146 ksiginfo_init(&it->it_ksi);
1147 it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1148 error = CLOCK_CALL(clock_id, timer_create, (it));
1153 if (preset_id != -1) {
1154 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1156 if (p->p_itimers->its_timers[id] != NULL) {
1163 * Find a free timer slot, skipping those reserved
1166 for (id = 3; id < TIMER_MAX; id++)
1167 if (p->p_itimers->its_timers[id] == NULL)
1169 if (id == TIMER_MAX) {
1175 it->it_timerid = id;
1176 p->p_itimers->its_timers[id] = it;
1178 it->it_sigev = *evp;
1180 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1183 case CLOCK_REALTIME:
1184 it->it_sigev.sigev_signo = SIGALRM;
1187 it->it_sigev.sigev_signo = SIGVTALRM;
1190 it->it_sigev.sigev_signo = SIGPROF;
1193 it->it_sigev.sigev_value.sival_int = id;
1196 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1197 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1198 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1199 it->it_ksi.ksi_code = SI_TIMER;
1200 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1201 it->it_ksi.ksi_timerid = id;
1209 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1211 uma_zfree(itimer_zone, it);
1215 #ifndef _SYS_SYSPROTO_H_
1216 struct ktimer_delete_args {
1221 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1224 return (kern_ktimer_delete(td, uap->timerid));
1227 static struct itimer *
1228 itimer_find(struct proc *p, int timerid)
1232 PROC_LOCK_ASSERT(p, MA_OWNED);
1233 if ((p->p_itimers == NULL) ||
1234 (timerid < 0) || (timerid >= TIMER_MAX) ||
1235 (it = p->p_itimers->its_timers[timerid]) == NULL) {
1239 if ((it->it_flags & ITF_DELETING) != 0) {
1247 kern_ktimer_delete(struct thread *td, int timerid)
1249 struct proc *p = td->td_proc;
1253 it = itimer_find(p, timerid);
1260 it->it_flags |= ITF_DELETING;
1261 while (it->it_usecount > 0) {
1262 it->it_flags |= ITF_WANTED;
1263 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1265 it->it_flags &= ~ITF_WANTED;
1266 CLOCK_CALL(it->it_clockid, timer_delete, (it));
1270 if (KSI_ONQ(&it->it_ksi))
1271 sigqueue_take(&it->it_ksi);
1272 p->p_itimers->its_timers[timerid] = NULL;
1274 uma_zfree(itimer_zone, it);
1278 #ifndef _SYS_SYSPROTO_H_
1279 struct ktimer_settime_args {
1282 const struct itimerspec * value;
1283 struct itimerspec * ovalue;
1287 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1289 struct itimerspec val, oval, *ovalp;
1292 error = copyin(uap->value, &val, sizeof(val));
1295 ovalp = uap->ovalue != NULL ? &oval : NULL;
1296 error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1297 if (error == 0 && uap->ovalue != NULL)
1298 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1303 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1304 struct itimerspec *val, struct itimerspec *oval)
1312 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1318 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1326 #ifndef _SYS_SYSPROTO_H_
1327 struct ktimer_gettime_args {
1329 struct itimerspec * value;
1333 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1335 struct itimerspec val;
1338 error = kern_ktimer_gettime(td, uap->timerid, &val);
1340 error = copyout(&val, uap->value, sizeof(val));
1345 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1353 if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1359 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1366 #ifndef _SYS_SYSPROTO_H_
1367 struct timer_getoverrun_args {
1372 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1375 return (kern_ktimer_getoverrun(td, uap->timerid));
1379 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1381 struct proc *p = td->td_proc;
1387 (it = itimer_find(p, timer_id)) == NULL) {
1391 td->td_retval[0] = it->it_overrun_last;
1400 realtimer_create(struct itimer *it)
1402 callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1407 realtimer_delete(struct itimer *it)
1409 mtx_assert(&it->it_mtx, MA_OWNED);
1412 * clear timer's value and interval to tell realtimer_expire
1413 * to not rearm the timer.
1415 timespecclear(&it->it_time.it_value);
1416 timespecclear(&it->it_time.it_interval);
1418 callout_drain(&it->it_callout);
1424 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1426 struct timespec cts;
1428 mtx_assert(&it->it_mtx, MA_OWNED);
1430 realtimer_clocktime(it->it_clockid, &cts);
1431 *ovalue = it->it_time;
1432 if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1433 timespecsub(&ovalue->it_value, &cts);
1434 if (ovalue->it_value.tv_sec < 0 ||
1435 (ovalue->it_value.tv_sec == 0 &&
1436 ovalue->it_value.tv_nsec == 0)) {
1437 ovalue->it_value.tv_sec = 0;
1438 ovalue->it_value.tv_nsec = 1;
1445 realtimer_settime(struct itimer *it, int flags,
1446 struct itimerspec *value, struct itimerspec *ovalue)
1448 struct timespec cts, ts;
1450 struct itimerspec val;
1452 mtx_assert(&it->it_mtx, MA_OWNED);
1455 if (itimespecfix(&val.it_value))
1458 if (timespecisset(&val.it_value)) {
1459 if (itimespecfix(&val.it_interval))
1462 timespecclear(&val.it_interval);
1466 realtimer_gettime(it, ovalue);
1469 if (timespecisset(&val.it_value)) {
1470 realtimer_clocktime(it->it_clockid, &cts);
1472 if ((flags & TIMER_ABSTIME) == 0) {
1473 /* Convert to absolute time. */
1474 timespecadd(&it->it_time.it_value, &cts);
1476 timespecsub(&ts, &cts);
1478 * We don't care if ts is negative, tztohz will
1482 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1483 callout_reset(&it->it_callout, tvtohz(&tv),
1484 realtimer_expire, it);
1486 callout_stop(&it->it_callout);
1493 realtimer_clocktime(clockid_t id, struct timespec *ts)
1495 if (id == CLOCK_REALTIME)
1497 else /* CLOCK_MONOTONIC */
1502 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1506 PROC_LOCK_ASSERT(p, MA_OWNED);
1507 it = itimer_find(p, timerid);
1509 ksi->ksi_overrun = it->it_overrun;
1510 it->it_overrun_last = it->it_overrun;
1519 itimespecfix(struct timespec *ts)
1522 if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1524 if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1525 ts->tv_nsec = tick * 1000;
1529 /* Timeout callback for realtime timer */
1531 realtimer_expire(void *arg)
1533 struct timespec cts, ts;
1537 it = (struct itimer *)arg;
1539 realtimer_clocktime(it->it_clockid, &cts);
1540 /* Only fire if time is reached. */
1541 if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1542 if (timespecisset(&it->it_time.it_interval)) {
1543 timespecadd(&it->it_time.it_value,
1544 &it->it_time.it_interval);
1545 while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1546 if (it->it_overrun < INT_MAX)
1549 it->it_ksi.ksi_errno = ERANGE;
1550 timespecadd(&it->it_time.it_value,
1551 &it->it_time.it_interval);
1554 /* single shot timer ? */
1555 timespecclear(&it->it_time.it_value);
1557 if (timespecisset(&it->it_time.it_value)) {
1558 ts = it->it_time.it_value;
1559 timespecsub(&ts, &cts);
1560 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1561 callout_reset(&it->it_callout, tvtohz(&tv),
1562 realtimer_expire, it);
1569 } else if (timespecisset(&it->it_time.it_value)) {
1570 ts = it->it_time.it_value;
1571 timespecsub(&ts, &cts);
1572 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1573 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1579 itimer_fire(struct itimer *it)
1581 struct proc *p = it->it_proc;
1584 if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1585 it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1586 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1588 timespecclear(&it->it_time.it_value);
1589 timespecclear(&it->it_time.it_interval);
1590 callout_stop(&it->it_callout);
1594 if (!KSI_ONQ(&it->it_ksi)) {
1595 it->it_ksi.ksi_errno = 0;
1596 ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1597 tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1599 if (it->it_overrun < INT_MAX)
1602 it->it_ksi.ksi_errno = ERANGE;
1609 itimers_alloc(struct proc *p)
1611 struct itimers *its;
1614 its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1615 LIST_INIT(&its->its_virtual);
1616 LIST_INIT(&its->its_prof);
1617 TAILQ_INIT(&its->its_worklist);
1618 for (i = 0; i < TIMER_MAX; i++)
1619 its->its_timers[i] = NULL;
1621 if (p->p_itimers == NULL) {
1627 free(its, M_SUBPROC);
1632 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1634 itimers_event_hook_exit(arg, p);
1637 /* Clean up timers when some process events are being triggered. */
1639 itimers_event_hook_exit(void *arg, struct proc *p)
1641 struct itimers *its;
1643 int event = (int)(intptr_t)arg;
1646 if (p->p_itimers != NULL) {
1648 for (i = 0; i < MAX_CLOCKS; ++i) {
1649 if (posix_clocks[i].event_hook != NULL)
1650 CLOCK_CALL(i, event_hook, (p, i, event));
1653 * According to susv3, XSI interval timers should be inherited
1656 if (event == ITIMER_EV_EXEC)
1658 else if (event == ITIMER_EV_EXIT)
1661 panic("unhandled event");
1662 for (; i < TIMER_MAX; ++i) {
1663 if ((it = its->its_timers[i]) != NULL)
1664 kern_ktimer_delete(curthread, i);
1666 if (its->its_timers[0] == NULL &&
1667 its->its_timers[1] == NULL &&
1668 its->its_timers[2] == NULL) {
1669 free(its, M_SUBPROC);
1670 p->p_itimers = NULL;