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