xref: /freebsd/sys/kern/kern_time.c (revision 8a4217aacf57330755501a349d0ea662d4880386)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)kern_time.c	8.1 (Berkeley) 6/10/93
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_ktrace.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/limits.h>
42 #include <sys/clock.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/sysproto.h>
46 #include <sys/eventhandler.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/kernel.h>
50 #include <sys/sleepqueue.h>
51 #include <sys/syscallsubr.h>
52 #include <sys/sysctl.h>
53 #include <sys/sysent.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/posix4.h>
57 #include <sys/time.h>
58 #include <sys/timers.h>
59 #include <sys/timetc.h>
60 #include <sys/vnode.h>
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64 
65 #include <vm/vm.h>
66 #include <vm/vm_extern.h>
67 
68 #define MAX_CLOCKS 	(CLOCK_MONOTONIC+1)
69 #define CPUCLOCK_BIT		0x80000000
70 #define CPUCLOCK_PROCESS_BIT	0x40000000
71 #define CPUCLOCK_ID_MASK	(~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
72 #define MAKE_THREAD_CPUCLOCK(tid)	(CPUCLOCK_BIT|(tid))
73 #define MAKE_PROCESS_CPUCLOCK(pid)	\
74 	(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
75 
76 static struct kclock	posix_clocks[MAX_CLOCKS];
77 static uma_zone_t	itimer_zone = NULL;
78 
79 /*
80  * Time of day and interval timer support.
81  *
82  * These routines provide the kernel entry points to get and set
83  * the time-of-day and per-process interval timers.  Subroutines
84  * here provide support for adding and subtracting timeval structures
85  * and decrementing interval timers, optionally reloading the interval
86  * timers when they expire.
87  */
88 
89 static int	settime(struct thread *, struct timeval *);
90 static void	timevalfix(struct timeval *);
91 static int	user_clock_nanosleep(struct thread *td, clockid_t clock_id,
92 		    int flags, const struct timespec *ua_rqtp,
93 		    struct timespec *ua_rmtp);
94 
95 static void	itimer_start(void);
96 static int	itimer_init(void *, int, int);
97 static void	itimer_fini(void *, int);
98 static void	itimer_enter(struct itimer *);
99 static void	itimer_leave(struct itimer *);
100 static struct itimer *itimer_find(struct proc *, int);
101 static void	itimers_alloc(struct proc *);
102 static void	itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
103 static void	itimers_event_hook_exit(void *arg, struct proc *p);
104 static int	realtimer_create(struct itimer *);
105 static int	realtimer_gettime(struct itimer *, struct itimerspec *);
106 static int	realtimer_settime(struct itimer *, int,
107 			struct itimerspec *, struct itimerspec *);
108 static int	realtimer_delete(struct itimer *);
109 static void	realtimer_clocktime(clockid_t, struct timespec *);
110 static void	realtimer_expire(void *);
111 
112 int		register_posix_clock(int, struct kclock *);
113 void		itimer_fire(struct itimer *it);
114 int		itimespecfix(struct timespec *ts);
115 
116 #define CLOCK_CALL(clock, call, arglist)		\
117 	((*posix_clocks[clock].call) arglist)
118 
119 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
120 
121 
122 static int
123 settime(struct thread *td, struct timeval *tv)
124 {
125 	struct timeval delta, tv1, tv2;
126 	static struct timeval maxtime, laststep;
127 	struct timespec ts;
128 
129 	microtime(&tv1);
130 	delta = *tv;
131 	timevalsub(&delta, &tv1);
132 
133 	/*
134 	 * If the system is secure, we do not allow the time to be
135 	 * set to a value earlier than 1 second less than the highest
136 	 * time we have yet seen. The worst a miscreant can do in
137 	 * this circumstance is "freeze" time. He couldn't go
138 	 * back to the past.
139 	 *
140 	 * We similarly do not allow the clock to be stepped more
141 	 * than one second, nor more than once per second. This allows
142 	 * a miscreant to make the clock march double-time, but no worse.
143 	 */
144 	if (securelevel_gt(td->td_ucred, 1) != 0) {
145 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
146 			/*
147 			 * Update maxtime to latest time we've seen.
148 			 */
149 			if (tv1.tv_sec > maxtime.tv_sec)
150 				maxtime = tv1;
151 			tv2 = *tv;
152 			timevalsub(&tv2, &maxtime);
153 			if (tv2.tv_sec < -1) {
154 				tv->tv_sec = maxtime.tv_sec - 1;
155 				printf("Time adjustment clamped to -1 second\n");
156 			}
157 		} else {
158 			if (tv1.tv_sec == laststep.tv_sec)
159 				return (EPERM);
160 			if (delta.tv_sec > 1) {
161 				tv->tv_sec = tv1.tv_sec + 1;
162 				printf("Time adjustment clamped to +1 second\n");
163 			}
164 			laststep = *tv;
165 		}
166 	}
167 
168 	ts.tv_sec = tv->tv_sec;
169 	ts.tv_nsec = tv->tv_usec * 1000;
170 	tc_setclock(&ts);
171 	resettodr();
172 	return (0);
173 }
174 
175 #ifndef _SYS_SYSPROTO_H_
176 struct clock_getcpuclockid2_args {
177 	id_t id;
178 	int which,
179 	clockid_t *clock_id;
180 };
181 #endif
182 /* ARGSUSED */
183 int
184 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
185 {
186 	clockid_t clk_id;
187 	int error;
188 
189 	error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
190 	if (error == 0)
191 		error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
192 	return (error);
193 }
194 
195 int
196 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
197     clockid_t *clk_id)
198 {
199 	struct proc *p;
200 	pid_t pid;
201 	lwpid_t tid;
202 	int error;
203 
204 	switch (which) {
205 	case CPUCLOCK_WHICH_PID:
206 		if (id != 0) {
207 			error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
208 			if (error != 0)
209 				return (error);
210 			PROC_UNLOCK(p);
211 			pid = id;
212 		} else {
213 			pid = td->td_proc->p_pid;
214 		}
215 		*clk_id = MAKE_PROCESS_CPUCLOCK(pid);
216 		return (0);
217 	case CPUCLOCK_WHICH_TID:
218 		tid = id == 0 ? td->td_tid : id;
219 		*clk_id = MAKE_THREAD_CPUCLOCK(tid);
220 		return (0);
221 	default:
222 		return (EINVAL);
223 	}
224 }
225 
226 #ifndef _SYS_SYSPROTO_H_
227 struct clock_gettime_args {
228 	clockid_t clock_id;
229 	struct	timespec *tp;
230 };
231 #endif
232 /* ARGSUSED */
233 int
234 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
235 {
236 	struct timespec ats;
237 	int error;
238 
239 	error = kern_clock_gettime(td, uap->clock_id, &ats);
240 	if (error == 0)
241 		error = copyout(&ats, uap->tp, sizeof(ats));
242 
243 	return (error);
244 }
245 
246 static inline void
247 cputick2timespec(uint64_t runtime, struct timespec *ats)
248 {
249 	runtime = cputick2usec(runtime);
250 	ats->tv_sec = runtime / 1000000;
251 	ats->tv_nsec = runtime % 1000000 * 1000;
252 }
253 
254 static void
255 get_thread_cputime(struct thread *targettd, struct timespec *ats)
256 {
257 	uint64_t runtime, curtime, switchtime;
258 
259 	if (targettd == NULL) { /* current thread */
260 		critical_enter();
261 		switchtime = PCPU_GET(switchtime);
262 		curtime = cpu_ticks();
263 		runtime = curthread->td_runtime;
264 		critical_exit();
265 		runtime += curtime - switchtime;
266 	} else {
267 		thread_lock(targettd);
268 		runtime = targettd->td_runtime;
269 		thread_unlock(targettd);
270 	}
271 	cputick2timespec(runtime, ats);
272 }
273 
274 static void
275 get_process_cputime(struct proc *targetp, struct timespec *ats)
276 {
277 	uint64_t runtime;
278 	struct rusage ru;
279 
280 	PROC_STATLOCK(targetp);
281 	rufetch(targetp, &ru);
282 	runtime = targetp->p_rux.rux_runtime;
283 	PROC_STATUNLOCK(targetp);
284 	cputick2timespec(runtime, ats);
285 }
286 
287 static int
288 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
289 {
290 	struct proc *p, *p2;
291 	struct thread *td2;
292 	lwpid_t tid;
293 	pid_t pid;
294 	int error;
295 
296 	p = td->td_proc;
297 	if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
298 		tid = clock_id & CPUCLOCK_ID_MASK;
299 		td2 = tdfind(tid, p->p_pid);
300 		if (td2 == NULL)
301 			return (EINVAL);
302 		get_thread_cputime(td2, ats);
303 		PROC_UNLOCK(td2->td_proc);
304 	} else {
305 		pid = clock_id & CPUCLOCK_ID_MASK;
306 		error = pget(pid, PGET_CANSEE, &p2);
307 		if (error != 0)
308 			return (EINVAL);
309 		get_process_cputime(p2, ats);
310 		PROC_UNLOCK(p2);
311 	}
312 	return (0);
313 }
314 
315 int
316 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
317 {
318 	struct timeval sys, user;
319 	struct proc *p;
320 
321 	p = td->td_proc;
322 	switch (clock_id) {
323 	case CLOCK_REALTIME:		/* Default to precise. */
324 	case CLOCK_REALTIME_PRECISE:
325 		nanotime(ats);
326 		break;
327 	case CLOCK_REALTIME_FAST:
328 		getnanotime(ats);
329 		break;
330 	case CLOCK_VIRTUAL:
331 		PROC_LOCK(p);
332 		PROC_STATLOCK(p);
333 		calcru(p, &user, &sys);
334 		PROC_STATUNLOCK(p);
335 		PROC_UNLOCK(p);
336 		TIMEVAL_TO_TIMESPEC(&user, ats);
337 		break;
338 	case CLOCK_PROF:
339 		PROC_LOCK(p);
340 		PROC_STATLOCK(p);
341 		calcru(p, &user, &sys);
342 		PROC_STATUNLOCK(p);
343 		PROC_UNLOCK(p);
344 		timevaladd(&user, &sys);
345 		TIMEVAL_TO_TIMESPEC(&user, ats);
346 		break;
347 	case CLOCK_MONOTONIC:		/* Default to precise. */
348 	case CLOCK_MONOTONIC_PRECISE:
349 	case CLOCK_UPTIME:
350 	case CLOCK_UPTIME_PRECISE:
351 		nanouptime(ats);
352 		break;
353 	case CLOCK_UPTIME_FAST:
354 	case CLOCK_MONOTONIC_FAST:
355 		getnanouptime(ats);
356 		break;
357 	case CLOCK_SECOND:
358 		ats->tv_sec = time_second;
359 		ats->tv_nsec = 0;
360 		break;
361 	case CLOCK_THREAD_CPUTIME_ID:
362 		get_thread_cputime(NULL, ats);
363 		break;
364 	case CLOCK_PROCESS_CPUTIME_ID:
365 		PROC_LOCK(p);
366 		get_process_cputime(p, ats);
367 		PROC_UNLOCK(p);
368 		break;
369 	default:
370 		if ((int)clock_id >= 0)
371 			return (EINVAL);
372 		return (get_cputime(td, clock_id, ats));
373 	}
374 	return (0);
375 }
376 
377 #ifndef _SYS_SYSPROTO_H_
378 struct clock_settime_args {
379 	clockid_t clock_id;
380 	const struct	timespec *tp;
381 };
382 #endif
383 /* ARGSUSED */
384 int
385 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
386 {
387 	struct timespec ats;
388 	int error;
389 
390 	if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
391 		return (error);
392 	return (kern_clock_settime(td, uap->clock_id, &ats));
393 }
394 
395 static int allow_insane_settime = 0;
396 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
397     &allow_insane_settime, 0,
398     "do not perform possibly restrictive checks on settime(2) args");
399 
400 int
401 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
402 {
403 	struct timeval atv;
404 	int error;
405 
406 	if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
407 		return (error);
408 	if (clock_id != CLOCK_REALTIME)
409 		return (EINVAL);
410 	if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
411 	    ats->tv_sec < 0)
412 		return (EINVAL);
413 	if (!allow_insane_settime && ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60)
414 		return (EINVAL);
415 	/* XXX Don't convert nsec->usec and back */
416 	TIMESPEC_TO_TIMEVAL(&atv, ats);
417 	error = settime(td, &atv);
418 	return (error);
419 }
420 
421 #ifndef _SYS_SYSPROTO_H_
422 struct clock_getres_args {
423 	clockid_t clock_id;
424 	struct	timespec *tp;
425 };
426 #endif
427 int
428 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
429 {
430 	struct timespec ts;
431 	int error;
432 
433 	if (uap->tp == NULL)
434 		return (0);
435 
436 	error = kern_clock_getres(td, uap->clock_id, &ts);
437 	if (error == 0)
438 		error = copyout(&ts, uap->tp, sizeof(ts));
439 	return (error);
440 }
441 
442 int
443 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
444 {
445 
446 	ts->tv_sec = 0;
447 	switch (clock_id) {
448 	case CLOCK_REALTIME:
449 	case CLOCK_REALTIME_FAST:
450 	case CLOCK_REALTIME_PRECISE:
451 	case CLOCK_MONOTONIC:
452 	case CLOCK_MONOTONIC_FAST:
453 	case CLOCK_MONOTONIC_PRECISE:
454 	case CLOCK_UPTIME:
455 	case CLOCK_UPTIME_FAST:
456 	case CLOCK_UPTIME_PRECISE:
457 		/*
458 		 * Round up the result of the division cheaply by adding 1.
459 		 * Rounding up is especially important if rounding down
460 		 * would give 0.  Perfect rounding is unimportant.
461 		 */
462 		ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
463 		break;
464 	case CLOCK_VIRTUAL:
465 	case CLOCK_PROF:
466 		/* Accurately round up here because we can do so cheaply. */
467 		ts->tv_nsec = howmany(1000000000, hz);
468 		break;
469 	case CLOCK_SECOND:
470 		ts->tv_sec = 1;
471 		ts->tv_nsec = 0;
472 		break;
473 	case CLOCK_THREAD_CPUTIME_ID:
474 	case CLOCK_PROCESS_CPUTIME_ID:
475 	cputime:
476 		/* sync with cputick2usec */
477 		ts->tv_nsec = 1000000 / cpu_tickrate();
478 		if (ts->tv_nsec == 0)
479 			ts->tv_nsec = 1000;
480 		break;
481 	default:
482 		if ((int)clock_id < 0)
483 			goto cputime;
484 		return (EINVAL);
485 	}
486 	return (0);
487 }
488 
489 int
490 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
491 {
492 
493 	return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
494 	    rmt));
495 }
496 
497 static uint8_t nanowait[MAXCPU];
498 
499 int
500 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
501     const struct timespec *rqt, struct timespec *rmt)
502 {
503 	struct timespec ts, now;
504 	sbintime_t sbt, sbtt, prec, tmp;
505 	time_t over;
506 	int error;
507 	bool is_abs_real;
508 
509 	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
510 		return (EINVAL);
511 	if ((flags & ~TIMER_ABSTIME) != 0)
512 		return (EINVAL);
513 	switch (clock_id) {
514 	case CLOCK_REALTIME:
515 	case CLOCK_REALTIME_PRECISE:
516 	case CLOCK_REALTIME_FAST:
517 	case CLOCK_SECOND:
518 		is_abs_real = (flags & TIMER_ABSTIME) != 0;
519 		break;
520 	case CLOCK_MONOTONIC:
521 	case CLOCK_MONOTONIC_PRECISE:
522 	case CLOCK_MONOTONIC_FAST:
523 	case CLOCK_UPTIME:
524 	case CLOCK_UPTIME_PRECISE:
525 	case CLOCK_UPTIME_FAST:
526 		is_abs_real = false;
527 		break;
528 	case CLOCK_VIRTUAL:
529 	case CLOCK_PROF:
530 	case CLOCK_PROCESS_CPUTIME_ID:
531 		return (ENOTSUP);
532 	case CLOCK_THREAD_CPUTIME_ID:
533 	default:
534 		return (EINVAL);
535 	}
536 	do {
537 		ts = *rqt;
538 		if ((flags & TIMER_ABSTIME) != 0) {
539 			if (is_abs_real)
540 				td->td_rtcgen =
541 				    atomic_load_acq_int(&rtc_generation);
542 			error = kern_clock_gettime(td, clock_id, &now);
543 			KASSERT(error == 0, ("kern_clock_gettime: %d", error));
544 			timespecsub(&ts, &now);
545 		}
546 		if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
547 			error = EWOULDBLOCK;
548 			break;
549 		}
550 		if (ts.tv_sec > INT32_MAX / 2) {
551 			over = ts.tv_sec - INT32_MAX / 2;
552 			ts.tv_sec -= over;
553 		} else
554 			over = 0;
555 		tmp = tstosbt(ts);
556 		prec = tmp;
557 		prec >>= tc_precexp;
558 		if (TIMESEL(&sbt, tmp))
559 			sbt += tc_tick_sbt;
560 		sbt += tmp;
561 		error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
562 		    sbt, prec, C_ABSOLUTE);
563 	} while (error == 0 && is_abs_real && td->td_rtcgen == 0);
564 	td->td_rtcgen = 0;
565 	if (error != EWOULDBLOCK) {
566 		TIMESEL(&sbtt, tmp);
567 		if (sbtt >= sbt)
568 			return (0);
569 		if (error == ERESTART)
570 			error = EINTR;
571 		if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
572 			ts = sbttots(sbt - sbtt);
573 			ts.tv_sec += over;
574 			if (ts.tv_sec < 0)
575 				timespecclear(&ts);
576 			*rmt = ts;
577 		}
578 		return (error);
579 	}
580 	return (0);
581 }
582 
583 #ifndef _SYS_SYSPROTO_H_
584 struct nanosleep_args {
585 	struct	timespec *rqtp;
586 	struct	timespec *rmtp;
587 };
588 #endif
589 /* ARGSUSED */
590 int
591 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
592 {
593 
594 	return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
595 	    uap->rqtp, uap->rmtp));
596 }
597 
598 #ifndef _SYS_SYSPROTO_H_
599 struct clock_nanosleep_args {
600 	clockid_t clock_id;
601 	int 	  flags;
602 	struct	timespec *rqtp;
603 	struct	timespec *rmtp;
604 };
605 #endif
606 /* ARGSUSED */
607 int
608 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
609 {
610 	int error;
611 
612 	error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
613 	    uap->rmtp);
614 	return (kern_posix_error(td, error));
615 }
616 
617 static int
618 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
619     const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
620 {
621 	struct timespec rmt, rqt;
622 	int error;
623 
624 	error = copyin(ua_rqtp, &rqt, sizeof(rqt));
625 	if (error)
626 		return (error);
627 	if (ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0 &&
628 	    !useracc(ua_rmtp, sizeof(rmt), VM_PROT_WRITE))
629 		return (EFAULT);
630 	error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
631 	if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
632 		int error2;
633 
634 		error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
635 		if (error2)
636 			error = error2;
637 	}
638 	return (error);
639 }
640 
641 #ifndef _SYS_SYSPROTO_H_
642 struct gettimeofday_args {
643 	struct	timeval *tp;
644 	struct	timezone *tzp;
645 };
646 #endif
647 /* ARGSUSED */
648 int
649 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
650 {
651 	struct timeval atv;
652 	struct timezone rtz;
653 	int error = 0;
654 
655 	if (uap->tp) {
656 		microtime(&atv);
657 		error = copyout(&atv, uap->tp, sizeof (atv));
658 	}
659 	if (error == 0 && uap->tzp != NULL) {
660 		rtz.tz_minuteswest = tz_minuteswest;
661 		rtz.tz_dsttime = tz_dsttime;
662 		error = copyout(&rtz, uap->tzp, sizeof (rtz));
663 	}
664 	return (error);
665 }
666 
667 #ifndef _SYS_SYSPROTO_H_
668 struct settimeofday_args {
669 	struct	timeval *tv;
670 	struct	timezone *tzp;
671 };
672 #endif
673 /* ARGSUSED */
674 int
675 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
676 {
677 	struct timeval atv, *tvp;
678 	struct timezone atz, *tzp;
679 	int error;
680 
681 	if (uap->tv) {
682 		error = copyin(uap->tv, &atv, sizeof(atv));
683 		if (error)
684 			return (error);
685 		tvp = &atv;
686 	} else
687 		tvp = NULL;
688 	if (uap->tzp) {
689 		error = copyin(uap->tzp, &atz, sizeof(atz));
690 		if (error)
691 			return (error);
692 		tzp = &atz;
693 	} else
694 		tzp = NULL;
695 	return (kern_settimeofday(td, tvp, tzp));
696 }
697 
698 int
699 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
700 {
701 	int error;
702 
703 	error = priv_check(td, PRIV_SETTIMEOFDAY);
704 	if (error)
705 		return (error);
706 	/* Verify all parameters before changing time. */
707 	if (tv) {
708 		if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
709 		    tv->tv_sec < 0)
710 			return (EINVAL);
711 		error = settime(td, tv);
712 	}
713 	if (tzp && error == 0) {
714 		tz_minuteswest = tzp->tz_minuteswest;
715 		tz_dsttime = tzp->tz_dsttime;
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);
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 		} else {
1563 			timespecsub(&ts, &cts);
1564 			/*
1565 			 * We don't care if ts is negative, tztohz will
1566 			 * fix it.
1567 			 */
1568 		}
1569 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1570 		callout_reset(&it->it_callout, tvtohz(&tv),
1571 			realtimer_expire, it);
1572 	} else {
1573 		callout_stop(&it->it_callout);
1574 	}
1575 
1576 	return (0);
1577 }
1578 
1579 static void
1580 realtimer_clocktime(clockid_t id, struct timespec *ts)
1581 {
1582 	if (id == CLOCK_REALTIME)
1583 		getnanotime(ts);
1584 	else	/* CLOCK_MONOTONIC */
1585 		getnanouptime(ts);
1586 }
1587 
1588 int
1589 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1590 {
1591 	struct itimer *it;
1592 
1593 	PROC_LOCK_ASSERT(p, MA_OWNED);
1594 	it = itimer_find(p, timerid);
1595 	if (it != NULL) {
1596 		ksi->ksi_overrun = it->it_overrun;
1597 		it->it_overrun_last = it->it_overrun;
1598 		it->it_overrun = 0;
1599 		ITIMER_UNLOCK(it);
1600 		return (0);
1601 	}
1602 	return (EINVAL);
1603 }
1604 
1605 int
1606 itimespecfix(struct timespec *ts)
1607 {
1608 
1609 	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1610 		return (EINVAL);
1611 	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1612 		ts->tv_nsec = tick * 1000;
1613 	return (0);
1614 }
1615 
1616 /* Timeout callback for realtime timer */
1617 static void
1618 realtimer_expire(void *arg)
1619 {
1620 	struct timespec cts, ts;
1621 	struct timeval tv;
1622 	struct itimer *it;
1623 
1624 	it = (struct itimer *)arg;
1625 
1626 	realtimer_clocktime(it->it_clockid, &cts);
1627 	/* Only fire if time is reached. */
1628 	if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1629 		if (timespecisset(&it->it_time.it_interval)) {
1630 			timespecadd(&it->it_time.it_value,
1631 				    &it->it_time.it_interval);
1632 			while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1633 				if (it->it_overrun < INT_MAX)
1634 					it->it_overrun++;
1635 				else
1636 					it->it_ksi.ksi_errno = ERANGE;
1637 				timespecadd(&it->it_time.it_value,
1638 					    &it->it_time.it_interval);
1639 			}
1640 		} else {
1641 			/* single shot timer ? */
1642 			timespecclear(&it->it_time.it_value);
1643 		}
1644 		if (timespecisset(&it->it_time.it_value)) {
1645 			ts = it->it_time.it_value;
1646 			timespecsub(&ts, &cts);
1647 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1648 			callout_reset(&it->it_callout, tvtohz(&tv),
1649 				 realtimer_expire, it);
1650 		}
1651 		itimer_enter(it);
1652 		ITIMER_UNLOCK(it);
1653 		itimer_fire(it);
1654 		ITIMER_LOCK(it);
1655 		itimer_leave(it);
1656 	} else if (timespecisset(&it->it_time.it_value)) {
1657 		ts = it->it_time.it_value;
1658 		timespecsub(&ts, &cts);
1659 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1660 		callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1661  			it);
1662 	}
1663 }
1664 
1665 void
1666 itimer_fire(struct itimer *it)
1667 {
1668 	struct proc *p = it->it_proc;
1669 	struct thread *td;
1670 
1671 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1672 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1673 		if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1674 			ITIMER_LOCK(it);
1675 			timespecclear(&it->it_time.it_value);
1676 			timespecclear(&it->it_time.it_interval);
1677 			callout_stop(&it->it_callout);
1678 			ITIMER_UNLOCK(it);
1679 			return;
1680 		}
1681 		if (!KSI_ONQ(&it->it_ksi)) {
1682 			it->it_ksi.ksi_errno = 0;
1683 			ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1684 			tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1685 		} else {
1686 			if (it->it_overrun < INT_MAX)
1687 				it->it_overrun++;
1688 			else
1689 				it->it_ksi.ksi_errno = ERANGE;
1690 		}
1691 		PROC_UNLOCK(p);
1692 	}
1693 }
1694 
1695 static void
1696 itimers_alloc(struct proc *p)
1697 {
1698 	struct itimers *its;
1699 	int i;
1700 
1701 	its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1702 	LIST_INIT(&its->its_virtual);
1703 	LIST_INIT(&its->its_prof);
1704 	TAILQ_INIT(&its->its_worklist);
1705 	for (i = 0; i < TIMER_MAX; i++)
1706 		its->its_timers[i] = NULL;
1707 	PROC_LOCK(p);
1708 	if (p->p_itimers == NULL) {
1709 		p->p_itimers = its;
1710 		PROC_UNLOCK(p);
1711 	}
1712 	else {
1713 		PROC_UNLOCK(p);
1714 		free(its, M_SUBPROC);
1715 	}
1716 }
1717 
1718 static void
1719 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1720 {
1721 	itimers_event_hook_exit(arg, p);
1722 }
1723 
1724 /* Clean up timers when some process events are being triggered. */
1725 static void
1726 itimers_event_hook_exit(void *arg, struct proc *p)
1727 {
1728 	struct itimers *its;
1729 	struct itimer *it;
1730 	int event = (int)(intptr_t)arg;
1731 	int i;
1732 
1733 	if (p->p_itimers != NULL) {
1734 		its = p->p_itimers;
1735 		for (i = 0; i < MAX_CLOCKS; ++i) {
1736 			if (posix_clocks[i].event_hook != NULL)
1737 				CLOCK_CALL(i, event_hook, (p, i, event));
1738 		}
1739 		/*
1740 		 * According to susv3, XSI interval timers should be inherited
1741 		 * by new image.
1742 		 */
1743 		if (event == ITIMER_EV_EXEC)
1744 			i = 3;
1745 		else if (event == ITIMER_EV_EXIT)
1746 			i = 0;
1747 		else
1748 			panic("unhandled event");
1749 		for (; i < TIMER_MAX; ++i) {
1750 			if ((it = its->its_timers[i]) != NULL)
1751 				kern_ktimer_delete(curthread, i);
1752 		}
1753 		if (its->its_timers[0] == NULL &&
1754 		    its->its_timers[1] == NULL &&
1755 		    its->its_timers[2] == NULL) {
1756 			free(its, M_SUBPROC);
1757 			p->p_itimers = NULL;
1758 		}
1759 	}
1760 }
1761