xref: /freebsd/sys/kern/kern_time.c (revision 148a8da8)
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 && ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60)
416 		return (EINVAL);
417 	/* XXX Don't convert nsec->usec and back */
418 	TIMESPEC_TO_TIMEVAL(&atv, ats);
419 	error = settime(td, &atv);
420 	return (error);
421 }
422 
423 #ifndef _SYS_SYSPROTO_H_
424 struct clock_getres_args {
425 	clockid_t clock_id;
426 	struct	timespec *tp;
427 };
428 #endif
429 int
430 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
431 {
432 	struct timespec ts;
433 	int error;
434 
435 	if (uap->tp == NULL)
436 		return (0);
437 
438 	error = kern_clock_getres(td, uap->clock_id, &ts);
439 	if (error == 0)
440 		error = copyout(&ts, uap->tp, sizeof(ts));
441 	return (error);
442 }
443 
444 int
445 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
446 {
447 
448 	ts->tv_sec = 0;
449 	switch (clock_id) {
450 	case CLOCK_REALTIME:
451 	case CLOCK_REALTIME_FAST:
452 	case CLOCK_REALTIME_PRECISE:
453 	case CLOCK_MONOTONIC:
454 	case CLOCK_MONOTONIC_FAST:
455 	case CLOCK_MONOTONIC_PRECISE:
456 	case CLOCK_UPTIME:
457 	case CLOCK_UPTIME_FAST:
458 	case CLOCK_UPTIME_PRECISE:
459 		/*
460 		 * Round up the result of the division cheaply by adding 1.
461 		 * Rounding up is especially important if rounding down
462 		 * would give 0.  Perfect rounding is unimportant.
463 		 */
464 		ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
465 		break;
466 	case CLOCK_VIRTUAL:
467 	case CLOCK_PROF:
468 		/* Accurately round up here because we can do so cheaply. */
469 		ts->tv_nsec = howmany(1000000000, hz);
470 		break;
471 	case CLOCK_SECOND:
472 		ts->tv_sec = 1;
473 		ts->tv_nsec = 0;
474 		break;
475 	case CLOCK_THREAD_CPUTIME_ID:
476 	case CLOCK_PROCESS_CPUTIME_ID:
477 	cputime:
478 		/* sync with cputick2usec */
479 		ts->tv_nsec = 1000000 / cpu_tickrate();
480 		if (ts->tv_nsec == 0)
481 			ts->tv_nsec = 1000;
482 		break;
483 	default:
484 		if ((int)clock_id < 0)
485 			goto cputime;
486 		return (EINVAL);
487 	}
488 	return (0);
489 }
490 
491 int
492 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
493 {
494 
495 	return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
496 	    rmt));
497 }
498 
499 static uint8_t nanowait[MAXCPU];
500 
501 int
502 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
503     const struct timespec *rqt, struct timespec *rmt)
504 {
505 	struct timespec ts, now;
506 	sbintime_t sbt, sbtt, prec, tmp;
507 	time_t over;
508 	int error;
509 	bool is_abs_real;
510 
511 	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
512 		return (EINVAL);
513 	if ((flags & ~TIMER_ABSTIME) != 0)
514 		return (EINVAL);
515 	switch (clock_id) {
516 	case CLOCK_REALTIME:
517 	case CLOCK_REALTIME_PRECISE:
518 	case CLOCK_REALTIME_FAST:
519 	case CLOCK_SECOND:
520 		is_abs_real = (flags & TIMER_ABSTIME) != 0;
521 		break;
522 	case CLOCK_MONOTONIC:
523 	case CLOCK_MONOTONIC_PRECISE:
524 	case CLOCK_MONOTONIC_FAST:
525 	case CLOCK_UPTIME:
526 	case CLOCK_UPTIME_PRECISE:
527 	case CLOCK_UPTIME_FAST:
528 		is_abs_real = false;
529 		break;
530 	case CLOCK_VIRTUAL:
531 	case CLOCK_PROF:
532 	case CLOCK_PROCESS_CPUTIME_ID:
533 		return (ENOTSUP);
534 	case CLOCK_THREAD_CPUTIME_ID:
535 	default:
536 		return (EINVAL);
537 	}
538 	do {
539 		ts = *rqt;
540 		if ((flags & TIMER_ABSTIME) != 0) {
541 			if (is_abs_real)
542 				td->td_rtcgen =
543 				    atomic_load_acq_int(&rtc_generation);
544 			error = kern_clock_gettime(td, clock_id, &now);
545 			KASSERT(error == 0, ("kern_clock_gettime: %d", error));
546 			timespecsub(&ts, &now, &ts);
547 		}
548 		if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
549 			error = EWOULDBLOCK;
550 			break;
551 		}
552 		if (ts.tv_sec > INT32_MAX / 2) {
553 			over = ts.tv_sec - INT32_MAX / 2;
554 			ts.tv_sec -= over;
555 		} else
556 			over = 0;
557 		tmp = tstosbt(ts);
558 		prec = tmp;
559 		prec >>= tc_precexp;
560 		if (TIMESEL(&sbt, tmp))
561 			sbt += tc_tick_sbt;
562 		sbt += tmp;
563 		error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
564 		    sbt, prec, C_ABSOLUTE);
565 	} while (error == 0 && is_abs_real && td->td_rtcgen == 0);
566 	td->td_rtcgen = 0;
567 	if (error != EWOULDBLOCK) {
568 		if (TIMESEL(&sbtt, tmp))
569 			sbtt += tc_tick_sbt;
570 		if (sbtt >= sbt)
571 			return (0);
572 		if (error == ERESTART)
573 			error = EINTR;
574 		if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
575 			ts = sbttots(sbt - sbtt);
576 			ts.tv_sec += over;
577 			if (ts.tv_sec < 0)
578 				timespecclear(&ts);
579 			*rmt = ts;
580 		}
581 		return (error);
582 	}
583 	return (0);
584 }
585 
586 #ifndef _SYS_SYSPROTO_H_
587 struct nanosleep_args {
588 	struct	timespec *rqtp;
589 	struct	timespec *rmtp;
590 };
591 #endif
592 /* ARGSUSED */
593 int
594 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
595 {
596 
597 	return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
598 	    uap->rqtp, uap->rmtp));
599 }
600 
601 #ifndef _SYS_SYSPROTO_H_
602 struct clock_nanosleep_args {
603 	clockid_t clock_id;
604 	int 	  flags;
605 	struct	timespec *rqtp;
606 	struct	timespec *rmtp;
607 };
608 #endif
609 /* ARGSUSED */
610 int
611 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
612 {
613 	int error;
614 
615 	error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
616 	    uap->rmtp);
617 	return (kern_posix_error(td, error));
618 }
619 
620 static int
621 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
622     const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
623 {
624 	struct timespec rmt, rqt;
625 	int error;
626 
627 	error = copyin(ua_rqtp, &rqt, sizeof(rqt));
628 	if (error)
629 		return (error);
630 	if (ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0 &&
631 	    !useracc(ua_rmtp, sizeof(rmt), VM_PROT_WRITE))
632 		return (EFAULT);
633 	error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
634 	if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
635 		int error2;
636 
637 		error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
638 		if (error2)
639 			error = error2;
640 	}
641 	return (error);
642 }
643 
644 #ifndef _SYS_SYSPROTO_H_
645 struct gettimeofday_args {
646 	struct	timeval *tp;
647 	struct	timezone *tzp;
648 };
649 #endif
650 /* ARGSUSED */
651 int
652 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
653 {
654 	struct timeval atv;
655 	struct timezone rtz;
656 	int error = 0;
657 
658 	if (uap->tp) {
659 		microtime(&atv);
660 		error = copyout(&atv, uap->tp, sizeof (atv));
661 	}
662 	if (error == 0 && uap->tzp != NULL) {
663 		rtz.tz_minuteswest = 0;
664 		rtz.tz_dsttime = 0;
665 		error = copyout(&rtz, uap->tzp, sizeof (rtz));
666 	}
667 	return (error);
668 }
669 
670 #ifndef _SYS_SYSPROTO_H_
671 struct settimeofday_args {
672 	struct	timeval *tv;
673 	struct	timezone *tzp;
674 };
675 #endif
676 /* ARGSUSED */
677 int
678 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
679 {
680 	struct timeval atv, *tvp;
681 	struct timezone atz, *tzp;
682 	int error;
683 
684 	if (uap->tv) {
685 		error = copyin(uap->tv, &atv, sizeof(atv));
686 		if (error)
687 			return (error);
688 		tvp = &atv;
689 	} else
690 		tvp = NULL;
691 	if (uap->tzp) {
692 		error = copyin(uap->tzp, &atz, sizeof(atz));
693 		if (error)
694 			return (error);
695 		tzp = &atz;
696 	} else
697 		tzp = NULL;
698 	return (kern_settimeofday(td, tvp, tzp));
699 }
700 
701 int
702 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
703 {
704 	int error;
705 
706 	error = priv_check(td, PRIV_SETTIMEOFDAY);
707 	if (error)
708 		return (error);
709 	/* Verify all parameters before changing time. */
710 	if (tv) {
711 		if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
712 		    tv->tv_sec < 0)
713 			return (EINVAL);
714 		error = settime(td, tv);
715 	}
716 	return (error);
717 }
718 
719 /*
720  * Get value of an interval timer.  The process virtual and profiling virtual
721  * time timers are kept in the p_stats area, since they can be swapped out.
722  * These are kept internally in the way they are specified externally: in
723  * time until they expire.
724  *
725  * The real time interval timer is kept in the process table slot for the
726  * process, and its value (it_value) is kept as an absolute time rather than
727  * as a delta, so that it is easy to keep periodic real-time signals from
728  * drifting.
729  *
730  * Virtual time timers are processed in the hardclock() routine of
731  * kern_clock.c.  The real time timer is processed by a timeout routine,
732  * called from the softclock() routine.  Since a callout may be delayed in
733  * real time due to interrupt processing in the system, it is possible for
734  * the real time timeout routine (realitexpire, given below), to be delayed
735  * in real time past when it is supposed to occur.  It does not suffice,
736  * therefore, to reload the real timer .it_value from the real time timers
737  * .it_interval.  Rather, we compute the next time in absolute time the timer
738  * should go off.
739  */
740 #ifndef _SYS_SYSPROTO_H_
741 struct getitimer_args {
742 	u_int	which;
743 	struct	itimerval *itv;
744 };
745 #endif
746 int
747 sys_getitimer(struct thread *td, struct getitimer_args *uap)
748 {
749 	struct itimerval aitv;
750 	int error;
751 
752 	error = kern_getitimer(td, uap->which, &aitv);
753 	if (error != 0)
754 		return (error);
755 	return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
756 }
757 
758 int
759 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
760 {
761 	struct proc *p = td->td_proc;
762 	struct timeval ctv;
763 
764 	if (which > ITIMER_PROF)
765 		return (EINVAL);
766 
767 	if (which == ITIMER_REAL) {
768 		/*
769 		 * Convert from absolute to relative time in .it_value
770 		 * part of real time timer.  If time for real time timer
771 		 * has passed return 0, else return difference between
772 		 * current time and time for the timer to go off.
773 		 */
774 		PROC_LOCK(p);
775 		*aitv = p->p_realtimer;
776 		PROC_UNLOCK(p);
777 		if (timevalisset(&aitv->it_value)) {
778 			microuptime(&ctv);
779 			if (timevalcmp(&aitv->it_value, &ctv, <))
780 				timevalclear(&aitv->it_value);
781 			else
782 				timevalsub(&aitv->it_value, &ctv);
783 		}
784 	} else {
785 		PROC_ITIMLOCK(p);
786 		*aitv = p->p_stats->p_timer[which];
787 		PROC_ITIMUNLOCK(p);
788 	}
789 #ifdef KTRACE
790 	if (KTRPOINT(td, KTR_STRUCT))
791 		ktritimerval(aitv);
792 #endif
793 	return (0);
794 }
795 
796 #ifndef _SYS_SYSPROTO_H_
797 struct setitimer_args {
798 	u_int	which;
799 	struct	itimerval *itv, *oitv;
800 };
801 #endif
802 int
803 sys_setitimer(struct thread *td, struct setitimer_args *uap)
804 {
805 	struct itimerval aitv, oitv;
806 	int error;
807 
808 	if (uap->itv == NULL) {
809 		uap->itv = uap->oitv;
810 		return (sys_getitimer(td, (struct getitimer_args *)uap));
811 	}
812 
813 	if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
814 		return (error);
815 	error = kern_setitimer(td, uap->which, &aitv, &oitv);
816 	if (error != 0 || uap->oitv == NULL)
817 		return (error);
818 	return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
819 }
820 
821 int
822 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
823     struct itimerval *oitv)
824 {
825 	struct proc *p = td->td_proc;
826 	struct timeval ctv;
827 	sbintime_t sbt, pr;
828 
829 	if (aitv == NULL)
830 		return (kern_getitimer(td, which, oitv));
831 
832 	if (which > ITIMER_PROF)
833 		return (EINVAL);
834 #ifdef KTRACE
835 	if (KTRPOINT(td, KTR_STRUCT))
836 		ktritimerval(aitv);
837 #endif
838 	if (itimerfix(&aitv->it_value) ||
839 	    aitv->it_value.tv_sec > INT32_MAX / 2)
840 		return (EINVAL);
841 	if (!timevalisset(&aitv->it_value))
842 		timevalclear(&aitv->it_interval);
843 	else if (itimerfix(&aitv->it_interval) ||
844 	    aitv->it_interval.tv_sec > INT32_MAX / 2)
845 		return (EINVAL);
846 
847 	if (which == ITIMER_REAL) {
848 		PROC_LOCK(p);
849 		if (timevalisset(&p->p_realtimer.it_value))
850 			callout_stop(&p->p_itcallout);
851 		microuptime(&ctv);
852 		if (timevalisset(&aitv->it_value)) {
853 			pr = tvtosbt(aitv->it_value) >> tc_precexp;
854 			timevaladd(&aitv->it_value, &ctv);
855 			sbt = tvtosbt(aitv->it_value);
856 			callout_reset_sbt(&p->p_itcallout, sbt, pr,
857 			    realitexpire, p, C_ABSOLUTE);
858 		}
859 		*oitv = p->p_realtimer;
860 		p->p_realtimer = *aitv;
861 		PROC_UNLOCK(p);
862 		if (timevalisset(&oitv->it_value)) {
863 			if (timevalcmp(&oitv->it_value, &ctv, <))
864 				timevalclear(&oitv->it_value);
865 			else
866 				timevalsub(&oitv->it_value, &ctv);
867 		}
868 	} else {
869 		if (aitv->it_interval.tv_sec == 0 &&
870 		    aitv->it_interval.tv_usec != 0 &&
871 		    aitv->it_interval.tv_usec < tick)
872 			aitv->it_interval.tv_usec = tick;
873 		if (aitv->it_value.tv_sec == 0 &&
874 		    aitv->it_value.tv_usec != 0 &&
875 		    aitv->it_value.tv_usec < tick)
876 			aitv->it_value.tv_usec = tick;
877 		PROC_ITIMLOCK(p);
878 		*oitv = p->p_stats->p_timer[which];
879 		p->p_stats->p_timer[which] = *aitv;
880 		PROC_ITIMUNLOCK(p);
881 	}
882 #ifdef KTRACE
883 	if (KTRPOINT(td, KTR_STRUCT))
884 		ktritimerval(oitv);
885 #endif
886 	return (0);
887 }
888 
889 /*
890  * Real interval timer expired:
891  * send process whose timer expired an alarm signal.
892  * If time is not set up to reload, then just return.
893  * Else compute next time timer should go off which is > current time.
894  * This is where delay in processing this timeout causes multiple
895  * SIGALRM calls to be compressed into one.
896  * tvtohz() always adds 1 to allow for the time until the next clock
897  * interrupt being strictly less than 1 clock tick, but we don't want
898  * that here since we want to appear to be in sync with the clock
899  * interrupt even when we're delayed.
900  */
901 void
902 realitexpire(void *arg)
903 {
904 	struct proc *p;
905 	struct timeval ctv;
906 	sbintime_t isbt;
907 
908 	p = (struct proc *)arg;
909 	kern_psignal(p, SIGALRM);
910 	if (!timevalisset(&p->p_realtimer.it_interval)) {
911 		timevalclear(&p->p_realtimer.it_value);
912 		if (p->p_flag & P_WEXIT)
913 			wakeup(&p->p_itcallout);
914 		return;
915 	}
916 	isbt = tvtosbt(p->p_realtimer.it_interval);
917 	if (isbt >= sbt_timethreshold)
918 		getmicrouptime(&ctv);
919 	else
920 		microuptime(&ctv);
921 	do {
922 		timevaladd(&p->p_realtimer.it_value,
923 		    &p->p_realtimer.it_interval);
924 	} while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
925 	callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
926 	    isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
927 }
928 
929 /*
930  * Check that a proposed value to load into the .it_value or
931  * .it_interval part of an interval timer is acceptable, and
932  * fix it to have at least minimal value (i.e. if it is less
933  * than the resolution of the clock, round it up.)
934  */
935 int
936 itimerfix(struct timeval *tv)
937 {
938 
939 	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
940 		return (EINVAL);
941 	if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
942 	    tv->tv_usec < (u_int)tick / 16)
943 		tv->tv_usec = (u_int)tick / 16;
944 	return (0);
945 }
946 
947 /*
948  * Decrement an interval timer by a specified number
949  * of microseconds, which must be less than a second,
950  * i.e. < 1000000.  If the timer expires, then reload
951  * it.  In this case, carry over (usec - old value) to
952  * reduce the value reloaded into the timer so that
953  * the timer does not drift.  This routine assumes
954  * that it is called in a context where the timers
955  * on which it is operating cannot change in value.
956  */
957 int
958 itimerdecr(struct itimerval *itp, int usec)
959 {
960 
961 	if (itp->it_value.tv_usec < usec) {
962 		if (itp->it_value.tv_sec == 0) {
963 			/* expired, and already in next interval */
964 			usec -= itp->it_value.tv_usec;
965 			goto expire;
966 		}
967 		itp->it_value.tv_usec += 1000000;
968 		itp->it_value.tv_sec--;
969 	}
970 	itp->it_value.tv_usec -= usec;
971 	usec = 0;
972 	if (timevalisset(&itp->it_value))
973 		return (1);
974 	/* expired, exactly at end of interval */
975 expire:
976 	if (timevalisset(&itp->it_interval)) {
977 		itp->it_value = itp->it_interval;
978 		itp->it_value.tv_usec -= usec;
979 		if (itp->it_value.tv_usec < 0) {
980 			itp->it_value.tv_usec += 1000000;
981 			itp->it_value.tv_sec--;
982 		}
983 	} else
984 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
985 	return (0);
986 }
987 
988 /*
989  * Add and subtract routines for timevals.
990  * N.B.: subtract routine doesn't deal with
991  * results which are before the beginning,
992  * it just gets very confused in this case.
993  * Caveat emptor.
994  */
995 void
996 timevaladd(struct timeval *t1, const struct timeval *t2)
997 {
998 
999 	t1->tv_sec += t2->tv_sec;
1000 	t1->tv_usec += t2->tv_usec;
1001 	timevalfix(t1);
1002 }
1003 
1004 void
1005 timevalsub(struct timeval *t1, const struct timeval *t2)
1006 {
1007 
1008 	t1->tv_sec -= t2->tv_sec;
1009 	t1->tv_usec -= t2->tv_usec;
1010 	timevalfix(t1);
1011 }
1012 
1013 static void
1014 timevalfix(struct timeval *t1)
1015 {
1016 
1017 	if (t1->tv_usec < 0) {
1018 		t1->tv_sec--;
1019 		t1->tv_usec += 1000000;
1020 	}
1021 	if (t1->tv_usec >= 1000000) {
1022 		t1->tv_sec++;
1023 		t1->tv_usec -= 1000000;
1024 	}
1025 }
1026 
1027 /*
1028  * ratecheck(): simple time-based rate-limit checking.
1029  */
1030 int
1031 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1032 {
1033 	struct timeval tv, delta;
1034 	int rv = 0;
1035 
1036 	getmicrouptime(&tv);		/* NB: 10ms precision */
1037 	delta = tv;
1038 	timevalsub(&delta, lasttime);
1039 
1040 	/*
1041 	 * check for 0,0 is so that the message will be seen at least once,
1042 	 * even if interval is huge.
1043 	 */
1044 	if (timevalcmp(&delta, mininterval, >=) ||
1045 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1046 		*lasttime = tv;
1047 		rv = 1;
1048 	}
1049 
1050 	return (rv);
1051 }
1052 
1053 /*
1054  * ppsratecheck(): packets (or events) per second limitation.
1055  *
1056  * Return 0 if the limit is to be enforced (e.g. the caller
1057  * should drop a packet because of the rate limitation).
1058  *
1059  * maxpps of 0 always causes zero to be returned.  maxpps of -1
1060  * always causes 1 to be returned; this effectively defeats rate
1061  * limiting.
1062  *
1063  * Note that we maintain the struct timeval for compatibility
1064  * with other bsd systems.  We reuse the storage and just monitor
1065  * clock ticks for minimal overhead.
1066  */
1067 int
1068 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1069 {
1070 	int now;
1071 
1072 	/*
1073 	 * Reset the last time and counter if this is the first call
1074 	 * or more than a second has passed since the last update of
1075 	 * lasttime.
1076 	 */
1077 	now = ticks;
1078 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1079 		lasttime->tv_sec = now;
1080 		*curpps = 1;
1081 		return (maxpps != 0);
1082 	} else {
1083 		(*curpps)++;		/* NB: ignore potential overflow */
1084 		return (maxpps < 0 || *curpps <= maxpps);
1085 	}
1086 }
1087 
1088 static void
1089 itimer_start(void)
1090 {
1091 	struct kclock rt_clock = {
1092 		.timer_create  = realtimer_create,
1093 		.timer_delete  = realtimer_delete,
1094 		.timer_settime = realtimer_settime,
1095 		.timer_gettime = realtimer_gettime,
1096 		.event_hook    = NULL
1097 	};
1098 
1099 	itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1100 		NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1101 	register_posix_clock(CLOCK_REALTIME,  &rt_clock);
1102 	register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1103 	p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1104 	p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1105 	p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1106 	EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1107 		(void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1108 	EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1109 		(void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
1110 }
1111 
1112 int
1113 register_posix_clock(int clockid, struct kclock *clk)
1114 {
1115 	if ((unsigned)clockid >= MAX_CLOCKS) {
1116 		printf("%s: invalid clockid\n", __func__);
1117 		return (0);
1118 	}
1119 	posix_clocks[clockid] = *clk;
1120 	return (1);
1121 }
1122 
1123 static int
1124 itimer_init(void *mem, int size, int flags)
1125 {
1126 	struct itimer *it;
1127 
1128 	it = (struct itimer *)mem;
1129 	mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1130 	return (0);
1131 }
1132 
1133 static void
1134 itimer_fini(void *mem, int size)
1135 {
1136 	struct itimer *it;
1137 
1138 	it = (struct itimer *)mem;
1139 	mtx_destroy(&it->it_mtx);
1140 }
1141 
1142 static void
1143 itimer_enter(struct itimer *it)
1144 {
1145 
1146 	mtx_assert(&it->it_mtx, MA_OWNED);
1147 	it->it_usecount++;
1148 }
1149 
1150 static void
1151 itimer_leave(struct itimer *it)
1152 {
1153 
1154 	mtx_assert(&it->it_mtx, MA_OWNED);
1155 	KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1156 
1157 	if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1158 		wakeup(it);
1159 }
1160 
1161 #ifndef _SYS_SYSPROTO_H_
1162 struct ktimer_create_args {
1163 	clockid_t clock_id;
1164 	struct sigevent * evp;
1165 	int * timerid;
1166 };
1167 #endif
1168 int
1169 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1170 {
1171 	struct sigevent *evp, ev;
1172 	int id;
1173 	int error;
1174 
1175 	if (uap->evp == NULL) {
1176 		evp = NULL;
1177 	} else {
1178 		error = copyin(uap->evp, &ev, sizeof(ev));
1179 		if (error != 0)
1180 			return (error);
1181 		evp = &ev;
1182 	}
1183 	error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1184 	if (error == 0) {
1185 		error = copyout(&id, uap->timerid, sizeof(int));
1186 		if (error != 0)
1187 			kern_ktimer_delete(td, id);
1188 	}
1189 	return (error);
1190 }
1191 
1192 int
1193 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1194     int *timerid, int preset_id)
1195 {
1196 	struct proc *p = td->td_proc;
1197 	struct itimer *it;
1198 	int id;
1199 	int error;
1200 
1201 	if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1202 		return (EINVAL);
1203 
1204 	if (posix_clocks[clock_id].timer_create == NULL)
1205 		return (EINVAL);
1206 
1207 	if (evp != NULL) {
1208 		if (evp->sigev_notify != SIGEV_NONE &&
1209 		    evp->sigev_notify != SIGEV_SIGNAL &&
1210 		    evp->sigev_notify != SIGEV_THREAD_ID)
1211 			return (EINVAL);
1212 		if ((evp->sigev_notify == SIGEV_SIGNAL ||
1213 		     evp->sigev_notify == SIGEV_THREAD_ID) &&
1214 			!_SIG_VALID(evp->sigev_signo))
1215 			return (EINVAL);
1216 	}
1217 
1218 	if (p->p_itimers == NULL)
1219 		itimers_alloc(p);
1220 
1221 	it = uma_zalloc(itimer_zone, M_WAITOK);
1222 	it->it_flags = 0;
1223 	it->it_usecount = 0;
1224 	it->it_active = 0;
1225 	timespecclear(&it->it_time.it_value);
1226 	timespecclear(&it->it_time.it_interval);
1227 	it->it_overrun = 0;
1228 	it->it_overrun_last = 0;
1229 	it->it_clockid = clock_id;
1230 	it->it_timerid = -1;
1231 	it->it_proc = p;
1232 	ksiginfo_init(&it->it_ksi);
1233 	it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1234 	error = CLOCK_CALL(clock_id, timer_create, (it));
1235 	if (error != 0)
1236 		goto out;
1237 
1238 	PROC_LOCK(p);
1239 	if (preset_id != -1) {
1240 		KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1241 		id = preset_id;
1242 		if (p->p_itimers->its_timers[id] != NULL) {
1243 			PROC_UNLOCK(p);
1244 			error = 0;
1245 			goto out;
1246 		}
1247 	} else {
1248 		/*
1249 		 * Find a free timer slot, skipping those reserved
1250 		 * for setitimer().
1251 		 */
1252 		for (id = 3; id < TIMER_MAX; id++)
1253 			if (p->p_itimers->its_timers[id] == NULL)
1254 				break;
1255 		if (id == TIMER_MAX) {
1256 			PROC_UNLOCK(p);
1257 			error = EAGAIN;
1258 			goto out;
1259 		}
1260 	}
1261 	it->it_timerid = id;
1262 	p->p_itimers->its_timers[id] = it;
1263 	if (evp != NULL)
1264 		it->it_sigev = *evp;
1265 	else {
1266 		it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1267 		switch (clock_id) {
1268 		default:
1269 		case CLOCK_REALTIME:
1270 			it->it_sigev.sigev_signo = SIGALRM;
1271 			break;
1272 		case CLOCK_VIRTUAL:
1273  			it->it_sigev.sigev_signo = SIGVTALRM;
1274 			break;
1275 		case CLOCK_PROF:
1276 			it->it_sigev.sigev_signo = SIGPROF;
1277 			break;
1278 		}
1279 		it->it_sigev.sigev_value.sival_int = id;
1280 	}
1281 
1282 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1283 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1284 		it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1285 		it->it_ksi.ksi_code = SI_TIMER;
1286 		it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1287 		it->it_ksi.ksi_timerid = id;
1288 	}
1289 	PROC_UNLOCK(p);
1290 	*timerid = id;
1291 	return (0);
1292 
1293 out:
1294 	ITIMER_LOCK(it);
1295 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1296 	ITIMER_UNLOCK(it);
1297 	uma_zfree(itimer_zone, it);
1298 	return (error);
1299 }
1300 
1301 #ifndef _SYS_SYSPROTO_H_
1302 struct ktimer_delete_args {
1303 	int timerid;
1304 };
1305 #endif
1306 int
1307 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1308 {
1309 
1310 	return (kern_ktimer_delete(td, uap->timerid));
1311 }
1312 
1313 static struct itimer *
1314 itimer_find(struct proc *p, int timerid)
1315 {
1316 	struct itimer *it;
1317 
1318 	PROC_LOCK_ASSERT(p, MA_OWNED);
1319 	if ((p->p_itimers == NULL) ||
1320 	    (timerid < 0) || (timerid >= TIMER_MAX) ||
1321 	    (it = p->p_itimers->its_timers[timerid]) == NULL) {
1322 		return (NULL);
1323 	}
1324 	ITIMER_LOCK(it);
1325 	if ((it->it_flags & ITF_DELETING) != 0) {
1326 		ITIMER_UNLOCK(it);
1327 		it = NULL;
1328 	}
1329 	return (it);
1330 }
1331 
1332 int
1333 kern_ktimer_delete(struct thread *td, int timerid)
1334 {
1335 	struct proc *p = td->td_proc;
1336 	struct itimer *it;
1337 
1338 	PROC_LOCK(p);
1339 	it = itimer_find(p, timerid);
1340 	if (it == NULL) {
1341 		PROC_UNLOCK(p);
1342 		return (EINVAL);
1343 	}
1344 	PROC_UNLOCK(p);
1345 
1346 	it->it_flags |= ITF_DELETING;
1347 	while (it->it_usecount > 0) {
1348 		it->it_flags |= ITF_WANTED;
1349 		msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1350 	}
1351 	it->it_flags &= ~ITF_WANTED;
1352 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1353 	ITIMER_UNLOCK(it);
1354 
1355 	PROC_LOCK(p);
1356 	if (KSI_ONQ(&it->it_ksi))
1357 		sigqueue_take(&it->it_ksi);
1358 	p->p_itimers->its_timers[timerid] = NULL;
1359 	PROC_UNLOCK(p);
1360 	uma_zfree(itimer_zone, it);
1361 	return (0);
1362 }
1363 
1364 #ifndef _SYS_SYSPROTO_H_
1365 struct ktimer_settime_args {
1366 	int timerid;
1367 	int flags;
1368 	const struct itimerspec * value;
1369 	struct itimerspec * ovalue;
1370 };
1371 #endif
1372 int
1373 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1374 {
1375 	struct itimerspec val, oval, *ovalp;
1376 	int error;
1377 
1378 	error = copyin(uap->value, &val, sizeof(val));
1379 	if (error != 0)
1380 		return (error);
1381 	ovalp = uap->ovalue != NULL ? &oval : NULL;
1382 	error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1383 	if (error == 0 && uap->ovalue != NULL)
1384 		error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1385 	return (error);
1386 }
1387 
1388 int
1389 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1390     struct itimerspec *val, struct itimerspec *oval)
1391 {
1392 	struct proc *p;
1393 	struct itimer *it;
1394 	int error;
1395 
1396 	p = td->td_proc;
1397 	PROC_LOCK(p);
1398 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1399 		PROC_UNLOCK(p);
1400 		error = EINVAL;
1401 	} else {
1402 		PROC_UNLOCK(p);
1403 		itimer_enter(it);
1404 		error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1405 		    flags, val, oval));
1406 		itimer_leave(it);
1407 		ITIMER_UNLOCK(it);
1408 	}
1409 	return (error);
1410 }
1411 
1412 #ifndef _SYS_SYSPROTO_H_
1413 struct ktimer_gettime_args {
1414 	int timerid;
1415 	struct itimerspec * value;
1416 };
1417 #endif
1418 int
1419 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1420 {
1421 	struct itimerspec val;
1422 	int error;
1423 
1424 	error = kern_ktimer_gettime(td, uap->timerid, &val);
1425 	if (error == 0)
1426 		error = copyout(&val, uap->value, sizeof(val));
1427 	return (error);
1428 }
1429 
1430 int
1431 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1432 {
1433 	struct proc *p;
1434 	struct itimer *it;
1435 	int error;
1436 
1437 	p = td->td_proc;
1438 	PROC_LOCK(p);
1439 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1440 		PROC_UNLOCK(p);
1441 		error = EINVAL;
1442 	} else {
1443 		PROC_UNLOCK(p);
1444 		itimer_enter(it);
1445 		error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1446 		itimer_leave(it);
1447 		ITIMER_UNLOCK(it);
1448 	}
1449 	return (error);
1450 }
1451 
1452 #ifndef _SYS_SYSPROTO_H_
1453 struct timer_getoverrun_args {
1454 	int timerid;
1455 };
1456 #endif
1457 int
1458 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1459 {
1460 
1461 	return (kern_ktimer_getoverrun(td, uap->timerid));
1462 }
1463 
1464 int
1465 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1466 {
1467 	struct proc *p = td->td_proc;
1468 	struct itimer *it;
1469 	int error ;
1470 
1471 	PROC_LOCK(p);
1472 	if (timer_id < 3 ||
1473 	    (it = itimer_find(p, timer_id)) == NULL) {
1474 		PROC_UNLOCK(p);
1475 		error = EINVAL;
1476 	} else {
1477 		td->td_retval[0] = it->it_overrun_last;
1478 		ITIMER_UNLOCK(it);
1479 		PROC_UNLOCK(p);
1480 		error = 0;
1481 	}
1482 	return (error);
1483 }
1484 
1485 static int
1486 realtimer_create(struct itimer *it)
1487 {
1488 	callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1489 	return (0);
1490 }
1491 
1492 static int
1493 realtimer_delete(struct itimer *it)
1494 {
1495 	mtx_assert(&it->it_mtx, MA_OWNED);
1496 
1497 	/*
1498 	 * clear timer's value and interval to tell realtimer_expire
1499 	 * to not rearm the timer.
1500 	 */
1501 	timespecclear(&it->it_time.it_value);
1502 	timespecclear(&it->it_time.it_interval);
1503 	ITIMER_UNLOCK(it);
1504 	callout_drain(&it->it_callout);
1505 	ITIMER_LOCK(it);
1506 	return (0);
1507 }
1508 
1509 static int
1510 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1511 {
1512 	struct timespec cts;
1513 
1514 	mtx_assert(&it->it_mtx, MA_OWNED);
1515 
1516 	realtimer_clocktime(it->it_clockid, &cts);
1517 	*ovalue = it->it_time;
1518 	if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1519 		timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1520 		if (ovalue->it_value.tv_sec < 0 ||
1521 		    (ovalue->it_value.tv_sec == 0 &&
1522 		     ovalue->it_value.tv_nsec == 0)) {
1523 			ovalue->it_value.tv_sec  = 0;
1524 			ovalue->it_value.tv_nsec = 1;
1525 		}
1526 	}
1527 	return (0);
1528 }
1529 
1530 static int
1531 realtimer_settime(struct itimer *it, int flags,
1532 	struct itimerspec *value, struct itimerspec *ovalue)
1533 {
1534 	struct timespec cts, ts;
1535 	struct timeval tv;
1536 	struct itimerspec val;
1537 
1538 	mtx_assert(&it->it_mtx, MA_OWNED);
1539 
1540 	val = *value;
1541 	if (itimespecfix(&val.it_value))
1542 		return (EINVAL);
1543 
1544 	if (timespecisset(&val.it_value)) {
1545 		if (itimespecfix(&val.it_interval))
1546 			return (EINVAL);
1547 	} else {
1548 		timespecclear(&val.it_interval);
1549 	}
1550 
1551 	if (ovalue != NULL)
1552 		realtimer_gettime(it, ovalue);
1553 
1554 	it->it_time = val;
1555 	if (timespecisset(&val.it_value)) {
1556 		realtimer_clocktime(it->it_clockid, &cts);
1557 		ts = val.it_value;
1558 		if ((flags & TIMER_ABSTIME) == 0) {
1559 			/* Convert to absolute time. */
1560 			timespecadd(&it->it_time.it_value, &cts,
1561 				&it->it_time.it_value);
1562 		} else {
1563 			timespecsub(&ts, &cts, &ts);
1564 			/*
1565 			 * We don't care if ts is negative, tztohz will
1566 			 * fix it.
1567 			 */
1568 		}
1569 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1570 		callout_reset(&it->it_callout, tvtohz(&tv),
1571 			realtimer_expire, it);
1572 	} else {
1573 		callout_stop(&it->it_callout);
1574 	}
1575 
1576 	return (0);
1577 }
1578 
1579 static void
1580 realtimer_clocktime(clockid_t id, struct timespec *ts)
1581 {
1582 	if (id == CLOCK_REALTIME)
1583 		getnanotime(ts);
1584 	else	/* CLOCK_MONOTONIC */
1585 		getnanouptime(ts);
1586 }
1587 
1588 int
1589 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1590 {
1591 	struct itimer *it;
1592 
1593 	PROC_LOCK_ASSERT(p, MA_OWNED);
1594 	it = itimer_find(p, timerid);
1595 	if (it != NULL) {
1596 		ksi->ksi_overrun = it->it_overrun;
1597 		it->it_overrun_last = it->it_overrun;
1598 		it->it_overrun = 0;
1599 		ITIMER_UNLOCK(it);
1600 		return (0);
1601 	}
1602 	return (EINVAL);
1603 }
1604 
1605 int
1606 itimespecfix(struct timespec *ts)
1607 {
1608 
1609 	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1610 		return (EINVAL);
1611 	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1612 		ts->tv_nsec = tick * 1000;
1613 	return (0);
1614 }
1615 
1616 /* Timeout callback for realtime timer */
1617 static void
1618 realtimer_expire(void *arg)
1619 {
1620 	struct timespec cts, ts;
1621 	struct timeval tv;
1622 	struct itimer *it;
1623 
1624 	it = (struct itimer *)arg;
1625 
1626 	realtimer_clocktime(it->it_clockid, &cts);
1627 	/* Only fire if time is reached. */
1628 	if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1629 		if (timespecisset(&it->it_time.it_interval)) {
1630 			timespecadd(&it->it_time.it_value,
1631 				    &it->it_time.it_interval,
1632 				    &it->it_time.it_value);
1633 			while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1634 				if (it->it_overrun < INT_MAX)
1635 					it->it_overrun++;
1636 				else
1637 					it->it_ksi.ksi_errno = ERANGE;
1638 				timespecadd(&it->it_time.it_value,
1639 					    &it->it_time.it_interval,
1640 					    &it->it_time.it_value);
1641 			}
1642 		} else {
1643 			/* single shot timer ? */
1644 			timespecclear(&it->it_time.it_value);
1645 		}
1646 		if (timespecisset(&it->it_time.it_value)) {
1647 			timespecsub(&it->it_time.it_value, &cts, &ts);
1648 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1649 			callout_reset(&it->it_callout, tvtohz(&tv),
1650 				 realtimer_expire, it);
1651 		}
1652 		itimer_enter(it);
1653 		ITIMER_UNLOCK(it);
1654 		itimer_fire(it);
1655 		ITIMER_LOCK(it);
1656 		itimer_leave(it);
1657 	} else if (timespecisset(&it->it_time.it_value)) {
1658 		ts = it->it_time.it_value;
1659 		timespecsub(&ts, &cts, &ts);
1660 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1661 		callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1662  			it);
1663 	}
1664 }
1665 
1666 void
1667 itimer_fire(struct itimer *it)
1668 {
1669 	struct proc *p = it->it_proc;
1670 	struct thread *td;
1671 
1672 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1673 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1674 		if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1675 			ITIMER_LOCK(it);
1676 			timespecclear(&it->it_time.it_value);
1677 			timespecclear(&it->it_time.it_interval);
1678 			callout_stop(&it->it_callout);
1679 			ITIMER_UNLOCK(it);
1680 			return;
1681 		}
1682 		if (!KSI_ONQ(&it->it_ksi)) {
1683 			it->it_ksi.ksi_errno = 0;
1684 			ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1685 			tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1686 		} else {
1687 			if (it->it_overrun < INT_MAX)
1688 				it->it_overrun++;
1689 			else
1690 				it->it_ksi.ksi_errno = ERANGE;
1691 		}
1692 		PROC_UNLOCK(p);
1693 	}
1694 }
1695 
1696 static void
1697 itimers_alloc(struct proc *p)
1698 {
1699 	struct itimers *its;
1700 	int i;
1701 
1702 	its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1703 	LIST_INIT(&its->its_virtual);
1704 	LIST_INIT(&its->its_prof);
1705 	TAILQ_INIT(&its->its_worklist);
1706 	for (i = 0; i < TIMER_MAX; i++)
1707 		its->its_timers[i] = NULL;
1708 	PROC_LOCK(p);
1709 	if (p->p_itimers == NULL) {
1710 		p->p_itimers = its;
1711 		PROC_UNLOCK(p);
1712 	}
1713 	else {
1714 		PROC_UNLOCK(p);
1715 		free(its, M_SUBPROC);
1716 	}
1717 }
1718 
1719 static void
1720 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1721 {
1722 	itimers_event_hook_exit(arg, p);
1723 }
1724 
1725 /* Clean up timers when some process events are being triggered. */
1726 static void
1727 itimers_event_hook_exit(void *arg, struct proc *p)
1728 {
1729 	struct itimers *its;
1730 	struct itimer *it;
1731 	int event = (int)(intptr_t)arg;
1732 	int i;
1733 
1734 	if (p->p_itimers != NULL) {
1735 		its = p->p_itimers;
1736 		for (i = 0; i < MAX_CLOCKS; ++i) {
1737 			if (posix_clocks[i].event_hook != NULL)
1738 				CLOCK_CALL(i, event_hook, (p, i, event));
1739 		}
1740 		/*
1741 		 * According to susv3, XSI interval timers should be inherited
1742 		 * by new image.
1743 		 */
1744 		if (event == ITIMER_EV_EXEC)
1745 			i = 3;
1746 		else if (event == ITIMER_EV_EXIT)
1747 			i = 0;
1748 		else
1749 			panic("unhandled event");
1750 		for (; i < TIMER_MAX; ++i) {
1751 			if ((it = its->its_timers[i]) != NULL)
1752 				kern_ktimer_delete(curthread, i);
1753 		}
1754 		if (its->its_timers[0] == NULL &&
1755 		    its->its_timers[1] == NULL &&
1756 		    its->its_timers[2] == NULL) {
1757 			free(its, M_SUBPROC);
1758 			p->p_itimers = NULL;
1759 		}
1760 	}
1761 }
1762