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