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