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