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