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