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