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