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