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