xref: /freebsd/sys/kern/kern_time.c (revision 864c53ead899f7838cd2e1cca3b485a4a82f5cdc)
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 
102 int		register_posix_clock(int, struct kclock *);
103 void		itimer_fire(struct itimer *it);
104 int		itimespecfix(struct timespec *ts);
105 
106 #define CLOCK_CALL(clock, call, arglist)		\
107 	((*posix_clocks[clock].call) arglist)
108 
109 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
110 
111 
112 static int
113 settime(struct thread *td, struct timeval *tv)
114 {
115 	struct timeval delta, tv1, tv2;
116 	static struct timeval maxtime, laststep;
117 	struct timespec ts;
118 	int s;
119 
120 	s = splclock();
121 	microtime(&tv1);
122 	delta = *tv;
123 	timevalsub(&delta, &tv1);
124 
125 	/*
126 	 * If the system is secure, we do not allow the time to be
127 	 * set to a value earlier than 1 second less than the highest
128 	 * time we have yet seen. The worst a miscreant can do in
129 	 * this circumstance is "freeze" time. He couldn't go
130 	 * back to the past.
131 	 *
132 	 * We similarly do not allow the clock to be stepped more
133 	 * than one second, nor more than once per second. This allows
134 	 * a miscreant to make the clock march double-time, but no worse.
135 	 */
136 	if (securelevel_gt(td->td_ucred, 1) != 0) {
137 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
138 			/*
139 			 * Update maxtime to latest time we've seen.
140 			 */
141 			if (tv1.tv_sec > maxtime.tv_sec)
142 				maxtime = tv1;
143 			tv2 = *tv;
144 			timevalsub(&tv2, &maxtime);
145 			if (tv2.tv_sec < -1) {
146 				tv->tv_sec = maxtime.tv_sec - 1;
147 				printf("Time adjustment clamped to -1 second\n");
148 			}
149 		} else {
150 			if (tv1.tv_sec == laststep.tv_sec) {
151 				splx(s);
152 				return (EPERM);
153 			}
154 			if (delta.tv_sec > 1) {
155 				tv->tv_sec = tv1.tv_sec + 1;
156 				printf("Time adjustment clamped to +1 second\n");
157 			}
158 			laststep = *tv;
159 		}
160 	}
161 
162 	ts.tv_sec = tv->tv_sec;
163 	ts.tv_nsec = tv->tv_usec * 1000;
164 	mtx_lock(&Giant);
165 	tc_setclock(&ts);
166 	resettodr();
167 	mtx_unlock(&Giant);
168 	return (0);
169 }
170 
171 #ifndef _SYS_SYSPROTO_H_
172 struct clock_getcpuclockid2_args {
173 	id_t id;
174 	int which,
175 	clockid_t *clock_id;
176 };
177 #endif
178 /* ARGSUSED */
179 int
180 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
181 {
182 	clockid_t clk_id;
183 	int error;
184 
185 	error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
186 	if (error == 0)
187 		error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
188 	return (error);
189 }
190 
191 int
192 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
193     clockid_t *clk_id)
194 {
195 	struct proc *p;
196 	pid_t pid;
197 	lwpid_t tid;
198 	int error;
199 
200 	switch (which) {
201 	case CPUCLOCK_WHICH_PID:
202 		if (id != 0) {
203 			p = pfind(id);
204 			if (p == NULL)
205 				return (ESRCH);
206 			error = p_cansee(td, p);
207 			PROC_UNLOCK(p);
208 			if (error != 0)
209 				return (error);
210 			pid = id;
211 		} else {
212 			pid = td->td_proc->p_pid;
213 		}
214 		*clk_id = MAKE_PROCESS_CPUCLOCK(pid);
215 		return (0);
216 	case CPUCLOCK_WHICH_TID:
217 		tid = id == 0 ? td->td_tid : id;
218 		*clk_id = MAKE_THREAD_CPUCLOCK(tid);
219 		return (0);
220 	default:
221 		return (EINVAL);
222 	}
223 }
224 
225 #ifndef _SYS_SYSPROTO_H_
226 struct clock_gettime_args {
227 	clockid_t clock_id;
228 	struct	timespec *tp;
229 };
230 #endif
231 /* ARGSUSED */
232 int
233 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
234 {
235 	struct timespec ats;
236 	int error;
237 
238 	error = kern_clock_gettime(td, uap->clock_id, &ats);
239 	if (error == 0)
240 		error = copyout(&ats, uap->tp, sizeof(ats));
241 
242 	return (error);
243 }
244 
245 static inline void
246 cputick2timespec(uint64_t runtime, struct timespec *ats)
247 {
248 	runtime = cputick2usec(runtime);
249 	ats->tv_sec = runtime / 1000000;
250 	ats->tv_nsec = runtime % 1000000 * 1000;
251 }
252 
253 static void
254 get_thread_cputime(struct thread *targettd, struct timespec *ats)
255 {
256 	uint64_t runtime, curtime, switchtime;
257 
258 	if (targettd == NULL) { /* current thread */
259 		critical_enter();
260 		switchtime = PCPU_GET(switchtime);
261 		curtime = cpu_ticks();
262 		runtime = curthread->td_runtime;
263 		critical_exit();
264 		runtime += curtime - switchtime;
265 	} else {
266 		thread_lock(targettd);
267 		runtime = targettd->td_runtime;
268 		thread_unlock(targettd);
269 	}
270 	cputick2timespec(runtime, ats);
271 }
272 
273 static void
274 get_process_cputime(struct proc *targetp, struct timespec *ats)
275 {
276 	uint64_t runtime;
277 	struct rusage ru;
278 
279 	PROC_SLOCK(targetp);
280 	rufetch(targetp, &ru);
281 	runtime = targetp->p_rux.rux_runtime;
282 	PROC_SUNLOCK(targetp);
283 	cputick2timespec(runtime, ats);
284 }
285 
286 static int
287 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
288 {
289 	struct proc *p, *p2;
290 	struct thread *td2;
291 	lwpid_t tid;
292 	pid_t pid;
293 	int error;
294 
295 	p = td->td_proc;
296 	if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
297 		tid = clock_id & CPUCLOCK_ID_MASK;
298 		td2 = tdfind(tid, p->p_pid);
299 		if (td2 == NULL)
300 			return (EINVAL);
301 		get_thread_cputime(td2, ats);
302 		PROC_UNLOCK(td2->td_proc);
303 	} else {
304 		pid = clock_id & CPUCLOCK_ID_MASK;
305 		error = pget(pid, PGET_CANSEE, &p2);
306 		if (error != 0)
307 			return (EINVAL);
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 		if (aitv->it_interval.tv_sec == 0 &&
778 		    aitv->it_interval.tv_usec != 0 &&
779 		    aitv->it_interval.tv_usec < tick)
780 			aitv->it_interval.tv_usec = tick;
781 		if (aitv->it_value.tv_sec == 0 &&
782 		    aitv->it_value.tv_usec != 0 &&
783 		    aitv->it_value.tv_usec < tick)
784 			aitv->it_value.tv_usec = tick;
785 		PROC_SLOCK(p);
786 		*oitv = p->p_stats->p_timer[which];
787 		p->p_stats->p_timer[which] = *aitv;
788 		PROC_SUNLOCK(p);
789 	}
790 	return (0);
791 }
792 
793 /*
794  * Real interval timer expired:
795  * send process whose timer expired an alarm signal.
796  * If time is not set up to reload, then just return.
797  * Else compute next time timer should go off which is > current time.
798  * This is where delay in processing this timeout causes multiple
799  * SIGALRM calls to be compressed into one.
800  * tvtohz() always adds 1 to allow for the time until the next clock
801  * interrupt being strictly less than 1 clock tick, but we don't want
802  * that here since we want to appear to be in sync with the clock
803  * interrupt even when we're delayed.
804  */
805 void
806 realitexpire(void *arg)
807 {
808 	struct proc *p;
809 	struct timeval ctv;
810 	sbintime_t isbt;
811 
812 	p = (struct proc *)arg;
813 	kern_psignal(p, SIGALRM);
814 	if (!timevalisset(&p->p_realtimer.it_interval)) {
815 		timevalclear(&p->p_realtimer.it_value);
816 		if (p->p_flag & P_WEXIT)
817 			wakeup(&p->p_itcallout);
818 		return;
819 	}
820 	isbt = tvtosbt(p->p_realtimer.it_interval);
821 	if (isbt >= sbt_timethreshold)
822 		getmicrouptime(&ctv);
823 	else
824 		microuptime(&ctv);
825 	do {
826 		timevaladd(&p->p_realtimer.it_value,
827 		    &p->p_realtimer.it_interval);
828 	} while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
829 	callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
830 	    isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
831 }
832 
833 /*
834  * Check that a proposed value to load into the .it_value or
835  * .it_interval part of an interval timer is acceptable, and
836  * fix it to have at least minimal value (i.e. if it is less
837  * than the resolution of the clock, round it up.)
838  */
839 int
840 itimerfix(struct timeval *tv)
841 {
842 
843 	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
844 		return (EINVAL);
845 	if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
846 	    tv->tv_usec < (u_int)tick / 16)
847 		tv->tv_usec = (u_int)tick / 16;
848 	return (0);
849 }
850 
851 /*
852  * Decrement an interval timer by a specified number
853  * of microseconds, which must be less than a second,
854  * i.e. < 1000000.  If the timer expires, then reload
855  * it.  In this case, carry over (usec - old value) to
856  * reduce the value reloaded into the timer so that
857  * the timer does not drift.  This routine assumes
858  * that it is called in a context where the timers
859  * on which it is operating cannot change in value.
860  */
861 int
862 itimerdecr(struct itimerval *itp, int usec)
863 {
864 
865 	if (itp->it_value.tv_usec < usec) {
866 		if (itp->it_value.tv_sec == 0) {
867 			/* expired, and already in next interval */
868 			usec -= itp->it_value.tv_usec;
869 			goto expire;
870 		}
871 		itp->it_value.tv_usec += 1000000;
872 		itp->it_value.tv_sec--;
873 	}
874 	itp->it_value.tv_usec -= usec;
875 	usec = 0;
876 	if (timevalisset(&itp->it_value))
877 		return (1);
878 	/* expired, exactly at end of interval */
879 expire:
880 	if (timevalisset(&itp->it_interval)) {
881 		itp->it_value = itp->it_interval;
882 		itp->it_value.tv_usec -= usec;
883 		if (itp->it_value.tv_usec < 0) {
884 			itp->it_value.tv_usec += 1000000;
885 			itp->it_value.tv_sec--;
886 		}
887 	} else
888 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
889 	return (0);
890 }
891 
892 /*
893  * Add and subtract routines for timevals.
894  * N.B.: subtract routine doesn't deal with
895  * results which are before the beginning,
896  * it just gets very confused in this case.
897  * Caveat emptor.
898  */
899 void
900 timevaladd(struct timeval *t1, const struct timeval *t2)
901 {
902 
903 	t1->tv_sec += t2->tv_sec;
904 	t1->tv_usec += t2->tv_usec;
905 	timevalfix(t1);
906 }
907 
908 void
909 timevalsub(struct timeval *t1, const struct timeval *t2)
910 {
911 
912 	t1->tv_sec -= t2->tv_sec;
913 	t1->tv_usec -= t2->tv_usec;
914 	timevalfix(t1);
915 }
916 
917 static void
918 timevalfix(struct timeval *t1)
919 {
920 
921 	if (t1->tv_usec < 0) {
922 		t1->tv_sec--;
923 		t1->tv_usec += 1000000;
924 	}
925 	if (t1->tv_usec >= 1000000) {
926 		t1->tv_sec++;
927 		t1->tv_usec -= 1000000;
928 	}
929 }
930 
931 /*
932  * ratecheck(): simple time-based rate-limit checking.
933  */
934 int
935 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
936 {
937 	struct timeval tv, delta;
938 	int rv = 0;
939 
940 	getmicrouptime(&tv);		/* NB: 10ms precision */
941 	delta = tv;
942 	timevalsub(&delta, lasttime);
943 
944 	/*
945 	 * check for 0,0 is so that the message will be seen at least once,
946 	 * even if interval is huge.
947 	 */
948 	if (timevalcmp(&delta, mininterval, >=) ||
949 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
950 		*lasttime = tv;
951 		rv = 1;
952 	}
953 
954 	return (rv);
955 }
956 
957 /*
958  * ppsratecheck(): packets (or events) per second limitation.
959  *
960  * Return 0 if the limit is to be enforced (e.g. the caller
961  * should drop a packet because of the rate limitation).
962  *
963  * maxpps of 0 always causes zero to be returned.  maxpps of -1
964  * always causes 1 to be returned; this effectively defeats rate
965  * limiting.
966  *
967  * Note that we maintain the struct timeval for compatibility
968  * with other bsd systems.  We reuse the storage and just monitor
969  * clock ticks for minimal overhead.
970  */
971 int
972 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
973 {
974 	int now;
975 
976 	/*
977 	 * Reset the last time and counter if this is the first call
978 	 * or more than a second has passed since the last update of
979 	 * lasttime.
980 	 */
981 	now = ticks;
982 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
983 		lasttime->tv_sec = now;
984 		*curpps = 1;
985 		return (maxpps != 0);
986 	} else {
987 		(*curpps)++;		/* NB: ignore potential overflow */
988 		return (maxpps < 0 || *curpps < maxpps);
989 	}
990 }
991 
992 static void
993 itimer_start(void)
994 {
995 	struct kclock rt_clock = {
996 		.timer_create  = realtimer_create,
997 		.timer_delete  = realtimer_delete,
998 		.timer_settime = realtimer_settime,
999 		.timer_gettime = realtimer_gettime,
1000 		.event_hook    = NULL
1001 	};
1002 
1003 	itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1004 		NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1005 	register_posix_clock(CLOCK_REALTIME,  &rt_clock);
1006 	register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1007 	p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1008 	p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1009 	p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1010 	EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1011 		(void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1012 	EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1013 		(void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1014 }
1015 
1016 int
1017 register_posix_clock(int clockid, struct kclock *clk)
1018 {
1019 	if ((unsigned)clockid >= MAX_CLOCKS) {
1020 		printf("%s: invalid clockid\n", __func__);
1021 		return (0);
1022 	}
1023 	posix_clocks[clockid] = *clk;
1024 	return (1);
1025 }
1026 
1027 static int
1028 itimer_init(void *mem, int size, int flags)
1029 {
1030 	struct itimer *it;
1031 
1032 	it = (struct itimer *)mem;
1033 	mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1034 	return (0);
1035 }
1036 
1037 static void
1038 itimer_fini(void *mem, int size)
1039 {
1040 	struct itimer *it;
1041 
1042 	it = (struct itimer *)mem;
1043 	mtx_destroy(&it->it_mtx);
1044 }
1045 
1046 static void
1047 itimer_enter(struct itimer *it)
1048 {
1049 
1050 	mtx_assert(&it->it_mtx, MA_OWNED);
1051 	it->it_usecount++;
1052 }
1053 
1054 static void
1055 itimer_leave(struct itimer *it)
1056 {
1057 
1058 	mtx_assert(&it->it_mtx, MA_OWNED);
1059 	KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1060 
1061 	if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1062 		wakeup(it);
1063 }
1064 
1065 #ifndef _SYS_SYSPROTO_H_
1066 struct ktimer_create_args {
1067 	clockid_t clock_id;
1068 	struct sigevent * evp;
1069 	int * timerid;
1070 };
1071 #endif
1072 int
1073 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1074 {
1075 	struct sigevent *evp, ev;
1076 	int id;
1077 	int error;
1078 
1079 	if (uap->evp == NULL) {
1080 		evp = NULL;
1081 	} else {
1082 		error = copyin(uap->evp, &ev, sizeof(ev));
1083 		if (error != 0)
1084 			return (error);
1085 		evp = &ev;
1086 	}
1087 	error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1088 	if (error == 0) {
1089 		error = copyout(&id, uap->timerid, sizeof(int));
1090 		if (error != 0)
1091 			kern_ktimer_delete(td, id);
1092 	}
1093 	return (error);
1094 }
1095 
1096 int
1097 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1098     int *timerid, int preset_id)
1099 {
1100 	struct proc *p = td->td_proc;
1101 	struct itimer *it;
1102 	int id;
1103 	int error;
1104 
1105 	if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1106 		return (EINVAL);
1107 
1108 	if (posix_clocks[clock_id].timer_create == NULL)
1109 		return (EINVAL);
1110 
1111 	if (evp != NULL) {
1112 		if (evp->sigev_notify != SIGEV_NONE &&
1113 		    evp->sigev_notify != SIGEV_SIGNAL &&
1114 		    evp->sigev_notify != SIGEV_THREAD_ID)
1115 			return (EINVAL);
1116 		if ((evp->sigev_notify == SIGEV_SIGNAL ||
1117 		     evp->sigev_notify == SIGEV_THREAD_ID) &&
1118 			!_SIG_VALID(evp->sigev_signo))
1119 			return (EINVAL);
1120 	}
1121 
1122 	if (p->p_itimers == NULL)
1123 		itimers_alloc(p);
1124 
1125 	it = uma_zalloc(itimer_zone, M_WAITOK);
1126 	it->it_flags = 0;
1127 	it->it_usecount = 0;
1128 	it->it_active = 0;
1129 	timespecclear(&it->it_time.it_value);
1130 	timespecclear(&it->it_time.it_interval);
1131 	it->it_overrun = 0;
1132 	it->it_overrun_last = 0;
1133 	it->it_clockid = clock_id;
1134 	it->it_timerid = -1;
1135 	it->it_proc = p;
1136 	ksiginfo_init(&it->it_ksi);
1137 	it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1138 	error = CLOCK_CALL(clock_id, timer_create, (it));
1139 	if (error != 0)
1140 		goto out;
1141 
1142 	PROC_LOCK(p);
1143 	if (preset_id != -1) {
1144 		KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1145 		id = preset_id;
1146 		if (p->p_itimers->its_timers[id] != NULL) {
1147 			PROC_UNLOCK(p);
1148 			error = 0;
1149 			goto out;
1150 		}
1151 	} else {
1152 		/*
1153 		 * Find a free timer slot, skipping those reserved
1154 		 * for setitimer().
1155 		 */
1156 		for (id = 3; id < TIMER_MAX; id++)
1157 			if (p->p_itimers->its_timers[id] == NULL)
1158 				break;
1159 		if (id == TIMER_MAX) {
1160 			PROC_UNLOCK(p);
1161 			error = EAGAIN;
1162 			goto out;
1163 		}
1164 	}
1165 	it->it_timerid = id;
1166 	p->p_itimers->its_timers[id] = it;
1167 	if (evp != NULL)
1168 		it->it_sigev = *evp;
1169 	else {
1170 		it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1171 		switch (clock_id) {
1172 		default:
1173 		case CLOCK_REALTIME:
1174 			it->it_sigev.sigev_signo = SIGALRM;
1175 			break;
1176 		case CLOCK_VIRTUAL:
1177  			it->it_sigev.sigev_signo = SIGVTALRM;
1178 			break;
1179 		case CLOCK_PROF:
1180 			it->it_sigev.sigev_signo = SIGPROF;
1181 			break;
1182 		}
1183 		it->it_sigev.sigev_value.sival_int = id;
1184 	}
1185 
1186 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1187 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1188 		it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1189 		it->it_ksi.ksi_code = SI_TIMER;
1190 		it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1191 		it->it_ksi.ksi_timerid = id;
1192 	}
1193 	PROC_UNLOCK(p);
1194 	*timerid = id;
1195 	return (0);
1196 
1197 out:
1198 	ITIMER_LOCK(it);
1199 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1200 	ITIMER_UNLOCK(it);
1201 	uma_zfree(itimer_zone, it);
1202 	return (error);
1203 }
1204 
1205 #ifndef _SYS_SYSPROTO_H_
1206 struct ktimer_delete_args {
1207 	int timerid;
1208 };
1209 #endif
1210 int
1211 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1212 {
1213 
1214 	return (kern_ktimer_delete(td, uap->timerid));
1215 }
1216 
1217 static struct itimer *
1218 itimer_find(struct proc *p, int timerid)
1219 {
1220 	struct itimer *it;
1221 
1222 	PROC_LOCK_ASSERT(p, MA_OWNED);
1223 	if ((p->p_itimers == NULL) ||
1224 	    (timerid < 0) || (timerid >= TIMER_MAX) ||
1225 	    (it = p->p_itimers->its_timers[timerid]) == NULL) {
1226 		return (NULL);
1227 	}
1228 	ITIMER_LOCK(it);
1229 	if ((it->it_flags & ITF_DELETING) != 0) {
1230 		ITIMER_UNLOCK(it);
1231 		it = NULL;
1232 	}
1233 	return (it);
1234 }
1235 
1236 int
1237 kern_ktimer_delete(struct thread *td, int timerid)
1238 {
1239 	struct proc *p = td->td_proc;
1240 	struct itimer *it;
1241 
1242 	PROC_LOCK(p);
1243 	it = itimer_find(p, timerid);
1244 	if (it == NULL) {
1245 		PROC_UNLOCK(p);
1246 		return (EINVAL);
1247 	}
1248 	PROC_UNLOCK(p);
1249 
1250 	it->it_flags |= ITF_DELETING;
1251 	while (it->it_usecount > 0) {
1252 		it->it_flags |= ITF_WANTED;
1253 		msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1254 	}
1255 	it->it_flags &= ~ITF_WANTED;
1256 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1257 	ITIMER_UNLOCK(it);
1258 
1259 	PROC_LOCK(p);
1260 	if (KSI_ONQ(&it->it_ksi))
1261 		sigqueue_take(&it->it_ksi);
1262 	p->p_itimers->its_timers[timerid] = NULL;
1263 	PROC_UNLOCK(p);
1264 	uma_zfree(itimer_zone, it);
1265 	return (0);
1266 }
1267 
1268 #ifndef _SYS_SYSPROTO_H_
1269 struct ktimer_settime_args {
1270 	int timerid;
1271 	int flags;
1272 	const struct itimerspec * value;
1273 	struct itimerspec * ovalue;
1274 };
1275 #endif
1276 int
1277 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1278 {
1279 	struct itimerspec val, oval, *ovalp;
1280 	int error;
1281 
1282 	error = copyin(uap->value, &val, sizeof(val));
1283 	if (error != 0)
1284 		return (error);
1285 	ovalp = uap->ovalue != NULL ? &oval : NULL;
1286 	error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1287 	if (error == 0 && uap->ovalue != NULL)
1288 		error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1289 	return (error);
1290 }
1291 
1292 int
1293 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1294     struct itimerspec *val, struct itimerspec *oval)
1295 {
1296 	struct proc *p;
1297 	struct itimer *it;
1298 	int error;
1299 
1300 	p = td->td_proc;
1301 	PROC_LOCK(p);
1302 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1303 		PROC_UNLOCK(p);
1304 		error = EINVAL;
1305 	} else {
1306 		PROC_UNLOCK(p);
1307 		itimer_enter(it);
1308 		error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1309 		    flags, val, oval));
1310 		itimer_leave(it);
1311 		ITIMER_UNLOCK(it);
1312 	}
1313 	return (error);
1314 }
1315 
1316 #ifndef _SYS_SYSPROTO_H_
1317 struct ktimer_gettime_args {
1318 	int timerid;
1319 	struct itimerspec * value;
1320 };
1321 #endif
1322 int
1323 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1324 {
1325 	struct itimerspec val;
1326 	int error;
1327 
1328 	error = kern_ktimer_gettime(td, uap->timerid, &val);
1329 	if (error == 0)
1330 		error = copyout(&val, uap->value, sizeof(val));
1331 	return (error);
1332 }
1333 
1334 int
1335 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1336 {
1337 	struct proc *p;
1338 	struct itimer *it;
1339 	int error;
1340 
1341 	p = td->td_proc;
1342 	PROC_LOCK(p);
1343 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1344 		PROC_UNLOCK(p);
1345 		error = EINVAL;
1346 	} else {
1347 		PROC_UNLOCK(p);
1348 		itimer_enter(it);
1349 		error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1350 		itimer_leave(it);
1351 		ITIMER_UNLOCK(it);
1352 	}
1353 	return (error);
1354 }
1355 
1356 #ifndef _SYS_SYSPROTO_H_
1357 struct timer_getoverrun_args {
1358 	int timerid;
1359 };
1360 #endif
1361 int
1362 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1363 {
1364 	struct proc *p = td->td_proc;
1365 	struct itimer *it;
1366 	int error ;
1367 
1368 	PROC_LOCK(p);
1369 	if (uap->timerid < 3 ||
1370 	    (it = itimer_find(p, uap->timerid)) == NULL) {
1371 		PROC_UNLOCK(p);
1372 		error = EINVAL;
1373 	} else {
1374 		td->td_retval[0] = it->it_overrun_last;
1375 		ITIMER_UNLOCK(it);
1376 		PROC_UNLOCK(p);
1377 		error = 0;
1378 	}
1379 	return (error);
1380 }
1381 
1382 static int
1383 realtimer_create(struct itimer *it)
1384 {
1385 	callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1386 	return (0);
1387 }
1388 
1389 static int
1390 realtimer_delete(struct itimer *it)
1391 {
1392 	mtx_assert(&it->it_mtx, MA_OWNED);
1393 
1394 	/*
1395 	 * clear timer's value and interval to tell realtimer_expire
1396 	 * to not rearm the timer.
1397 	 */
1398 	timespecclear(&it->it_time.it_value);
1399 	timespecclear(&it->it_time.it_interval);
1400 	ITIMER_UNLOCK(it);
1401 	callout_drain(&it->it_callout);
1402 	ITIMER_LOCK(it);
1403 	return (0);
1404 }
1405 
1406 static int
1407 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1408 {
1409 	struct timespec cts;
1410 
1411 	mtx_assert(&it->it_mtx, MA_OWNED);
1412 
1413 	realtimer_clocktime(it->it_clockid, &cts);
1414 	*ovalue = it->it_time;
1415 	if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1416 		timespecsub(&ovalue->it_value, &cts);
1417 		if (ovalue->it_value.tv_sec < 0 ||
1418 		    (ovalue->it_value.tv_sec == 0 &&
1419 		     ovalue->it_value.tv_nsec == 0)) {
1420 			ovalue->it_value.tv_sec  = 0;
1421 			ovalue->it_value.tv_nsec = 1;
1422 		}
1423 	}
1424 	return (0);
1425 }
1426 
1427 static int
1428 realtimer_settime(struct itimer *it, int flags,
1429 	struct itimerspec *value, struct itimerspec *ovalue)
1430 {
1431 	struct timespec cts, ts;
1432 	struct timeval tv;
1433 	struct itimerspec val;
1434 
1435 	mtx_assert(&it->it_mtx, MA_OWNED);
1436 
1437 	val = *value;
1438 	if (itimespecfix(&val.it_value))
1439 		return (EINVAL);
1440 
1441 	if (timespecisset(&val.it_value)) {
1442 		if (itimespecfix(&val.it_interval))
1443 			return (EINVAL);
1444 	} else {
1445 		timespecclear(&val.it_interval);
1446 	}
1447 
1448 	if (ovalue != NULL)
1449 		realtimer_gettime(it, ovalue);
1450 
1451 	it->it_time = val;
1452 	if (timespecisset(&val.it_value)) {
1453 		realtimer_clocktime(it->it_clockid, &cts);
1454 		ts = val.it_value;
1455 		if ((flags & TIMER_ABSTIME) == 0) {
1456 			/* Convert to absolute time. */
1457 			timespecadd(&it->it_time.it_value, &cts);
1458 		} else {
1459 			timespecsub(&ts, &cts);
1460 			/*
1461 			 * We don't care if ts is negative, tztohz will
1462 			 * fix it.
1463 			 */
1464 		}
1465 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1466 		callout_reset(&it->it_callout, tvtohz(&tv),
1467 			realtimer_expire, it);
1468 	} else {
1469 		callout_stop(&it->it_callout);
1470 	}
1471 
1472 	return (0);
1473 }
1474 
1475 static void
1476 realtimer_clocktime(clockid_t id, struct timespec *ts)
1477 {
1478 	if (id == CLOCK_REALTIME)
1479 		getnanotime(ts);
1480 	else	/* CLOCK_MONOTONIC */
1481 		getnanouptime(ts);
1482 }
1483 
1484 int
1485 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1486 {
1487 	struct itimer *it;
1488 
1489 	PROC_LOCK_ASSERT(p, MA_OWNED);
1490 	it = itimer_find(p, timerid);
1491 	if (it != NULL) {
1492 		ksi->ksi_overrun = it->it_overrun;
1493 		it->it_overrun_last = it->it_overrun;
1494 		it->it_overrun = 0;
1495 		ITIMER_UNLOCK(it);
1496 		return (0);
1497 	}
1498 	return (EINVAL);
1499 }
1500 
1501 int
1502 itimespecfix(struct timespec *ts)
1503 {
1504 
1505 	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1506 		return (EINVAL);
1507 	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1508 		ts->tv_nsec = tick * 1000;
1509 	return (0);
1510 }
1511 
1512 /* Timeout callback for realtime timer */
1513 static void
1514 realtimer_expire(void *arg)
1515 {
1516 	struct timespec cts, ts;
1517 	struct timeval tv;
1518 	struct itimer *it;
1519 
1520 	it = (struct itimer *)arg;
1521 
1522 	realtimer_clocktime(it->it_clockid, &cts);
1523 	/* Only fire if time is reached. */
1524 	if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1525 		if (timespecisset(&it->it_time.it_interval)) {
1526 			timespecadd(&it->it_time.it_value,
1527 				    &it->it_time.it_interval);
1528 			while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1529 				if (it->it_overrun < INT_MAX)
1530 					it->it_overrun++;
1531 				else
1532 					it->it_ksi.ksi_errno = ERANGE;
1533 				timespecadd(&it->it_time.it_value,
1534 					    &it->it_time.it_interval);
1535 			}
1536 		} else {
1537 			/* single shot timer ? */
1538 			timespecclear(&it->it_time.it_value);
1539 		}
1540 		if (timespecisset(&it->it_time.it_value)) {
1541 			ts = it->it_time.it_value;
1542 			timespecsub(&ts, &cts);
1543 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1544 			callout_reset(&it->it_callout, tvtohz(&tv),
1545 				 realtimer_expire, it);
1546 		}
1547 		itimer_enter(it);
1548 		ITIMER_UNLOCK(it);
1549 		itimer_fire(it);
1550 		ITIMER_LOCK(it);
1551 		itimer_leave(it);
1552 	} else if (timespecisset(&it->it_time.it_value)) {
1553 		ts = it->it_time.it_value;
1554 		timespecsub(&ts, &cts);
1555 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1556 		callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1557  			it);
1558 	}
1559 }
1560 
1561 void
1562 itimer_fire(struct itimer *it)
1563 {
1564 	struct proc *p = it->it_proc;
1565 	struct thread *td;
1566 
1567 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1568 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1569 		if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1570 			ITIMER_LOCK(it);
1571 			timespecclear(&it->it_time.it_value);
1572 			timespecclear(&it->it_time.it_interval);
1573 			callout_stop(&it->it_callout);
1574 			ITIMER_UNLOCK(it);
1575 			return;
1576 		}
1577 		if (!KSI_ONQ(&it->it_ksi)) {
1578 			it->it_ksi.ksi_errno = 0;
1579 			ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1580 			tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1581 		} else {
1582 			if (it->it_overrun < INT_MAX)
1583 				it->it_overrun++;
1584 			else
1585 				it->it_ksi.ksi_errno = ERANGE;
1586 		}
1587 		PROC_UNLOCK(p);
1588 	}
1589 }
1590 
1591 static void
1592 itimers_alloc(struct proc *p)
1593 {
1594 	struct itimers *its;
1595 	int i;
1596 
1597 	its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1598 	LIST_INIT(&its->its_virtual);
1599 	LIST_INIT(&its->its_prof);
1600 	TAILQ_INIT(&its->its_worklist);
1601 	for (i = 0; i < TIMER_MAX; i++)
1602 		its->its_timers[i] = NULL;
1603 	PROC_LOCK(p);
1604 	if (p->p_itimers == NULL) {
1605 		p->p_itimers = its;
1606 		PROC_UNLOCK(p);
1607 	}
1608 	else {
1609 		PROC_UNLOCK(p);
1610 		free(its, M_SUBPROC);
1611 	}
1612 }
1613 
1614 static void
1615 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1616 {
1617 	itimers_event_hook_exit(arg, p);
1618 }
1619 
1620 /* Clean up timers when some process events are being triggered. */
1621 static void
1622 itimers_event_hook_exit(void *arg, struct proc *p)
1623 {
1624 	struct itimers *its;
1625 	struct itimer *it;
1626 	int event = (int)(intptr_t)arg;
1627 	int i;
1628 
1629 	if (p->p_itimers != NULL) {
1630 		its = p->p_itimers;
1631 		for (i = 0; i < MAX_CLOCKS; ++i) {
1632 			if (posix_clocks[i].event_hook != NULL)
1633 				CLOCK_CALL(i, event_hook, (p, i, event));
1634 		}
1635 		/*
1636 		 * According to susv3, XSI interval timers should be inherited
1637 		 * by new image.
1638 		 */
1639 		if (event == ITIMER_EV_EXEC)
1640 			i = 3;
1641 		else if (event == ITIMER_EV_EXIT)
1642 			i = 0;
1643 		else
1644 			panic("unhandled event");
1645 		for (; i < TIMER_MAX; ++i) {
1646 			if ((it = its->its_timers[i]) != NULL)
1647 				kern_ktimer_delete(curthread, i);
1648 		}
1649 		if (its->its_timers[0] == NULL &&
1650 		    its->its_timers[1] == NULL &&
1651 		    its->its_timers[2] == NULL) {
1652 			free(its, M_SUBPROC);
1653 			p->p_itimers = NULL;
1654 		}
1655 	}
1656 }
1657