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