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