xref: /freebsd/sys/kern/kern_time.c (revision ac099daf6742ead81ea7ea86351a8ef4e783041b)
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/resourcevar.h>
47 #include <sys/signalvar.h>
48 #include <sys/kernel.h>
49 #include <sys/sleepqueue.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/posix4.h>
56 #include <sys/time.h>
57 #include <sys/timers.h>
58 #include <sys/timetc.h>
59 #include <sys/vnode.h>
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63 
64 #include <vm/vm.h>
65 #include <vm/vm_extern.h>
66 
67 #define MAX_CLOCKS 	(CLOCK_MONOTONIC+1)
68 #define CPUCLOCK_BIT		0x80000000
69 #define CPUCLOCK_PROCESS_BIT	0x40000000
70 #define CPUCLOCK_ID_MASK	(~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
71 #define MAKE_THREAD_CPUCLOCK(tid)	(CPUCLOCK_BIT|(tid))
72 #define MAKE_PROCESS_CPUCLOCK(pid)	\
73 	(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
74 
75 static struct kclock	posix_clocks[MAX_CLOCKS];
76 static uma_zone_t	itimer_zone = NULL;
77 
78 /*
79  * Time of day and interval timer support.
80  *
81  * These routines provide the kernel entry points to get and set
82  * the time-of-day and per-process interval timers.  Subroutines
83  * here provide support for adding and subtracting timeval structures
84  * and decrementing interval timers, optionally reloading the interval
85  * timers when they expire.
86  */
87 
88 static int	settime(struct thread *, struct timeval *);
89 static void	timevalfix(struct timeval *);
90 static int	user_clock_nanosleep(struct thread *td, clockid_t clock_id,
91 		    int flags, const struct timespec *ua_rqtp,
92 		    struct timespec *ua_rmtp);
93 
94 static void	itimer_start(void);
95 static int	itimer_init(void *, int, int);
96 static void	itimer_fini(void *, int);
97 static void	itimer_enter(struct itimer *);
98 static void	itimer_leave(struct itimer *);
99 static struct itimer *itimer_find(struct proc *, int);
100 static void	itimers_alloc(struct proc *);
101 static int	realtimer_create(struct itimer *);
102 static int	realtimer_gettime(struct itimer *, struct itimerspec *);
103 static int	realtimer_settime(struct itimer *, int,
104 			struct itimerspec *, struct itimerspec *);
105 static int	realtimer_delete(struct itimer *);
106 static void	realtimer_clocktime(clockid_t, struct timespec *);
107 static void	realtimer_expire(void *);
108 static void	realtimer_expire_l(struct itimer *it, bool proc_locked);
109 
110 static int	register_posix_clock(int, const struct kclock *);
111 static void	itimer_fire(struct itimer *it);
112 static int	itimespecfix(struct timespec *ts);
113 
114 #define CLOCK_CALL(clock, call, arglist)		\
115 	((*posix_clocks[clock].call) arglist)
116 
117 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
118 
119 static int
120 settime(struct thread *td, struct timeval *tv)
121 {
122 	struct timeval delta, tv1, tv2;
123 	static struct timeval maxtime, laststep;
124 	struct timespec ts;
125 
126 	microtime(&tv1);
127 	delta = *tv;
128 	timevalsub(&delta, &tv1);
129 
130 	/*
131 	 * If the system is secure, we do not allow the time to be
132 	 * set to a value earlier than 1 second less than the highest
133 	 * time we have yet seen. The worst a miscreant can do in
134 	 * this circumstance is "freeze" time. He couldn't go
135 	 * back to the past.
136 	 *
137 	 * We similarly do not allow the clock to be stepped more
138 	 * than one second, nor more than once per second. This allows
139 	 * a miscreant to make the clock march double-time, but no worse.
140 	 */
141 	if (securelevel_gt(td->td_ucred, 1) != 0) {
142 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
143 			/*
144 			 * Update maxtime to latest time we've seen.
145 			 */
146 			if (tv1.tv_sec > maxtime.tv_sec)
147 				maxtime = tv1;
148 			tv2 = *tv;
149 			timevalsub(&tv2, &maxtime);
150 			if (tv2.tv_sec < -1) {
151 				tv->tv_sec = maxtime.tv_sec - 1;
152 				printf("Time adjustment clamped to -1 second\n");
153 			}
154 		} else {
155 			if (tv1.tv_sec == laststep.tv_sec)
156 				return (EPERM);
157 			if (delta.tv_sec > 1) {
158 				tv->tv_sec = tv1.tv_sec + 1;
159 				printf("Time adjustment clamped to +1 second\n");
160 			}
161 			laststep = *tv;
162 		}
163 	}
164 
165 	ts.tv_sec = tv->tv_sec;
166 	ts.tv_nsec = tv->tv_usec * 1000;
167 	tc_setclock(&ts);
168 	resettodr();
169 	return (0);
170 }
171 
172 #ifndef _SYS_SYSPROTO_H_
173 struct clock_getcpuclockid2_args {
174 	id_t id;
175 	int which,
176 	clockid_t *clock_id;
177 };
178 #endif
179 /* ARGSUSED */
180 int
181 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
182 {
183 	clockid_t clk_id;
184 	int error;
185 
186 	error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
187 	if (error == 0)
188 		error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
189 	return (error);
190 }
191 
192 int
193 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
194     clockid_t *clk_id)
195 {
196 	struct proc *p;
197 	pid_t pid;
198 	lwpid_t tid;
199 	int error;
200 
201 	switch (which) {
202 	case CPUCLOCK_WHICH_PID:
203 		if (id != 0) {
204 			error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
205 			if (error != 0)
206 				return (error);
207 			PROC_UNLOCK(p);
208 			pid = id;
209 		} else {
210 			pid = td->td_proc->p_pid;
211 		}
212 		*clk_id = MAKE_PROCESS_CPUCLOCK(pid);
213 		return (0);
214 	case CPUCLOCK_WHICH_TID:
215 		tid = id == 0 ? td->td_tid : id;
216 		*clk_id = MAKE_THREAD_CPUCLOCK(tid);
217 		return (0);
218 	default:
219 		return (EINVAL);
220 	}
221 }
222 
223 #ifndef _SYS_SYSPROTO_H_
224 struct clock_gettime_args {
225 	clockid_t clock_id;
226 	struct	timespec *tp;
227 };
228 #endif
229 /* ARGSUSED */
230 int
231 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
232 {
233 	struct timespec ats;
234 	int error;
235 
236 	error = kern_clock_gettime(td, uap->clock_id, &ats);
237 	if (error == 0)
238 		error = copyout(&ats, uap->tp, sizeof(ats));
239 
240 	return (error);
241 }
242 
243 static inline void
244 cputick2timespec(uint64_t runtime, struct timespec *ats)
245 {
246 	runtime = cputick2usec(runtime);
247 	ats->tv_sec = runtime / 1000000;
248 	ats->tv_nsec = runtime % 1000000 * 1000;
249 }
250 
251 void
252 kern_thread_cputime(struct thread *targettd, struct timespec *ats)
253 {
254 	uint64_t runtime, curtime, switchtime;
255 
256 	if (targettd == NULL) { /* current thread */
257 		critical_enter();
258 		switchtime = PCPU_GET(switchtime);
259 		curtime = cpu_ticks();
260 		runtime = curthread->td_runtime;
261 		critical_exit();
262 		runtime += curtime - switchtime;
263 	} else {
264 		PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
265 		thread_lock(targettd);
266 		runtime = targettd->td_runtime;
267 		thread_unlock(targettd);
268 	}
269 	cputick2timespec(runtime, ats);
270 }
271 
272 void
273 kern_process_cputime(struct proc *targetp, struct timespec *ats)
274 {
275 	uint64_t runtime;
276 	struct rusage ru;
277 
278 	PROC_LOCK_ASSERT(targetp, MA_OWNED);
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 		kern_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 		kern_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 		kern_thread_cputime(NULL, ats);
364 		break;
365 	case CLOCK_PROCESS_CPUTIME_ID:
366 		PROC_LOCK(p);
367 		kern_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, error2;
627 
628 	error = copyin(ua_rqtp, &rqt, sizeof(rqt));
629 	if (error)
630 		return (error);
631 	error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
632 	if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
633 		error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
634 		if (error2 != 0)
635 			error = error2;
636 	}
637 	return (error);
638 }
639 
640 #ifndef _SYS_SYSPROTO_H_
641 struct gettimeofday_args {
642 	struct	timeval *tp;
643 	struct	timezone *tzp;
644 };
645 #endif
646 /* ARGSUSED */
647 int
648 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
649 {
650 	struct timeval atv;
651 	struct timezone rtz;
652 	int error = 0;
653 
654 	if (uap->tp) {
655 		microtime(&atv);
656 		error = copyout(&atv, uap->tp, sizeof (atv));
657 	}
658 	if (error == 0 && uap->tzp != NULL) {
659 		rtz.tz_minuteswest = 0;
660 		rtz.tz_dsttime = 0;
661 		error = copyout(&rtz, uap->tzp, sizeof (rtz));
662 	}
663 	return (error);
664 }
665 
666 #ifndef _SYS_SYSPROTO_H_
667 struct settimeofday_args {
668 	struct	timeval *tv;
669 	struct	timezone *tzp;
670 };
671 #endif
672 /* ARGSUSED */
673 int
674 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
675 {
676 	struct timeval atv, *tvp;
677 	struct timezone atz, *tzp;
678 	int error;
679 
680 	if (uap->tv) {
681 		error = copyin(uap->tv, &atv, sizeof(atv));
682 		if (error)
683 			return (error);
684 		tvp = &atv;
685 	} else
686 		tvp = NULL;
687 	if (uap->tzp) {
688 		error = copyin(uap->tzp, &atz, sizeof(atz));
689 		if (error)
690 			return (error);
691 		tzp = &atz;
692 	} else
693 		tzp = NULL;
694 	return (kern_settimeofday(td, tvp, tzp));
695 }
696 
697 int
698 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
699 {
700 	int error;
701 
702 	error = priv_check(td, PRIV_SETTIMEOFDAY);
703 	if (error)
704 		return (error);
705 	/* Verify all parameters before changing time. */
706 	if (tv) {
707 		if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
708 		    tv->tv_sec < 0)
709 			return (EINVAL);
710 		error = settime(td, tv);
711 	}
712 	return (error);
713 }
714 
715 /*
716  * Get value of an interval timer.  The process virtual and profiling virtual
717  * time timers are kept in the p_stats area, since they can be swapped out.
718  * These are kept internally in the way they are specified externally: in
719  * time until they expire.
720  *
721  * The real time interval timer is kept in the process table slot for the
722  * process, and its value (it_value) is kept as an absolute time rather than
723  * as a delta, so that it is easy to keep periodic real-time signals from
724  * drifting.
725  *
726  * Virtual time timers are processed in the hardclock() routine of
727  * kern_clock.c.  The real time timer is processed by a timeout routine,
728  * called from the softclock() routine.  Since a callout may be delayed in
729  * real time due to interrupt processing in the system, it is possible for
730  * the real time timeout routine (realitexpire, given below), to be delayed
731  * in real time past when it is supposed to occur.  It does not suffice,
732  * therefore, to reload the real timer .it_value from the real time timers
733  * .it_interval.  Rather, we compute the next time in absolute time the timer
734  * should go off.
735  */
736 #ifndef _SYS_SYSPROTO_H_
737 struct getitimer_args {
738 	u_int	which;
739 	struct	itimerval *itv;
740 };
741 #endif
742 int
743 sys_getitimer(struct thread *td, struct getitimer_args *uap)
744 {
745 	struct itimerval aitv;
746 	int error;
747 
748 	error = kern_getitimer(td, uap->which, &aitv);
749 	if (error != 0)
750 		return (error);
751 	return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
752 }
753 
754 int
755 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
756 {
757 	struct proc *p = td->td_proc;
758 	struct timeval ctv;
759 
760 	if (which > ITIMER_PROF)
761 		return (EINVAL);
762 
763 	if (which == ITIMER_REAL) {
764 		/*
765 		 * Convert from absolute to relative time in .it_value
766 		 * part of real time timer.  If time for real time timer
767 		 * has passed return 0, else return difference between
768 		 * current time and time for the timer to go off.
769 		 */
770 		PROC_LOCK(p);
771 		*aitv = p->p_realtimer;
772 		PROC_UNLOCK(p);
773 		if (timevalisset(&aitv->it_value)) {
774 			microuptime(&ctv);
775 			if (timevalcmp(&aitv->it_value, &ctv, <))
776 				timevalclear(&aitv->it_value);
777 			else
778 				timevalsub(&aitv->it_value, &ctv);
779 		}
780 	} else {
781 		PROC_ITIMLOCK(p);
782 		*aitv = p->p_stats->p_timer[which];
783 		PROC_ITIMUNLOCK(p);
784 	}
785 #ifdef KTRACE
786 	if (KTRPOINT(td, KTR_STRUCT))
787 		ktritimerval(aitv);
788 #endif
789 	return (0);
790 }
791 
792 #ifndef _SYS_SYSPROTO_H_
793 struct setitimer_args {
794 	u_int	which;
795 	struct	itimerval *itv, *oitv;
796 };
797 #endif
798 int
799 sys_setitimer(struct thread *td, struct setitimer_args *uap)
800 {
801 	struct itimerval aitv, oitv;
802 	int error;
803 
804 	if (uap->itv == NULL) {
805 		uap->itv = uap->oitv;
806 		return (sys_getitimer(td, (struct getitimer_args *)uap));
807 	}
808 
809 	if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
810 		return (error);
811 	error = kern_setitimer(td, uap->which, &aitv, &oitv);
812 	if (error != 0 || uap->oitv == NULL)
813 		return (error);
814 	return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
815 }
816 
817 int
818 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
819     struct itimerval *oitv)
820 {
821 	struct proc *p = td->td_proc;
822 	struct timeval ctv;
823 	sbintime_t sbt, pr;
824 
825 	if (aitv == NULL)
826 		return (kern_getitimer(td, which, oitv));
827 
828 	if (which > ITIMER_PROF)
829 		return (EINVAL);
830 #ifdef KTRACE
831 	if (KTRPOINT(td, KTR_STRUCT))
832 		ktritimerval(aitv);
833 #endif
834 	if (itimerfix(&aitv->it_value) ||
835 	    aitv->it_value.tv_sec > INT32_MAX / 2)
836 		return (EINVAL);
837 	if (!timevalisset(&aitv->it_value))
838 		timevalclear(&aitv->it_interval);
839 	else if (itimerfix(&aitv->it_interval) ||
840 	    aitv->it_interval.tv_sec > INT32_MAX / 2)
841 		return (EINVAL);
842 
843 	if (which == ITIMER_REAL) {
844 		PROC_LOCK(p);
845 		if (timevalisset(&p->p_realtimer.it_value))
846 			callout_stop(&p->p_itcallout);
847 		microuptime(&ctv);
848 		if (timevalisset(&aitv->it_value)) {
849 			pr = tvtosbt(aitv->it_value) >> tc_precexp;
850 			timevaladd(&aitv->it_value, &ctv);
851 			sbt = tvtosbt(aitv->it_value);
852 			callout_reset_sbt(&p->p_itcallout, sbt, pr,
853 			    realitexpire, p, C_ABSOLUTE);
854 		}
855 		*oitv = p->p_realtimer;
856 		p->p_realtimer = *aitv;
857 		PROC_UNLOCK(p);
858 		if (timevalisset(&oitv->it_value)) {
859 			if (timevalcmp(&oitv->it_value, &ctv, <))
860 				timevalclear(&oitv->it_value);
861 			else
862 				timevalsub(&oitv->it_value, &ctv);
863 		}
864 	} else {
865 		if (aitv->it_interval.tv_sec == 0 &&
866 		    aitv->it_interval.tv_usec != 0 &&
867 		    aitv->it_interval.tv_usec < tick)
868 			aitv->it_interval.tv_usec = tick;
869 		if (aitv->it_value.tv_sec == 0 &&
870 		    aitv->it_value.tv_usec != 0 &&
871 		    aitv->it_value.tv_usec < tick)
872 			aitv->it_value.tv_usec = tick;
873 		PROC_ITIMLOCK(p);
874 		*oitv = p->p_stats->p_timer[which];
875 		p->p_stats->p_timer[which] = *aitv;
876 		PROC_ITIMUNLOCK(p);
877 	}
878 #ifdef KTRACE
879 	if (KTRPOINT(td, KTR_STRUCT))
880 		ktritimerval(oitv);
881 #endif
882 	return (0);
883 }
884 
885 static void
886 realitexpire_reset_callout(struct proc *p, sbintime_t *isbtp)
887 {
888 	sbintime_t prec;
889 
890 	prec = isbtp == NULL ? tvtosbt(p->p_realtimer.it_interval) : *isbtp;
891 	callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
892 	    prec >> tc_precexp, realitexpire, p, C_ABSOLUTE);
893 }
894 
895 void
896 itimer_proc_continue(struct proc *p)
897 {
898 	struct timeval ctv;
899 	struct itimer *it;
900 	int id;
901 
902 	PROC_LOCK_ASSERT(p, MA_OWNED);
903 
904 	if ((p->p_flag2 & P2_ITSTOPPED) != 0) {
905 		p->p_flag2 &= ~P2_ITSTOPPED;
906 		microuptime(&ctv);
907 		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >=))
908 			realitexpire(p);
909 		else
910 			realitexpire_reset_callout(p, NULL);
911 	}
912 
913 	if (p->p_itimers != NULL) {
914 		for (id = 3; id < TIMER_MAX; id++) {
915 			it = p->p_itimers->its_timers[id];
916 			if (it == NULL)
917 				continue;
918 			if ((it->it_flags & ITF_PSTOPPED) != 0) {
919 				ITIMER_LOCK(it);
920 				if ((it->it_flags & ITF_PSTOPPED) != 0) {
921 					it->it_flags &= ~ITF_PSTOPPED;
922 					if ((it->it_flags & ITF_DELETING) == 0)
923 						realtimer_expire_l(it, true);
924 				}
925 				ITIMER_UNLOCK(it);
926 			}
927 		}
928 	}
929 }
930 
931 /*
932  * Real interval timer expired:
933  * send process whose timer expired an alarm signal.
934  * If time is not set up to reload, then just return.
935  * Else compute next time timer should go off which is > current time.
936  * This is where delay in processing this timeout causes multiple
937  * SIGALRM calls to be compressed into one.
938  * tvtohz() always adds 1 to allow for the time until the next clock
939  * interrupt being strictly less than 1 clock tick, but we don't want
940  * that here since we want to appear to be in sync with the clock
941  * interrupt even when we're delayed.
942  */
943 void
944 realitexpire(void *arg)
945 {
946 	struct proc *p;
947 	struct timeval ctv;
948 	sbintime_t isbt;
949 
950 	p = (struct proc *)arg;
951 	kern_psignal(p, SIGALRM);
952 	if (!timevalisset(&p->p_realtimer.it_interval)) {
953 		timevalclear(&p->p_realtimer.it_value);
954 		if (p->p_flag & P_WEXIT)
955 			wakeup(&p->p_itcallout);
956 		return;
957 	}
958 
959 	isbt = tvtosbt(p->p_realtimer.it_interval);
960 	if (isbt >= sbt_timethreshold)
961 		getmicrouptime(&ctv);
962 	else
963 		microuptime(&ctv);
964 	do {
965 		timevaladd(&p->p_realtimer.it_value,
966 		    &p->p_realtimer.it_interval);
967 	} while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
968 
969 	if (P_SHOULDSTOP(p) || P_KILLED(p)) {
970 		p->p_flag2 |= P2_ITSTOPPED;
971 		return;
972 	}
973 
974 	p->p_flag2 &= ~P2_ITSTOPPED;
975 	realitexpire_reset_callout(p, &isbt);
976 }
977 
978 /*
979  * Check that a proposed value to load into the .it_value or
980  * .it_interval part of an interval timer is acceptable, and
981  * fix it to have at least minimal value (i.e. if it is less
982  * than the resolution of the clock, round it up.)
983  */
984 int
985 itimerfix(struct timeval *tv)
986 {
987 
988 	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
989 		return (EINVAL);
990 	if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
991 	    tv->tv_usec < (u_int)tick / 16)
992 		tv->tv_usec = (u_int)tick / 16;
993 	return (0);
994 }
995 
996 /*
997  * Decrement an interval timer by a specified number
998  * of microseconds, which must be less than a second,
999  * i.e. < 1000000.  If the timer expires, then reload
1000  * it.  In this case, carry over (usec - old value) to
1001  * reduce the value reloaded into the timer so that
1002  * the timer does not drift.  This routine assumes
1003  * that it is called in a context where the timers
1004  * on which it is operating cannot change in value.
1005  */
1006 int
1007 itimerdecr(struct itimerval *itp, int usec)
1008 {
1009 
1010 	if (itp->it_value.tv_usec < usec) {
1011 		if (itp->it_value.tv_sec == 0) {
1012 			/* expired, and already in next interval */
1013 			usec -= itp->it_value.tv_usec;
1014 			goto expire;
1015 		}
1016 		itp->it_value.tv_usec += 1000000;
1017 		itp->it_value.tv_sec--;
1018 	}
1019 	itp->it_value.tv_usec -= usec;
1020 	usec = 0;
1021 	if (timevalisset(&itp->it_value))
1022 		return (1);
1023 	/* expired, exactly at end of interval */
1024 expire:
1025 	if (timevalisset(&itp->it_interval)) {
1026 		itp->it_value = itp->it_interval;
1027 		itp->it_value.tv_usec -= usec;
1028 		if (itp->it_value.tv_usec < 0) {
1029 			itp->it_value.tv_usec += 1000000;
1030 			itp->it_value.tv_sec--;
1031 		}
1032 	} else
1033 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
1034 	return (0);
1035 }
1036 
1037 /*
1038  * Add and subtract routines for timevals.
1039  * N.B.: subtract routine doesn't deal with
1040  * results which are before the beginning,
1041  * it just gets very confused in this case.
1042  * Caveat emptor.
1043  */
1044 void
1045 timevaladd(struct timeval *t1, const struct timeval *t2)
1046 {
1047 
1048 	t1->tv_sec += t2->tv_sec;
1049 	t1->tv_usec += t2->tv_usec;
1050 	timevalfix(t1);
1051 }
1052 
1053 void
1054 timevalsub(struct timeval *t1, const struct timeval *t2)
1055 {
1056 
1057 	t1->tv_sec -= t2->tv_sec;
1058 	t1->tv_usec -= t2->tv_usec;
1059 	timevalfix(t1);
1060 }
1061 
1062 static void
1063 timevalfix(struct timeval *t1)
1064 {
1065 
1066 	if (t1->tv_usec < 0) {
1067 		t1->tv_sec--;
1068 		t1->tv_usec += 1000000;
1069 	}
1070 	if (t1->tv_usec >= 1000000) {
1071 		t1->tv_sec++;
1072 		t1->tv_usec -= 1000000;
1073 	}
1074 }
1075 
1076 /*
1077  * ratecheck(): simple time-based rate-limit checking.
1078  */
1079 int
1080 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1081 {
1082 	struct timeval tv, delta;
1083 	int rv = 0;
1084 
1085 	getmicrouptime(&tv);		/* NB: 10ms precision */
1086 	delta = tv;
1087 	timevalsub(&delta, lasttime);
1088 
1089 	/*
1090 	 * check for 0,0 is so that the message will be seen at least once,
1091 	 * even if interval is huge.
1092 	 */
1093 	if (timevalcmp(&delta, mininterval, >=) ||
1094 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1095 		*lasttime = tv;
1096 		rv = 1;
1097 	}
1098 
1099 	return (rv);
1100 }
1101 
1102 /*
1103  * ppsratecheck(): packets (or events) per second limitation.
1104  *
1105  * Return 0 if the limit is to be enforced (e.g. the caller
1106  * should drop a packet because of the rate limitation).
1107  *
1108  * maxpps of 0 always causes zero to be returned.  maxpps of -1
1109  * always causes 1 to be returned; this effectively defeats rate
1110  * limiting.
1111  *
1112  * Note that we maintain the struct timeval for compatibility
1113  * with other bsd systems.  We reuse the storage and just monitor
1114  * clock ticks for minimal overhead.
1115  */
1116 int
1117 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1118 {
1119 	int now;
1120 
1121 	/*
1122 	 * Reset the last time and counter if this is the first call
1123 	 * or more than a second has passed since the last update of
1124 	 * lasttime.
1125 	 */
1126 	now = ticks;
1127 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1128 		lasttime->tv_sec = now;
1129 		*curpps = 1;
1130 		return (maxpps != 0);
1131 	} else {
1132 		(*curpps)++;		/* NB: ignore potential overflow */
1133 		return (maxpps < 0 || *curpps <= maxpps);
1134 	}
1135 }
1136 
1137 static void
1138 itimer_start(void)
1139 {
1140 	static const struct kclock rt_clock = {
1141 		.timer_create  = realtimer_create,
1142 		.timer_delete  = realtimer_delete,
1143 		.timer_settime = realtimer_settime,
1144 		.timer_gettime = realtimer_gettime,
1145 	};
1146 
1147 	itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1148 		NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1149 	register_posix_clock(CLOCK_REALTIME,  &rt_clock);
1150 	register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1151 	p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1152 	p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1153 	p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1154 }
1155 
1156 static int
1157 register_posix_clock(int clockid, const struct kclock *clk)
1158 {
1159 	if ((unsigned)clockid >= MAX_CLOCKS) {
1160 		printf("%s: invalid clockid\n", __func__);
1161 		return (0);
1162 	}
1163 	posix_clocks[clockid] = *clk;
1164 	return (1);
1165 }
1166 
1167 static int
1168 itimer_init(void *mem, int size, int flags)
1169 {
1170 	struct itimer *it;
1171 
1172 	it = (struct itimer *)mem;
1173 	mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1174 	return (0);
1175 }
1176 
1177 static void
1178 itimer_fini(void *mem, int size)
1179 {
1180 	struct itimer *it;
1181 
1182 	it = (struct itimer *)mem;
1183 	mtx_destroy(&it->it_mtx);
1184 }
1185 
1186 static void
1187 itimer_enter(struct itimer *it)
1188 {
1189 
1190 	mtx_assert(&it->it_mtx, MA_OWNED);
1191 	it->it_usecount++;
1192 }
1193 
1194 static void
1195 itimer_leave(struct itimer *it)
1196 {
1197 
1198 	mtx_assert(&it->it_mtx, MA_OWNED);
1199 	KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1200 
1201 	if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1202 		wakeup(it);
1203 }
1204 
1205 #ifndef _SYS_SYSPROTO_H_
1206 struct ktimer_create_args {
1207 	clockid_t clock_id;
1208 	struct sigevent * evp;
1209 	int * timerid;
1210 };
1211 #endif
1212 int
1213 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1214 {
1215 	struct sigevent *evp, ev;
1216 	int id;
1217 	int error;
1218 
1219 	if (uap->evp == NULL) {
1220 		evp = NULL;
1221 	} else {
1222 		error = copyin(uap->evp, &ev, sizeof(ev));
1223 		if (error != 0)
1224 			return (error);
1225 		evp = &ev;
1226 	}
1227 	error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1228 	if (error == 0) {
1229 		error = copyout(&id, uap->timerid, sizeof(int));
1230 		if (error != 0)
1231 			kern_ktimer_delete(td, id);
1232 	}
1233 	return (error);
1234 }
1235 
1236 int
1237 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1238     int *timerid, int preset_id)
1239 {
1240 	struct proc *p = td->td_proc;
1241 	struct itimer *it;
1242 	int id;
1243 	int error;
1244 
1245 	if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1246 		return (EINVAL);
1247 
1248 	if (posix_clocks[clock_id].timer_create == NULL)
1249 		return (EINVAL);
1250 
1251 	if (evp != NULL) {
1252 		if (evp->sigev_notify != SIGEV_NONE &&
1253 		    evp->sigev_notify != SIGEV_SIGNAL &&
1254 		    evp->sigev_notify != SIGEV_THREAD_ID)
1255 			return (EINVAL);
1256 		if ((evp->sigev_notify == SIGEV_SIGNAL ||
1257 		     evp->sigev_notify == SIGEV_THREAD_ID) &&
1258 			!_SIG_VALID(evp->sigev_signo))
1259 			return (EINVAL);
1260 	}
1261 
1262 	if (p->p_itimers == NULL)
1263 		itimers_alloc(p);
1264 
1265 	it = uma_zalloc(itimer_zone, M_WAITOK);
1266 	it->it_flags = 0;
1267 	it->it_usecount = 0;
1268 	it->it_active = 0;
1269 	timespecclear(&it->it_time.it_value);
1270 	timespecclear(&it->it_time.it_interval);
1271 	it->it_overrun = 0;
1272 	it->it_overrun_last = 0;
1273 	it->it_clockid = clock_id;
1274 	it->it_timerid = -1;
1275 	it->it_proc = p;
1276 	ksiginfo_init(&it->it_ksi);
1277 	it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1278 	error = CLOCK_CALL(clock_id, timer_create, (it));
1279 	if (error != 0)
1280 		goto out;
1281 
1282 	PROC_LOCK(p);
1283 	if (preset_id != -1) {
1284 		KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1285 		id = preset_id;
1286 		if (p->p_itimers->its_timers[id] != NULL) {
1287 			PROC_UNLOCK(p);
1288 			error = 0;
1289 			goto out;
1290 		}
1291 	} else {
1292 		/*
1293 		 * Find a free timer slot, skipping those reserved
1294 		 * for setitimer().
1295 		 */
1296 		for (id = 3; id < TIMER_MAX; id++)
1297 			if (p->p_itimers->its_timers[id] == NULL)
1298 				break;
1299 		if (id == TIMER_MAX) {
1300 			PROC_UNLOCK(p);
1301 			error = EAGAIN;
1302 			goto out;
1303 		}
1304 	}
1305 	it->it_timerid = id;
1306 	p->p_itimers->its_timers[id] = it;
1307 	if (evp != NULL)
1308 		it->it_sigev = *evp;
1309 	else {
1310 		it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1311 		switch (clock_id) {
1312 		default:
1313 		case CLOCK_REALTIME:
1314 			it->it_sigev.sigev_signo = SIGALRM;
1315 			break;
1316 		case CLOCK_VIRTUAL:
1317  			it->it_sigev.sigev_signo = SIGVTALRM;
1318 			break;
1319 		case CLOCK_PROF:
1320 			it->it_sigev.sigev_signo = SIGPROF;
1321 			break;
1322 		}
1323 		it->it_sigev.sigev_value.sival_int = id;
1324 	}
1325 
1326 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1327 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1328 		it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1329 		it->it_ksi.ksi_code = SI_TIMER;
1330 		it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1331 		it->it_ksi.ksi_timerid = id;
1332 	}
1333 	PROC_UNLOCK(p);
1334 	*timerid = id;
1335 	return (0);
1336 
1337 out:
1338 	ITIMER_LOCK(it);
1339 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1340 	ITIMER_UNLOCK(it);
1341 	uma_zfree(itimer_zone, it);
1342 	return (error);
1343 }
1344 
1345 #ifndef _SYS_SYSPROTO_H_
1346 struct ktimer_delete_args {
1347 	int timerid;
1348 };
1349 #endif
1350 int
1351 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1352 {
1353 
1354 	return (kern_ktimer_delete(td, uap->timerid));
1355 }
1356 
1357 static struct itimer *
1358 itimer_find(struct proc *p, int timerid)
1359 {
1360 	struct itimer *it;
1361 
1362 	PROC_LOCK_ASSERT(p, MA_OWNED);
1363 	if ((p->p_itimers == NULL) ||
1364 	    (timerid < 0) || (timerid >= TIMER_MAX) ||
1365 	    (it = p->p_itimers->its_timers[timerid]) == NULL) {
1366 		return (NULL);
1367 	}
1368 	ITIMER_LOCK(it);
1369 	if ((it->it_flags & ITF_DELETING) != 0) {
1370 		ITIMER_UNLOCK(it);
1371 		it = NULL;
1372 	}
1373 	return (it);
1374 }
1375 
1376 int
1377 kern_ktimer_delete(struct thread *td, int timerid)
1378 {
1379 	struct proc *p = td->td_proc;
1380 	struct itimer *it;
1381 
1382 	PROC_LOCK(p);
1383 	it = itimer_find(p, timerid);
1384 	if (it == NULL) {
1385 		PROC_UNLOCK(p);
1386 		return (EINVAL);
1387 	}
1388 	PROC_UNLOCK(p);
1389 
1390 	it->it_flags |= ITF_DELETING;
1391 	while (it->it_usecount > 0) {
1392 		it->it_flags |= ITF_WANTED;
1393 		msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1394 	}
1395 	it->it_flags &= ~ITF_WANTED;
1396 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
1397 	ITIMER_UNLOCK(it);
1398 
1399 	PROC_LOCK(p);
1400 	if (KSI_ONQ(&it->it_ksi))
1401 		sigqueue_take(&it->it_ksi);
1402 	p->p_itimers->its_timers[timerid] = NULL;
1403 	PROC_UNLOCK(p);
1404 	uma_zfree(itimer_zone, it);
1405 	return (0);
1406 }
1407 
1408 #ifndef _SYS_SYSPROTO_H_
1409 struct ktimer_settime_args {
1410 	int timerid;
1411 	int flags;
1412 	const struct itimerspec * value;
1413 	struct itimerspec * ovalue;
1414 };
1415 #endif
1416 int
1417 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1418 {
1419 	struct itimerspec val, oval, *ovalp;
1420 	int error;
1421 
1422 	error = copyin(uap->value, &val, sizeof(val));
1423 	if (error != 0)
1424 		return (error);
1425 	ovalp = uap->ovalue != NULL ? &oval : NULL;
1426 	error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1427 	if (error == 0 && uap->ovalue != NULL)
1428 		error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1429 	return (error);
1430 }
1431 
1432 int
1433 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1434     struct itimerspec *val, struct itimerspec *oval)
1435 {
1436 	struct proc *p;
1437 	struct itimer *it;
1438 	int error;
1439 
1440 	p = td->td_proc;
1441 	PROC_LOCK(p);
1442 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1443 		PROC_UNLOCK(p);
1444 		error = EINVAL;
1445 	} else {
1446 		PROC_UNLOCK(p);
1447 		itimer_enter(it);
1448 		error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1449 		    flags, val, oval));
1450 		itimer_leave(it);
1451 		ITIMER_UNLOCK(it);
1452 	}
1453 	return (error);
1454 }
1455 
1456 #ifndef _SYS_SYSPROTO_H_
1457 struct ktimer_gettime_args {
1458 	int timerid;
1459 	struct itimerspec * value;
1460 };
1461 #endif
1462 int
1463 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1464 {
1465 	struct itimerspec val;
1466 	int error;
1467 
1468 	error = kern_ktimer_gettime(td, uap->timerid, &val);
1469 	if (error == 0)
1470 		error = copyout(&val, uap->value, sizeof(val));
1471 	return (error);
1472 }
1473 
1474 int
1475 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1476 {
1477 	struct proc *p;
1478 	struct itimer *it;
1479 	int error;
1480 
1481 	p = td->td_proc;
1482 	PROC_LOCK(p);
1483 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1484 		PROC_UNLOCK(p);
1485 		error = EINVAL;
1486 	} else {
1487 		PROC_UNLOCK(p);
1488 		itimer_enter(it);
1489 		error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1490 		itimer_leave(it);
1491 		ITIMER_UNLOCK(it);
1492 	}
1493 	return (error);
1494 }
1495 
1496 #ifndef _SYS_SYSPROTO_H_
1497 struct timer_getoverrun_args {
1498 	int timerid;
1499 };
1500 #endif
1501 int
1502 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1503 {
1504 
1505 	return (kern_ktimer_getoverrun(td, uap->timerid));
1506 }
1507 
1508 int
1509 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1510 {
1511 	struct proc *p = td->td_proc;
1512 	struct itimer *it;
1513 	int error ;
1514 
1515 	PROC_LOCK(p);
1516 	if (timer_id < 3 ||
1517 	    (it = itimer_find(p, timer_id)) == NULL) {
1518 		PROC_UNLOCK(p);
1519 		error = EINVAL;
1520 	} else {
1521 		td->td_retval[0] = it->it_overrun_last;
1522 		ITIMER_UNLOCK(it);
1523 		PROC_UNLOCK(p);
1524 		error = 0;
1525 	}
1526 	return (error);
1527 }
1528 
1529 static int
1530 realtimer_create(struct itimer *it)
1531 {
1532 	callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1533 	return (0);
1534 }
1535 
1536 static int
1537 realtimer_delete(struct itimer *it)
1538 {
1539 	mtx_assert(&it->it_mtx, MA_OWNED);
1540 
1541 	/*
1542 	 * clear timer's value and interval to tell realtimer_expire
1543 	 * to not rearm the timer.
1544 	 */
1545 	timespecclear(&it->it_time.it_value);
1546 	timespecclear(&it->it_time.it_interval);
1547 	ITIMER_UNLOCK(it);
1548 	callout_drain(&it->it_callout);
1549 	ITIMER_LOCK(it);
1550 	return (0);
1551 }
1552 
1553 static int
1554 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1555 {
1556 	struct timespec cts;
1557 
1558 	mtx_assert(&it->it_mtx, MA_OWNED);
1559 
1560 	realtimer_clocktime(it->it_clockid, &cts);
1561 	*ovalue = it->it_time;
1562 	if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1563 		timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1564 		if (ovalue->it_value.tv_sec < 0 ||
1565 		    (ovalue->it_value.tv_sec == 0 &&
1566 		     ovalue->it_value.tv_nsec == 0)) {
1567 			ovalue->it_value.tv_sec  = 0;
1568 			ovalue->it_value.tv_nsec = 1;
1569 		}
1570 	}
1571 	return (0);
1572 }
1573 
1574 static int
1575 realtimer_settime(struct itimer *it, int flags, struct itimerspec *value,
1576     struct itimerspec *ovalue)
1577 {
1578 	struct timespec cts, ts;
1579 	struct timeval tv;
1580 	struct itimerspec val;
1581 
1582 	mtx_assert(&it->it_mtx, MA_OWNED);
1583 
1584 	val = *value;
1585 	if (itimespecfix(&val.it_value))
1586 		return (EINVAL);
1587 
1588 	if (timespecisset(&val.it_value)) {
1589 		if (itimespecfix(&val.it_interval))
1590 			return (EINVAL);
1591 	} else {
1592 		timespecclear(&val.it_interval);
1593 	}
1594 
1595 	if (ovalue != NULL)
1596 		realtimer_gettime(it, ovalue);
1597 
1598 	it->it_time = val;
1599 	if (timespecisset(&val.it_value)) {
1600 		realtimer_clocktime(it->it_clockid, &cts);
1601 		ts = val.it_value;
1602 		if ((flags & TIMER_ABSTIME) == 0) {
1603 			/* Convert to absolute time. */
1604 			timespecadd(&it->it_time.it_value, &cts,
1605 			    &it->it_time.it_value);
1606 		} else {
1607 			timespecsub(&ts, &cts, &ts);
1608 			/*
1609 			 * We don't care if ts is negative, tztohz will
1610 			 * fix it.
1611 			 */
1612 		}
1613 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
1614 		callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1615 		    it);
1616 	} else {
1617 		callout_stop(&it->it_callout);
1618 	}
1619 
1620 	return (0);
1621 }
1622 
1623 static void
1624 realtimer_clocktime(clockid_t id, struct timespec *ts)
1625 {
1626 	if (id == CLOCK_REALTIME)
1627 		getnanotime(ts);
1628 	else	/* CLOCK_MONOTONIC */
1629 		getnanouptime(ts);
1630 }
1631 
1632 int
1633 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1634 {
1635 	struct itimer *it;
1636 
1637 	PROC_LOCK_ASSERT(p, MA_OWNED);
1638 	it = itimer_find(p, timerid);
1639 	if (it != NULL) {
1640 		ksi->ksi_overrun = it->it_overrun;
1641 		it->it_overrun_last = it->it_overrun;
1642 		it->it_overrun = 0;
1643 		ITIMER_UNLOCK(it);
1644 		return (0);
1645 	}
1646 	return (EINVAL);
1647 }
1648 
1649 static int
1650 itimespecfix(struct timespec *ts)
1651 {
1652 
1653 	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1654 		return (EINVAL);
1655 	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1656 		ts->tv_nsec = tick * 1000;
1657 	return (0);
1658 }
1659 
1660 #define	timespectons(tsp)			\
1661 	((uint64_t)(tsp)->tv_sec * 1000000000 + (tsp)->tv_nsec)
1662 #define	timespecfromns(ns) (struct timespec){	\
1663 	.tv_sec = (ns) / 1000000000,		\
1664 	.tv_nsec = (ns) % 1000000000		\
1665 }
1666 
1667 static void
1668 realtimer_expire_l(struct itimer *it, bool proc_locked)
1669 {
1670 	struct timespec cts, ts;
1671 	struct timeval tv;
1672 	struct proc *p;
1673 	uint64_t interval, now, overruns, value;
1674 
1675 	realtimer_clocktime(it->it_clockid, &cts);
1676 	/* Only fire if time is reached. */
1677 	if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1678 		if (timespecisset(&it->it_time.it_interval)) {
1679 			timespecadd(&it->it_time.it_value,
1680 			    &it->it_time.it_interval,
1681 			    &it->it_time.it_value);
1682 
1683 			interval = timespectons(&it->it_time.it_interval);
1684 			value = timespectons(&it->it_time.it_value);
1685 			now = timespectons(&cts);
1686 
1687 			if (now >= value) {
1688 				/*
1689 				 * We missed at least one period.
1690 				 */
1691 				overruns = howmany(now - value + 1, interval);
1692 				if (it->it_overrun + overruns >=
1693 				    it->it_overrun &&
1694 				    it->it_overrun + overruns <= INT_MAX) {
1695 					it->it_overrun += (int)overruns;
1696 				} else {
1697 					it->it_overrun = INT_MAX;
1698 					it->it_ksi.ksi_errno = ERANGE;
1699 				}
1700 				value =
1701 				    now + interval - (now - value) % interval;
1702 				it->it_time.it_value = timespecfromns(value);
1703 			}
1704 		} else {
1705 			/* single shot timer ? */
1706 			timespecclear(&it->it_time.it_value);
1707 		}
1708 
1709 		p = it->it_proc;
1710 		if (timespecisset(&it->it_time.it_value)) {
1711 			if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1712 				it->it_flags |= ITF_PSTOPPED;
1713 			} else {
1714 				timespecsub(&it->it_time.it_value, &cts, &ts);
1715 				TIMESPEC_TO_TIMEVAL(&tv, &ts);
1716 				callout_reset(&it->it_callout, tvtohz(&tv),
1717 				    realtimer_expire, it);
1718 			}
1719 		}
1720 
1721 		itimer_enter(it);
1722 		ITIMER_UNLOCK(it);
1723 		if (proc_locked)
1724 			PROC_UNLOCK(p);
1725 		itimer_fire(it);
1726 		if (proc_locked)
1727 			PROC_LOCK(p);
1728 		ITIMER_LOCK(it);
1729 		itimer_leave(it);
1730 	} else if (timespecisset(&it->it_time.it_value)) {
1731 		p = it->it_proc;
1732 		if (P_SHOULDSTOP(p) || P_KILLED(p)) {
1733 			it->it_flags |= ITF_PSTOPPED;
1734 		} else {
1735 			ts = it->it_time.it_value;
1736 			timespecsub(&ts, &cts, &ts);
1737 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
1738 			callout_reset(&it->it_callout, tvtohz(&tv),
1739 			    realtimer_expire, it);
1740 		}
1741 	}
1742 }
1743 
1744 /* Timeout callback for realtime timer */
1745 static void
1746 realtimer_expire(void *arg)
1747 {
1748 	realtimer_expire_l(arg, false);
1749 }
1750 
1751 static void
1752 itimer_fire(struct itimer *it)
1753 {
1754 	struct proc *p = it->it_proc;
1755 	struct thread *td;
1756 
1757 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1758 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1759 		if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1760 			ITIMER_LOCK(it);
1761 			timespecclear(&it->it_time.it_value);
1762 			timespecclear(&it->it_time.it_interval);
1763 			callout_stop(&it->it_callout);
1764 			ITIMER_UNLOCK(it);
1765 			return;
1766 		}
1767 		if (!KSI_ONQ(&it->it_ksi)) {
1768 			it->it_ksi.ksi_errno = 0;
1769 			ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1770 			tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1771 		} else {
1772 			if (it->it_overrun < INT_MAX)
1773 				it->it_overrun++;
1774 			else
1775 				it->it_ksi.ksi_errno = ERANGE;
1776 		}
1777 		PROC_UNLOCK(p);
1778 	}
1779 }
1780 
1781 static void
1782 itimers_alloc(struct proc *p)
1783 {
1784 	struct itimers *its;
1785 	int i;
1786 
1787 	its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1788 	LIST_INIT(&its->its_virtual);
1789 	LIST_INIT(&its->its_prof);
1790 	TAILQ_INIT(&its->its_worklist);
1791 	for (i = 0; i < TIMER_MAX; i++)
1792 		its->its_timers[i] = NULL;
1793 	PROC_LOCK(p);
1794 	if (p->p_itimers == NULL) {
1795 		p->p_itimers = its;
1796 		PROC_UNLOCK(p);
1797 	}
1798 	else {
1799 		PROC_UNLOCK(p);
1800 		free(its, M_SUBPROC);
1801 	}
1802 }
1803 
1804 /* Clean up timers when some process events are being triggered. */
1805 static void
1806 itimers_event_exit_exec(int start_idx, struct proc *p)
1807 {
1808 	struct itimers *its;
1809 	struct itimer *it;
1810 	int i;
1811 
1812 	its = p->p_itimers;
1813 	if (its == NULL)
1814 		return;
1815 
1816 	for (i = start_idx; i < TIMER_MAX; ++i) {
1817 		if ((it = its->its_timers[i]) != NULL)
1818 			kern_ktimer_delete(curthread, i);
1819 	}
1820 	if (its->its_timers[0] == NULL && its->its_timers[1] == NULL &&
1821 	    its->its_timers[2] == NULL) {
1822 		free(its, M_SUBPROC);
1823 		p->p_itimers = NULL;
1824 	}
1825 }
1826 
1827 void
1828 itimers_exec(struct proc *p)
1829 {
1830 	/*
1831 	 * According to susv3, XSI interval timers should be inherited
1832 	 * by new image.
1833 	 */
1834 	itimers_event_exit_exec(3, p);
1835 }
1836 
1837 void
1838 itimers_exit(struct proc *p)
1839 {
1840 	itimers_event_exit_exec(0, p);
1841 }
1842