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