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