xref: /freebsd/sys/kern/kern_time.c (revision 94942af266ac119ede0ca836f9aa5a5ac0582938)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  *
29  *	@(#)kern_time.c	8.1 (Berkeley) 6/10/93
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/limits.h>
38 #include <sys/clock.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/sysproto.h>
42 #include <sys/eventhandler.h>
43 #include <sys/resourcevar.h>
44 #include <sys/signalvar.h>
45 #include <sys/kernel.h>
46 #include <sys/syscallsubr.h>
47 #include <sys/sysctl.h>
48 #include <sys/sysent.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/posix4.h>
52 #include <sys/time.h>
53 #include <sys/timers.h>
54 #include <sys/timetc.h>
55 #include <sys/vnode.h>
56 
57 #include <vm/vm.h>
58 #include <vm/vm_extern.h>
59 
60 #define MAX_CLOCKS 	(CLOCK_MONOTONIC+1)
61 
62 static struct kclock	posix_clocks[MAX_CLOCKS];
63 static uma_zone_t	itimer_zone = NULL;
64 
65 /*
66  * Time of day and interval timer support.
67  *
68  * These routines provide the kernel entry points to get and set
69  * the time-of-day and per-process interval timers.  Subroutines
70  * here provide support for adding and subtracting timeval structures
71  * and decrementing interval timers, optionally reloading the interval
72  * timers when they expire.
73  */
74 
75 static int	settime(struct thread *, struct timeval *);
76 static void	timevalfix(struct timeval *);
77 static void	no_lease_updatetime(int);
78 
79 static void	itimer_start(void);
80 static int	itimer_init(void *, int, int);
81 static void	itimer_fini(void *, int);
82 static void	itimer_enter(struct itimer *);
83 static void	itimer_leave(struct itimer *);
84 static struct itimer *itimer_find(struct proc *, int);
85 static void	itimers_alloc(struct proc *);
86 static void	itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
87 static void	itimers_event_hook_exit(void *arg, struct proc *p);
88 static int	realtimer_create(struct itimer *);
89 static int	realtimer_gettime(struct itimer *, struct itimerspec *);
90 static int	realtimer_settime(struct itimer *, int,
91 			struct itimerspec *, struct itimerspec *);
92 static int	realtimer_delete(struct itimer *);
93 static void	realtimer_clocktime(clockid_t, struct timespec *);
94 static void	realtimer_expire(void *);
95 static int	kern_timer_create(struct thread *, clockid_t,
96 			struct sigevent *, int *, int);
97 static int	kern_timer_delete(struct thread *, int);
98 
99 int		register_posix_clock(int, struct kclock *);
100 void		itimer_fire(struct itimer *it);
101 int		itimespecfix(struct timespec *ts);
102 
103 #define CLOCK_CALL(clock, call, arglist)		\
104 	((*posix_clocks[clock].call) arglist)
105 
106 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
107 
108 
109 static void
110 no_lease_updatetime(deltat)
111 	int deltat;
112 {
113 }
114 
115 void (*lease_updatetime)(int)  = no_lease_updatetime;
116 
117 static int
118 settime(struct thread *td, struct timeval *tv)
119 {
120 	struct timeval delta, tv1, tv2;
121 	static struct timeval maxtime, laststep;
122 	struct timespec ts;
123 	int s;
124 
125 	s = splclock();
126 	microtime(&tv1);
127 	delta = *tv;
128 	timevalsub(&delta, &tv1);
129 
130 	/*
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
135 	 * back to the past.
136 	 *
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.
140 	 */
141 	if (securelevel_gt(td->td_ucred, 1) != 0) {
142 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
143 			/*
144 			 * Update maxtime to latest time we've seen.
145 			 */
146 			if (tv1.tv_sec > maxtime.tv_sec)
147 				maxtime = tv1;
148 			tv2 = *tv;
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");
153 			}
154 		} else {
155 			if (tv1.tv_sec == laststep.tv_sec) {
156 				splx(s);
157 				return (EPERM);
158 			}
159 			if (delta.tv_sec > 1) {
160 				tv->tv_sec = tv1.tv_sec + 1;
161 				printf("Time adjustment clamped to +1 second\n");
162 			}
163 			laststep = *tv;
164 		}
165 	}
166 
167 	ts.tv_sec = tv->tv_sec;
168 	ts.tv_nsec = tv->tv_usec * 1000;
169 	mtx_lock(&Giant);
170 	tc_setclock(&ts);
171 	(void) splsoftclock();
172 	lease_updatetime(delta.tv_sec);
173 	splx(s);
174 	resettodr();
175 	mtx_unlock(&Giant);
176 	return (0);
177 }
178 
179 #ifndef _SYS_SYSPROTO_H_
180 struct clock_gettime_args {
181 	clockid_t clock_id;
182 	struct	timespec *tp;
183 };
184 #endif
185 /* ARGSUSED */
186 int
187 clock_gettime(struct thread *td, struct clock_gettime_args *uap)
188 {
189 	struct timespec ats;
190 	int error;
191 
192 	error = kern_clock_gettime(td, uap->clock_id, &ats);
193 	if (error == 0)
194 		error = copyout(&ats, uap->tp, sizeof(ats));
195 
196 	return (error);
197 }
198 
199 int
200 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
201 {
202 	struct timeval sys, user;
203 	struct proc *p;
204 
205 	p = td->td_proc;
206 	switch (clock_id) {
207 	case CLOCK_REALTIME:		/* Default to precise. */
208 	case CLOCK_REALTIME_PRECISE:
209 		nanotime(ats);
210 		break;
211 	case CLOCK_REALTIME_FAST:
212 		getnanotime(ats);
213 		break;
214 	case CLOCK_VIRTUAL:
215 		PROC_LOCK(p);
216 		calcru(p, &user, &sys);
217 		PROC_UNLOCK(p);
218 		TIMEVAL_TO_TIMESPEC(&user, ats);
219 		break;
220 	case CLOCK_PROF:
221 		PROC_LOCK(p);
222 		calcru(p, &user, &sys);
223 		PROC_UNLOCK(p);
224 		timevaladd(&user, &sys);
225 		TIMEVAL_TO_TIMESPEC(&user, ats);
226 		break;
227 	case CLOCK_MONOTONIC:		/* Default to precise. */
228 	case CLOCK_MONOTONIC_PRECISE:
229 	case CLOCK_UPTIME:
230 	case CLOCK_UPTIME_PRECISE:
231 		nanouptime(ats);
232 		break;
233 	case CLOCK_UPTIME_FAST:
234 	case CLOCK_MONOTONIC_FAST:
235 		getnanouptime(ats);
236 		break;
237 	case CLOCK_SECOND:
238 		ats->tv_sec = time_second;
239 		ats->tv_nsec = 0;
240 		break;
241 	default:
242 		return (EINVAL);
243 	}
244 	return (0);
245 }
246 
247 #ifndef _SYS_SYSPROTO_H_
248 struct clock_settime_args {
249 	clockid_t clock_id;
250 	const struct	timespec *tp;
251 };
252 #endif
253 /* ARGSUSED */
254 int
255 clock_settime(struct thread *td, struct clock_settime_args *uap)
256 {
257 	struct timespec ats;
258 	int error;
259 
260 	if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
261 		return (error);
262 	return (kern_clock_settime(td, uap->clock_id, &ats));
263 }
264 
265 int
266 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
267 {
268 	struct timeval atv;
269 	int error;
270 
271 	if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
272 		return (error);
273 	if (clock_id != CLOCK_REALTIME)
274 		return (EINVAL);
275 	if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
276 		return (EINVAL);
277 	/* XXX Don't convert nsec->usec and back */
278 	TIMESPEC_TO_TIMEVAL(&atv, ats);
279 	error = settime(td, &atv);
280 	return (error);
281 }
282 
283 #ifndef _SYS_SYSPROTO_H_
284 struct clock_getres_args {
285 	clockid_t clock_id;
286 	struct	timespec *tp;
287 };
288 #endif
289 int
290 clock_getres(struct thread *td, struct clock_getres_args *uap)
291 {
292 	struct timespec ts;
293 	int error;
294 
295 	if (uap->tp == NULL)
296 		return (0);
297 
298 	error = kern_clock_getres(td, uap->clock_id, &ts);
299 	if (error == 0)
300 		error = copyout(&ts, uap->tp, sizeof(ts));
301 	return (error);
302 }
303 
304 int
305 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
306 {
307 
308 	ts->tv_sec = 0;
309 	switch (clock_id) {
310 	case CLOCK_REALTIME:
311 	case CLOCK_REALTIME_FAST:
312 	case CLOCK_REALTIME_PRECISE:
313 	case CLOCK_MONOTONIC:
314 	case CLOCK_MONOTONIC_FAST:
315 	case CLOCK_MONOTONIC_PRECISE:
316 	case CLOCK_UPTIME:
317 	case CLOCK_UPTIME_FAST:
318 	case CLOCK_UPTIME_PRECISE:
319 		/*
320 		 * Round up the result of the division cheaply by adding 1.
321 		 * Rounding up is especially important if rounding down
322 		 * would give 0.  Perfect rounding is unimportant.
323 		 */
324 		ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
325 		break;
326 	case CLOCK_VIRTUAL:
327 	case CLOCK_PROF:
328 		/* Accurately round up here because we can do so cheaply. */
329 		ts->tv_nsec = (1000000000 + hz - 1) / hz;
330 		break;
331 	case CLOCK_SECOND:
332 		ts->tv_sec = 1;
333 		ts->tv_nsec = 0;
334 		break;
335 	default:
336 		return (EINVAL);
337 	}
338 	return (0);
339 }
340 
341 static int nanowait;
342 
343 int
344 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
345 {
346 	struct timespec ts, ts2, ts3;
347 	struct timeval tv;
348 	int error;
349 
350 	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
351 		return (EINVAL);
352 	if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
353 		return (0);
354 	getnanouptime(&ts);
355 	timespecadd(&ts, rqt);
356 	TIMESPEC_TO_TIMEVAL(&tv, rqt);
357 	for (;;) {
358 		error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
359 		    tvtohz(&tv));
360 		getnanouptime(&ts2);
361 		if (error != EWOULDBLOCK) {
362 			if (error == ERESTART)
363 				error = EINTR;
364 			if (rmt != NULL) {
365 				timespecsub(&ts, &ts2);
366 				if (ts.tv_sec < 0)
367 					timespecclear(&ts);
368 				*rmt = ts;
369 			}
370 			return (error);
371 		}
372 		if (timespeccmp(&ts2, &ts, >=))
373 			return (0);
374 		ts3 = ts;
375 		timespecsub(&ts3, &ts2);
376 		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
377 	}
378 }
379 
380 #ifndef _SYS_SYSPROTO_H_
381 struct nanosleep_args {
382 	struct	timespec *rqtp;
383 	struct	timespec *rmtp;
384 };
385 #endif
386 /* ARGSUSED */
387 int
388 nanosleep(struct thread *td, struct nanosleep_args *uap)
389 {
390 	struct timespec rmt, rqt;
391 	int error;
392 
393 	error = copyin(uap->rqtp, &rqt, sizeof(rqt));
394 	if (error)
395 		return (error);
396 
397 	if (uap->rmtp &&
398 	    !useracc((caddr_t)uap->rmtp, sizeof(rmt), VM_PROT_WRITE))
399 			return (EFAULT);
400 	error = kern_nanosleep(td, &rqt, &rmt);
401 	if (error && uap->rmtp) {
402 		int error2;
403 
404 		error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
405 		if (error2)
406 			error = error2;
407 	}
408 	return (error);
409 }
410 
411 #ifndef _SYS_SYSPROTO_H_
412 struct gettimeofday_args {
413 	struct	timeval *tp;
414 	struct	timezone *tzp;
415 };
416 #endif
417 /* ARGSUSED */
418 int
419 gettimeofday(struct thread *td, struct gettimeofday_args *uap)
420 {
421 	struct timeval atv;
422 	struct timezone rtz;
423 	int error = 0;
424 
425 	if (uap->tp) {
426 		microtime(&atv);
427 		error = copyout(&atv, uap->tp, sizeof (atv));
428 	}
429 	if (error == 0 && uap->tzp != NULL) {
430 		rtz.tz_minuteswest = tz_minuteswest;
431 		rtz.tz_dsttime = tz_dsttime;
432 		error = copyout(&rtz, uap->tzp, sizeof (rtz));
433 	}
434 	return (error);
435 }
436 
437 #ifndef _SYS_SYSPROTO_H_
438 struct settimeofday_args {
439 	struct	timeval *tv;
440 	struct	timezone *tzp;
441 };
442 #endif
443 /* ARGSUSED */
444 int
445 settimeofday(struct thread *td, struct settimeofday_args *uap)
446 {
447 	struct timeval atv, *tvp;
448 	struct timezone atz, *tzp;
449 	int error;
450 
451 	if (uap->tv) {
452 		error = copyin(uap->tv, &atv, sizeof(atv));
453 		if (error)
454 			return (error);
455 		tvp = &atv;
456 	} else
457 		tvp = NULL;
458 	if (uap->tzp) {
459 		error = copyin(uap->tzp, &atz, sizeof(atz));
460 		if (error)
461 			return (error);
462 		tzp = &atz;
463 	} else
464 		tzp = NULL;
465 	return (kern_settimeofday(td, tvp, tzp));
466 }
467 
468 int
469 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
470 {
471 	int error;
472 
473 	error = priv_check(td, PRIV_SETTIMEOFDAY);
474 	if (error)
475 		return (error);
476 	/* Verify all parameters before changing time. */
477 	if (tv) {
478 		if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
479 			return (EINVAL);
480 		error = settime(td, tv);
481 	}
482 	if (tzp && error == 0) {
483 		tz_minuteswest = tzp->tz_minuteswest;
484 		tz_dsttime = tzp->tz_dsttime;
485 	}
486 	return (error);
487 }
488 
489 /*
490  * Get value of an interval timer.  The process virtual and profiling virtual
491  * time timers are kept in the p_stats area, since they can be swapped out.
492  * These are kept internally in the way they are specified externally: in
493  * time until they expire.
494  *
495  * The real time interval timer is kept in the process table slot for the
496  * process, and its value (it_value) is kept as an absolute time rather than
497  * as a delta, so that it is easy to keep periodic real-time signals from
498  * drifting.
499  *
500  * Virtual time timers are processed in the hardclock() routine of
501  * kern_clock.c.  The real time timer is processed by a timeout routine,
502  * called from the softclock() routine.  Since a callout may be delayed in
503  * real time due to interrupt processing in the system, it is possible for
504  * the real time timeout routine (realitexpire, given below), to be delayed
505  * in real time past when it is supposed to occur.  It does not suffice,
506  * therefore, to reload the real timer .it_value from the real time timers
507  * .it_interval.  Rather, we compute the next time in absolute time the timer
508  * should go off.
509  */
510 #ifndef _SYS_SYSPROTO_H_
511 struct getitimer_args {
512 	u_int	which;
513 	struct	itimerval *itv;
514 };
515 #endif
516 int
517 getitimer(struct thread *td, struct getitimer_args *uap)
518 {
519 	struct itimerval aitv;
520 	int error;
521 
522 	error = kern_getitimer(td, uap->which, &aitv);
523 	if (error != 0)
524 		return (error);
525 	return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
526 }
527 
528 int
529 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
530 {
531 	struct proc *p = td->td_proc;
532 	struct timeval ctv;
533 
534 	if (which > ITIMER_PROF)
535 		return (EINVAL);
536 
537 	if (which == ITIMER_REAL) {
538 		/*
539 		 * Convert from absolute to relative time in .it_value
540 		 * part of real time timer.  If time for real time timer
541 		 * has passed return 0, else return difference between
542 		 * current time and time for the timer to go off.
543 		 */
544 		PROC_LOCK(p);
545 		*aitv = p->p_realtimer;
546 		PROC_UNLOCK(p);
547 		if (timevalisset(&aitv->it_value)) {
548 			getmicrouptime(&ctv);
549 			if (timevalcmp(&aitv->it_value, &ctv, <))
550 				timevalclear(&aitv->it_value);
551 			else
552 				timevalsub(&aitv->it_value, &ctv);
553 		}
554 	} else {
555 		mtx_lock_spin(&sched_lock);
556 		*aitv = p->p_stats->p_timer[which];
557 		mtx_unlock_spin(&sched_lock);
558 	}
559 	return (0);
560 }
561 
562 #ifndef _SYS_SYSPROTO_H_
563 struct setitimer_args {
564 	u_int	which;
565 	struct	itimerval *itv, *oitv;
566 };
567 #endif
568 int
569 setitimer(struct thread *td, struct setitimer_args *uap)
570 {
571 	struct itimerval aitv, oitv;
572 	int error;
573 
574 	if (uap->itv == NULL) {
575 		uap->itv = uap->oitv;
576 		return (getitimer(td, (struct getitimer_args *)uap));
577 	}
578 
579 	if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
580 		return (error);
581 	error = kern_setitimer(td, uap->which, &aitv, &oitv);
582 	if (error != 0 || uap->oitv == NULL)
583 		return (error);
584 	return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
585 }
586 
587 int
588 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
589     struct itimerval *oitv)
590 {
591 	struct proc *p = td->td_proc;
592 	struct timeval ctv;
593 
594 	if (aitv == NULL)
595 		return (kern_getitimer(td, which, oitv));
596 
597 	if (which > ITIMER_PROF)
598 		return (EINVAL);
599 	if (itimerfix(&aitv->it_value))
600 		return (EINVAL);
601 	if (!timevalisset(&aitv->it_value))
602 		timevalclear(&aitv->it_interval);
603 	else if (itimerfix(&aitv->it_interval))
604 		return (EINVAL);
605 
606 	if (which == ITIMER_REAL) {
607 		PROC_LOCK(p);
608 		if (timevalisset(&p->p_realtimer.it_value))
609 			callout_stop(&p->p_itcallout);
610 		getmicrouptime(&ctv);
611 		if (timevalisset(&aitv->it_value)) {
612 			callout_reset(&p->p_itcallout, tvtohz(&aitv->it_value),
613 			    realitexpire, p);
614 			timevaladd(&aitv->it_value, &ctv);
615 		}
616 		*oitv = p->p_realtimer;
617 		p->p_realtimer = *aitv;
618 		PROC_UNLOCK(p);
619 		if (timevalisset(&oitv->it_value)) {
620 			if (timevalcmp(&oitv->it_value, &ctv, <))
621 				timevalclear(&oitv->it_value);
622 			else
623 				timevalsub(&oitv->it_value, &ctv);
624 		}
625 	} else {
626 		mtx_lock_spin(&sched_lock);
627 		*oitv = p->p_stats->p_timer[which];
628 		p->p_stats->p_timer[which] = *aitv;
629 		mtx_unlock_spin(&sched_lock);
630 	}
631 	return (0);
632 }
633 
634 /*
635  * Real interval timer expired:
636  * send process whose timer expired an alarm signal.
637  * If time is not set up to reload, then just return.
638  * Else compute next time timer should go off which is > current time.
639  * This is where delay in processing this timeout causes multiple
640  * SIGALRM calls to be compressed into one.
641  * tvtohz() always adds 1 to allow for the time until the next clock
642  * interrupt being strictly less than 1 clock tick, but we don't want
643  * that here since we want to appear to be in sync with the clock
644  * interrupt even when we're delayed.
645  */
646 void
647 realitexpire(void *arg)
648 {
649 	struct proc *p;
650 	struct timeval ctv, ntv;
651 
652 	p = (struct proc *)arg;
653 	PROC_LOCK(p);
654 	psignal(p, SIGALRM);
655 	if (!timevalisset(&p->p_realtimer.it_interval)) {
656 		timevalclear(&p->p_realtimer.it_value);
657 		if (p->p_flag & P_WEXIT)
658 			wakeup(&p->p_itcallout);
659 		PROC_UNLOCK(p);
660 		return;
661 	}
662 	for (;;) {
663 		timevaladd(&p->p_realtimer.it_value,
664 		    &p->p_realtimer.it_interval);
665 		getmicrouptime(&ctv);
666 		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
667 			ntv = p->p_realtimer.it_value;
668 			timevalsub(&ntv, &ctv);
669 			callout_reset(&p->p_itcallout, tvtohz(&ntv) - 1,
670 			    realitexpire, p);
671 			PROC_UNLOCK(p);
672 			return;
673 		}
674 	}
675 	/*NOTREACHED*/
676 }
677 
678 /*
679  * Check that a proposed value to load into the .it_value or
680  * .it_interval part of an interval timer is acceptable, and
681  * fix it to have at least minimal value (i.e. if it is less
682  * than the resolution of the clock, round it up.)
683  */
684 int
685 itimerfix(struct timeval *tv)
686 {
687 
688 	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
689 		return (EINVAL);
690 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
691 		tv->tv_usec = tick;
692 	return (0);
693 }
694 
695 /*
696  * Decrement an interval timer by a specified number
697  * of microseconds, which must be less than a second,
698  * i.e. < 1000000.  If the timer expires, then reload
699  * it.  In this case, carry over (usec - old value) to
700  * reduce the value reloaded into the timer so that
701  * the timer does not drift.  This routine assumes
702  * that it is called in a context where the timers
703  * on which it is operating cannot change in value.
704  */
705 int
706 itimerdecr(struct itimerval *itp, int usec)
707 {
708 
709 	if (itp->it_value.tv_usec < usec) {
710 		if (itp->it_value.tv_sec == 0) {
711 			/* expired, and already in next interval */
712 			usec -= itp->it_value.tv_usec;
713 			goto expire;
714 		}
715 		itp->it_value.tv_usec += 1000000;
716 		itp->it_value.tv_sec--;
717 	}
718 	itp->it_value.tv_usec -= usec;
719 	usec = 0;
720 	if (timevalisset(&itp->it_value))
721 		return (1);
722 	/* expired, exactly at end of interval */
723 expire:
724 	if (timevalisset(&itp->it_interval)) {
725 		itp->it_value = itp->it_interval;
726 		itp->it_value.tv_usec -= usec;
727 		if (itp->it_value.tv_usec < 0) {
728 			itp->it_value.tv_usec += 1000000;
729 			itp->it_value.tv_sec--;
730 		}
731 	} else
732 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
733 	return (0);
734 }
735 
736 /*
737  * Add and subtract routines for timevals.
738  * N.B.: subtract routine doesn't deal with
739  * results which are before the beginning,
740  * it just gets very confused in this case.
741  * Caveat emptor.
742  */
743 void
744 timevaladd(struct timeval *t1, const struct timeval *t2)
745 {
746 
747 	t1->tv_sec += t2->tv_sec;
748 	t1->tv_usec += t2->tv_usec;
749 	timevalfix(t1);
750 }
751 
752 void
753 timevalsub(struct timeval *t1, const struct timeval *t2)
754 {
755 
756 	t1->tv_sec -= t2->tv_sec;
757 	t1->tv_usec -= t2->tv_usec;
758 	timevalfix(t1);
759 }
760 
761 static void
762 timevalfix(struct timeval *t1)
763 {
764 
765 	if (t1->tv_usec < 0) {
766 		t1->tv_sec--;
767 		t1->tv_usec += 1000000;
768 	}
769 	if (t1->tv_usec >= 1000000) {
770 		t1->tv_sec++;
771 		t1->tv_usec -= 1000000;
772 	}
773 }
774 
775 /*
776  * ratecheck(): simple time-based rate-limit checking.
777  */
778 int
779 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
780 {
781 	struct timeval tv, delta;
782 	int rv = 0;
783 
784 	getmicrouptime(&tv);		/* NB: 10ms precision */
785 	delta = tv;
786 	timevalsub(&delta, lasttime);
787 
788 	/*
789 	 * check for 0,0 is so that the message will be seen at least once,
790 	 * even if interval is huge.
791 	 */
792 	if (timevalcmp(&delta, mininterval, >=) ||
793 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
794 		*lasttime = tv;
795 		rv = 1;
796 	}
797 
798 	return (rv);
799 }
800 
801 /*
802  * ppsratecheck(): packets (or events) per second limitation.
803  *
804  * Return 0 if the limit is to be enforced (e.g. the caller
805  * should drop a packet because of the rate limitation).
806  *
807  * maxpps of 0 always causes zero to be returned.  maxpps of -1
808  * always causes 1 to be returned; this effectively defeats rate
809  * limiting.
810  *
811  * Note that we maintain the struct timeval for compatibility
812  * with other bsd systems.  We reuse the storage and just monitor
813  * clock ticks for minimal overhead.
814  */
815 int
816 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
817 {
818 	int now;
819 
820 	/*
821 	 * Reset the last time and counter if this is the first call
822 	 * or more than a second has passed since the last update of
823 	 * lasttime.
824 	 */
825 	now = ticks;
826 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
827 		lasttime->tv_sec = now;
828 		*curpps = 1;
829 		return (maxpps != 0);
830 	} else {
831 		(*curpps)++;		/* NB: ignore potential overflow */
832 		return (maxpps < 0 || *curpps < maxpps);
833 	}
834 }
835 
836 static void
837 itimer_start(void)
838 {
839 	struct kclock rt_clock = {
840 		.timer_create  = realtimer_create,
841 		.timer_delete  = realtimer_delete,
842 		.timer_settime = realtimer_settime,
843 		.timer_gettime = realtimer_gettime,
844 		.event_hook    = NULL
845 	};
846 
847 	itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
848 		NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
849 	register_posix_clock(CLOCK_REALTIME,  &rt_clock);
850 	register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
851 	p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
852 	p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
853 	p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
854 	EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
855 		(void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
856 	EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
857 		(void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
858 }
859 
860 int
861 register_posix_clock(int clockid, struct kclock *clk)
862 {
863 	if ((unsigned)clockid >= MAX_CLOCKS) {
864 		printf("%s: invalid clockid\n", __func__);
865 		return (0);
866 	}
867 	posix_clocks[clockid] = *clk;
868 	return (1);
869 }
870 
871 static int
872 itimer_init(void *mem, int size, int flags)
873 {
874 	struct itimer *it;
875 
876 	it = (struct itimer *)mem;
877 	mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
878 	return (0);
879 }
880 
881 static void
882 itimer_fini(void *mem, int size)
883 {
884 	struct itimer *it;
885 
886 	it = (struct itimer *)mem;
887 	mtx_destroy(&it->it_mtx);
888 }
889 
890 static void
891 itimer_enter(struct itimer *it)
892 {
893 
894 	mtx_assert(&it->it_mtx, MA_OWNED);
895 	it->it_usecount++;
896 }
897 
898 static void
899 itimer_leave(struct itimer *it)
900 {
901 
902 	mtx_assert(&it->it_mtx, MA_OWNED);
903 	KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
904 
905 	if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
906 		wakeup(it);
907 }
908 
909 #ifndef _SYS_SYSPROTO_H_
910 struct ktimer_create_args {
911 	clockid_t clock_id;
912 	struct sigevent * evp;
913 	int * timerid;
914 };
915 #endif
916 int
917 ktimer_create(struct thread *td, struct ktimer_create_args *uap)
918 {
919 	struct sigevent *evp1, ev;
920 	int id;
921 	int error;
922 
923 	if (uap->evp != NULL) {
924 		error = copyin(uap->evp, &ev, sizeof(ev));
925 		if (error != 0)
926 			return (error);
927 		evp1 = &ev;
928 	} else
929 		evp1 = NULL;
930 
931 	error = kern_timer_create(td, uap->clock_id, evp1, &id, -1);
932 
933 	if (error == 0) {
934 		error = copyout(&id, uap->timerid, sizeof(int));
935 		if (error != 0)
936 			kern_timer_delete(td, id);
937 	}
938 	return (error);
939 }
940 
941 static int
942 kern_timer_create(struct thread *td, clockid_t clock_id,
943 	struct sigevent *evp, int *timerid, int preset_id)
944 {
945 	struct proc *p = td->td_proc;
946 	struct itimer *it;
947 	int id;
948 	int error;
949 
950 	if (clock_id < 0 || clock_id >= MAX_CLOCKS)
951 		return (EINVAL);
952 
953 	if (posix_clocks[clock_id].timer_create == NULL)
954 		return (EINVAL);
955 
956 	if (evp != NULL) {
957 		if (evp->sigev_notify != SIGEV_NONE &&
958 		    evp->sigev_notify != SIGEV_SIGNAL &&
959 		    evp->sigev_notify != SIGEV_THREAD_ID)
960 			return (EINVAL);
961 		if ((evp->sigev_notify == SIGEV_SIGNAL ||
962 		     evp->sigev_notify == SIGEV_THREAD_ID) &&
963 			!_SIG_VALID(evp->sigev_signo))
964 			return (EINVAL);
965 	}
966 
967 	if (p->p_itimers == NULL)
968 		itimers_alloc(p);
969 
970 	it = uma_zalloc(itimer_zone, M_WAITOK);
971 	it->it_flags = 0;
972 	it->it_usecount = 0;
973 	it->it_active = 0;
974 	timespecclear(&it->it_time.it_value);
975 	timespecclear(&it->it_time.it_interval);
976 	it->it_overrun = 0;
977 	it->it_overrun_last = 0;
978 	it->it_clockid = clock_id;
979 	it->it_timerid = -1;
980 	it->it_proc = p;
981 	ksiginfo_init(&it->it_ksi);
982 	it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
983 	error = CLOCK_CALL(clock_id, timer_create, (it));
984 	if (error != 0)
985 		goto out;
986 
987 	PROC_LOCK(p);
988 	if (preset_id != -1) {
989 		KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
990 		id = preset_id;
991 		if (p->p_itimers->its_timers[id] != NULL) {
992 			PROC_UNLOCK(p);
993 			error = 0;
994 			goto out;
995 		}
996 	} else {
997 		/*
998 		 * Find a free timer slot, skipping those reserved
999 		 * for setitimer().
1000 		 */
1001 		for (id = 3; id < TIMER_MAX; id++)
1002 			if (p->p_itimers->its_timers[id] == NULL)
1003 				break;
1004 		if (id == TIMER_MAX) {
1005 			PROC_UNLOCK(p);
1006 			error = EAGAIN;
1007 			goto out;
1008 		}
1009 	}
1010 	it->it_timerid = id;
1011 	p->p_itimers->its_timers[id] = it;
1012 	if (evp != NULL)
1013 		it->it_sigev = *evp;
1014 	else {
1015 		it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1016 		switch (clock_id) {
1017 		default:
1018 		case CLOCK_REALTIME:
1019 			it->it_sigev.sigev_signo = SIGALRM;
1020 			break;
1021 		case CLOCK_VIRTUAL:
1022  			it->it_sigev.sigev_signo = SIGVTALRM;
1023 			break;
1024 		case CLOCK_PROF:
1025 			it->it_sigev.sigev_signo = SIGPROF;
1026 			break;
1027 		}
1028 		it->it_sigev.sigev_value.sival_int = id;
1029 	}
1030 
1031 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1032 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1033 		it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1034 		it->it_ksi.ksi_code = SI_TIMER;
1035 		it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1036 		it->it_ksi.ksi_timerid = id;
1037 	}
1038 	PROC_UNLOCK(p);
1039 	*timerid = id;
1040 	return (0);
1041 
1042 out:
1043 	ITIMER_LOCK(it);
1044 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1045 	ITIMER_UNLOCK(it);
1046 	uma_zfree(itimer_zone, it);
1047 	return (error);
1048 }
1049 
1050 #ifndef _SYS_SYSPROTO_H_
1051 struct ktimer_delete_args {
1052 	int timerid;
1053 };
1054 #endif
1055 int
1056 ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1057 {
1058 	return (kern_timer_delete(td, uap->timerid));
1059 }
1060 
1061 static struct itimer *
1062 itimer_find(struct proc *p, int timerid)
1063 {
1064 	struct itimer *it;
1065 
1066 	PROC_LOCK_ASSERT(p, MA_OWNED);
1067 	if ((p->p_itimers == NULL) || (timerid >= TIMER_MAX) ||
1068 	    (it = p->p_itimers->its_timers[timerid]) == NULL) {
1069 		return (NULL);
1070 	}
1071 	ITIMER_LOCK(it);
1072 	if ((it->it_flags & ITF_DELETING) != 0) {
1073 		ITIMER_UNLOCK(it);
1074 		it = NULL;
1075 	}
1076 	return (it);
1077 }
1078 
1079 static int
1080 kern_timer_delete(struct thread *td, int timerid)
1081 {
1082 	struct proc *p = td->td_proc;
1083 	struct itimer *it;
1084 
1085 	PROC_LOCK(p);
1086 	it = itimer_find(p, timerid);
1087 	if (it == NULL) {
1088 		PROC_UNLOCK(p);
1089 		return (EINVAL);
1090 	}
1091 	PROC_UNLOCK(p);
1092 
1093 	it->it_flags |= ITF_DELETING;
1094 	while (it->it_usecount > 0) {
1095 		it->it_flags |= ITF_WANTED;
1096 		msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1097 	}
1098 	it->it_flags &= ~ITF_WANTED;
1099 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1100 	ITIMER_UNLOCK(it);
1101 
1102 	PROC_LOCK(p);
1103 	if (KSI_ONQ(&it->it_ksi))
1104 		sigqueue_take(&it->it_ksi);
1105 	p->p_itimers->its_timers[timerid] = NULL;
1106 	PROC_UNLOCK(p);
1107 	uma_zfree(itimer_zone, it);
1108 	return (0);
1109 }
1110 
1111 #ifndef _SYS_SYSPROTO_H_
1112 struct ktimer_settime_args {
1113 	int timerid;
1114 	int flags;
1115 	const struct itimerspec * value;
1116 	struct itimerspec * ovalue;
1117 };
1118 #endif
1119 int
1120 ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1121 {
1122 	struct proc *p = td->td_proc;
1123 	struct itimer *it;
1124 	struct itimerspec val, oval, *ovalp;
1125 	int error;
1126 
1127 	error = copyin(uap->value, &val, sizeof(val));
1128 	if (error != 0)
1129 		return (error);
1130 
1131 	if (uap->ovalue != NULL)
1132 		ovalp = &oval;
1133 	else
1134 		ovalp = NULL;
1135 
1136 	PROC_LOCK(p);
1137 	if (uap->timerid < 3 ||
1138 	    (it = itimer_find(p, uap->timerid)) == NULL) {
1139 		PROC_UNLOCK(p);
1140 		error = EINVAL;
1141 	} else {
1142 		PROC_UNLOCK(p);
1143 		itimer_enter(it);
1144 		error = CLOCK_CALL(it->it_clockid, timer_settime,
1145 				(it, uap->flags, &val, ovalp));
1146 		itimer_leave(it);
1147 		ITIMER_UNLOCK(it);
1148 	}
1149 	if (error == 0 && uap->ovalue != NULL)
1150 		error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1151 	return (error);
1152 }
1153 
1154 #ifndef _SYS_SYSPROTO_H_
1155 struct ktimer_gettime_args {
1156 	int timerid;
1157 	struct itimerspec * value;
1158 };
1159 #endif
1160 int
1161 ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1162 {
1163 	struct proc *p = td->td_proc;
1164 	struct itimer *it;
1165 	struct itimerspec val;
1166 	int error;
1167 
1168 	PROC_LOCK(p);
1169 	if (uap->timerid < 3 ||
1170 	   (it = itimer_find(p, uap->timerid)) == NULL) {
1171 		PROC_UNLOCK(p);
1172 		error = EINVAL;
1173 	} else {
1174 		PROC_UNLOCK(p);
1175 		itimer_enter(it);
1176 		error = CLOCK_CALL(it->it_clockid, timer_gettime,
1177 				(it, &val));
1178 		itimer_leave(it);
1179 		ITIMER_UNLOCK(it);
1180 	}
1181 	if (error == 0)
1182 		error = copyout(&val, uap->value, sizeof(val));
1183 	return (error);
1184 }
1185 
1186 #ifndef _SYS_SYSPROTO_H_
1187 struct timer_getoverrun_args {
1188 	int timerid;
1189 };
1190 #endif
1191 int
1192 ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1193 {
1194 	struct proc *p = td->td_proc;
1195 	struct itimer *it;
1196 	int error ;
1197 
1198 	PROC_LOCK(p);
1199 	if (uap->timerid < 3 ||
1200 	    (it = itimer_find(p, uap->timerid)) == NULL) {
1201 		PROC_UNLOCK(p);
1202 		error = EINVAL;
1203 	} else {
1204 		td->td_retval[0] = it->it_overrun_last;
1205 		ITIMER_UNLOCK(it);
1206 		PROC_UNLOCK(p);
1207 		error = 0;
1208 	}
1209 	return (error);
1210 }
1211 
1212 static int
1213 realtimer_create(struct itimer *it)
1214 {
1215 	callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1216 	return (0);
1217 }
1218 
1219 static int
1220 realtimer_delete(struct itimer *it)
1221 {
1222 	mtx_assert(&it->it_mtx, MA_OWNED);
1223 
1224 	ITIMER_UNLOCK(it);
1225 	callout_drain(&it->it_callout);
1226 	ITIMER_LOCK(it);
1227 	return (0);
1228 }
1229 
1230 static int
1231 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1232 {
1233 	struct timespec cts;
1234 
1235 	mtx_assert(&it->it_mtx, MA_OWNED);
1236 
1237 	realtimer_clocktime(it->it_clockid, &cts);
1238 	*ovalue = it->it_time;
1239 	if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1240 		timespecsub(&ovalue->it_value, &cts);
1241 		if (ovalue->it_value.tv_sec < 0 ||
1242 		    (ovalue->it_value.tv_sec == 0 &&
1243 		     ovalue->it_value.tv_nsec == 0)) {
1244 			ovalue->it_value.tv_sec  = 0;
1245 			ovalue->it_value.tv_nsec = 1;
1246 		}
1247 	}
1248 	return (0);
1249 }
1250 
1251 static int
1252 realtimer_settime(struct itimer *it, int flags,
1253 	struct itimerspec *value, struct itimerspec *ovalue)
1254 {
1255 	struct timespec cts, ts;
1256 	struct timeval tv;
1257 	struct itimerspec val;
1258 
1259 	mtx_assert(&it->it_mtx, MA_OWNED);
1260 
1261 	val = *value;
1262 	if (itimespecfix(&val.it_value))
1263 		return (EINVAL);
1264 
1265 	if (timespecisset(&val.it_value)) {
1266 		if (itimespecfix(&val.it_interval))
1267 			return (EINVAL);
1268 	} else {
1269 		timespecclear(&val.it_interval);
1270 	}
1271 
1272 	if (ovalue != NULL)
1273 		realtimer_gettime(it, ovalue);
1274 
1275 	it->it_time = val;
1276 	if (timespecisset(&val.it_value)) {
1277 		realtimer_clocktime(it->it_clockid, &cts);
1278 		ts = val.it_value;
1279 		if ((flags & TIMER_ABSTIME) == 0) {
1280 			/* Convert to absolute time. */
1281 			timespecadd(&it->it_time.it_value, &cts);
1282 		} else {
1283 			timespecsub(&ts, &cts);
1284 			/*
1285 			 * We don't care if ts is negative, tztohz will
1286 			 * fix it.
1287 			 */
1288 		}
1289 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1290 		callout_reset(&it->it_callout, tvtohz(&tv),
1291 			realtimer_expire, it);
1292 	} else {
1293 		callout_stop(&it->it_callout);
1294 	}
1295 
1296 	return (0);
1297 }
1298 
1299 static void
1300 realtimer_clocktime(clockid_t id, struct timespec *ts)
1301 {
1302 	if (id == CLOCK_REALTIME)
1303 		getnanotime(ts);
1304 	else	/* CLOCK_MONOTONIC */
1305 		getnanouptime(ts);
1306 }
1307 
1308 int
1309 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1310 {
1311 	struct itimer *it;
1312 
1313 	PROC_LOCK_ASSERT(p, MA_OWNED);
1314 	it = itimer_find(p, timerid);
1315 	if (it != NULL) {
1316 		ksi->ksi_overrun = it->it_overrun;
1317 		it->it_overrun_last = it->it_overrun;
1318 		it->it_overrun = 0;
1319 		ITIMER_UNLOCK(it);
1320 		return (0);
1321 	}
1322 	return (EINVAL);
1323 }
1324 
1325 int
1326 itimespecfix(struct timespec *ts)
1327 {
1328 
1329 	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1330 		return (EINVAL);
1331 	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1332 		ts->tv_nsec = tick * 1000;
1333 	return (0);
1334 }
1335 
1336 /* Timeout callback for realtime timer */
1337 static void
1338 realtimer_expire(void *arg)
1339 {
1340 	struct timespec cts, ts;
1341 	struct timeval tv;
1342 	struct itimer *it;
1343 	struct proc *p;
1344 
1345 	it = (struct itimer *)arg;
1346 	p = it->it_proc;
1347 
1348 	realtimer_clocktime(it->it_clockid, &cts);
1349 	/* Only fire if time is reached. */
1350 	if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1351 		if (timespecisset(&it->it_time.it_interval)) {
1352 			timespecadd(&it->it_time.it_value,
1353 				    &it->it_time.it_interval);
1354 			while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1355 				if (it->it_overrun < INT_MAX)
1356 					it->it_overrun++;
1357 				else
1358 					it->it_ksi.ksi_errno = ERANGE;
1359 				timespecadd(&it->it_time.it_value,
1360 					    &it->it_time.it_interval);
1361 			}
1362 		} else {
1363 			/* single shot timer ? */
1364 			timespecclear(&it->it_time.it_value);
1365 		}
1366 		if (timespecisset(&it->it_time.it_value)) {
1367 			ts = it->it_time.it_value;
1368 			timespecsub(&ts, &cts);
1369 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1370 			callout_reset(&it->it_callout, tvtohz(&tv),
1371 				 realtimer_expire, it);
1372 		}
1373 		ITIMER_UNLOCK(it);
1374 		itimer_fire(it);
1375 		ITIMER_LOCK(it);
1376 	} else if (timespecisset(&it->it_time.it_value)) {
1377 		ts = it->it_time.it_value;
1378 		timespecsub(&ts, &cts);
1379 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1380 		callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1381  			it);
1382 	}
1383 }
1384 
1385 void
1386 itimer_fire(struct itimer *it)
1387 {
1388 	struct proc *p = it->it_proc;
1389 	int ret;
1390 
1391 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1392 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1393 		PROC_LOCK(p);
1394 		if (!KSI_ONQ(&it->it_ksi)) {
1395 			it->it_ksi.ksi_errno = 0;
1396 			ret = psignal_event(p, &it->it_sigev, &it->it_ksi);
1397 			if (__predict_false(ret != 0)) {
1398 				it->it_overrun++;
1399 				/*
1400 				 * Broken userland code, thread went
1401 				 * away, disarm the timer.
1402 				 */
1403 				if (ret == ESRCH) {
1404 					ITIMER_LOCK(it);
1405 					timespecclear(&it->it_time.it_value);
1406 					timespecclear(&it->it_time.it_interval);
1407 					callout_stop(&it->it_callout);
1408 					ITIMER_UNLOCK(it);
1409 				}
1410 			}
1411 		} else {
1412 			if (it->it_overrun < INT_MAX)
1413 				it->it_overrun++;
1414 			else
1415 				it->it_ksi.ksi_errno = ERANGE;
1416 		}
1417 		PROC_UNLOCK(p);
1418 	}
1419 }
1420 
1421 static void
1422 itimers_alloc(struct proc *p)
1423 {
1424 	struct itimers *its;
1425 	int i;
1426 
1427 	its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1428 	LIST_INIT(&its->its_virtual);
1429 	LIST_INIT(&its->its_prof);
1430 	TAILQ_INIT(&its->its_worklist);
1431 	for (i = 0; i < TIMER_MAX; i++)
1432 		its->its_timers[i] = NULL;
1433 	PROC_LOCK(p);
1434 	if (p->p_itimers == NULL) {
1435 		p->p_itimers = its;
1436 		PROC_UNLOCK(p);
1437 	}
1438 	else {
1439 		PROC_UNLOCK(p);
1440 		free(its, M_SUBPROC);
1441 	}
1442 }
1443 
1444 static void
1445 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1446 {
1447 	itimers_event_hook_exit(arg, p);
1448 }
1449 
1450 /* Clean up timers when some process events are being triggered. */
1451 static void
1452 itimers_event_hook_exit(void *arg, struct proc *p)
1453 {
1454 	struct itimers *its;
1455 	struct itimer *it;
1456 	int event = (int)(intptr_t)arg;
1457 	int i;
1458 
1459 	if (p->p_itimers != NULL) {
1460 		its = p->p_itimers;
1461 		for (i = 0; i < MAX_CLOCKS; ++i) {
1462 			if (posix_clocks[i].event_hook != NULL)
1463 				CLOCK_CALL(i, event_hook, (p, i, event));
1464 		}
1465 		/*
1466 		 * According to susv3, XSI interval timers should be inherited
1467 		 * by new image.
1468 		 */
1469 		if (event == ITIMER_EV_EXEC)
1470 			i = 3;
1471 		else if (event == ITIMER_EV_EXIT)
1472 			i = 0;
1473 		else
1474 			panic("unhandled event");
1475 		for (; i < TIMER_MAX; ++i) {
1476 			if ((it = its->its_timers[i]) != NULL)
1477 				kern_timer_delete(curthread, i);
1478 		}
1479 		if (its->its_timers[0] == NULL &&
1480 		    its->its_timers[1] == NULL &&
1481 		    its->its_timers[2] == NULL) {
1482 			free(its, M_SUBPROC);
1483 			p->p_itimers = NULL;
1484 		}
1485 	}
1486 }
1487