xref: /freebsd/sys/kern/kern_time.c (revision cbc108919090590010b44d8f654ca10370013b2c)
19454b2d8SWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1989, 1993
5df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
6df8bae1dSRodney W. Grimes  *
7df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
8df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
9df8bae1dSRodney W. Grimes  * are met:
10df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
11df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
12df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
13df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
14df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
1569a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
16df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
17df8bae1dSRodney W. Grimes  *    without specific prior written permission.
18df8bae1dSRodney W. Grimes  *
19df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
30df8bae1dSRodney W. Grimes  *
31df8bae1dSRodney W. Grimes  *	@(#)kern_time.c	8.1 (Berkeley) 6/10/93
32df8bae1dSRodney W. Grimes  */
33df8bae1dSRodney W. Grimes 
34677b542eSDavid E. O'Brien #include <sys/cdefs.h>
35677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
36677b542eSDavid E. O'Brien 
37de56aee0SKonstantin Belousov #include "opt_ktrace.h"
38de56aee0SKonstantin Belousov 
39df8bae1dSRodney W. Grimes #include <sys/param.h>
40e96c1fdcSPeter Wemm #include <sys/systm.h>
41aff5bcb1SDavid Xu #include <sys/limits.h>
42f645b0b5SPoul-Henning Kamp #include <sys/clock.h>
43fb919e4dSMark Murray #include <sys/lock.h>
44fb919e4dSMark Murray #include <sys/mutex.h>
45d2d3e875SBruce Evans #include <sys/sysproto.h>
46d26b1a1fSDavid Xu #include <sys/eventhandler.h>
47df8bae1dSRodney W. Grimes #include <sys/resourcevar.h>
48797f2d22SPoul-Henning Kamp #include <sys/signalvar.h>
49df8bae1dSRodney W. Grimes #include <sys/kernel.h>
50098176f0SDavide Italiano #include <sys/sleepqueue.h>
51efa42cbcSPaul Saab #include <sys/syscallsubr.h>
5277e718f7SDavid Xu #include <sys/sysctl.h>
5394c8fcd8SPeter Wemm #include <sys/sysent.h>
54acd3428bSRobert Watson #include <sys/priv.h>
55df8bae1dSRodney W. Grimes #include <sys/proc.h>
566aeb05d7STom Rhodes #include <sys/posix4.h>
57708e7684SPeter Wemm #include <sys/time.h>
5886857b36SDavid Xu #include <sys/timers.h>
5991266b96SPoul-Henning Kamp #include <sys/timetc.h>
60df8bae1dSRodney W. Grimes #include <sys/vnode.h>
61de56aee0SKonstantin Belousov #ifdef KTRACE
62de56aee0SKonstantin Belousov #include <sys/ktrace.h>
63de56aee0SKonstantin Belousov #endif
64fb919e4dSMark Murray 
655b870b7bSPeter Wemm #include <vm/vm.h>
665b870b7bSPeter Wemm #include <vm/vm_extern.h>
67df8bae1dSRodney W. Grimes 
6886857b36SDavid Xu #define MAX_CLOCKS 	(CLOCK_MONOTONIC+1)
69d65f1abcSDavid Xu #define CPUCLOCK_BIT		0x80000000
70d65f1abcSDavid Xu #define CPUCLOCK_PROCESS_BIT	0x40000000
71d65f1abcSDavid Xu #define CPUCLOCK_ID_MASK	(~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
72d65f1abcSDavid Xu #define MAKE_THREAD_CPUCLOCK(tid)	(CPUCLOCK_BIT|(tid))
73d65f1abcSDavid Xu #define MAKE_PROCESS_CPUCLOCK(pid)	\
74d65f1abcSDavid Xu 	(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
7586857b36SDavid Xu 
7686857b36SDavid Xu static struct kclock	posix_clocks[MAX_CLOCKS];
7786857b36SDavid Xu static uma_zone_t	itimer_zone = NULL;
7886857b36SDavid Xu 
79df8bae1dSRodney W. Grimes /*
80df8bae1dSRodney W. Grimes  * Time of day and interval timer support.
81df8bae1dSRodney W. Grimes  *
82df8bae1dSRodney W. Grimes  * These routines provide the kernel entry points to get and set
83df8bae1dSRodney W. Grimes  * the time-of-day and per-process interval timers.  Subroutines
84df8bae1dSRodney W. Grimes  * here provide support for adding and subtracting timeval structures
85df8bae1dSRodney W. Grimes  * and decrementing interval timers, optionally reloading the interval
86df8bae1dSRodney W. Grimes  * timers when they expire.
87df8bae1dSRodney W. Grimes  */
88df8bae1dSRodney W. Grimes 
897edfb592SJohn Baldwin static int	settime(struct thread *, struct timeval *);
904d77a549SAlfred Perlstein static void	timevalfix(struct timeval *);
913f8455b0SEric van Gyzen static int	user_clock_nanosleep(struct thread *td, clockid_t clock_id,
923f8455b0SEric van Gyzen 		    int flags, const struct timespec *ua_rqtp,
933f8455b0SEric van Gyzen 		    struct timespec *ua_rmtp);
9494c8fcd8SPeter Wemm 
9586857b36SDavid Xu static void	itimer_start(void);
9686857b36SDavid Xu static int	itimer_init(void *, int, int);
9786857b36SDavid Xu static void	itimer_fini(void *, int);
9886857b36SDavid Xu static void	itimer_enter(struct itimer *);
9986857b36SDavid Xu static void	itimer_leave(struct itimer *);
100843b99c6SDavid Xu static struct itimer *itimer_find(struct proc *, int);
10186857b36SDavid Xu static void	itimers_alloc(struct proc *);
102993182e5SAlexander Leidinger static void	itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
103993182e5SAlexander Leidinger static void	itimers_event_hook_exit(void *arg, struct proc *p);
10486857b36SDavid Xu static int	realtimer_create(struct itimer *);
10586857b36SDavid Xu static int	realtimer_gettime(struct itimer *, struct itimerspec *);
10686857b36SDavid Xu static int	realtimer_settime(struct itimer *, int,
10786857b36SDavid Xu 			struct itimerspec *, struct itimerspec *);
10886857b36SDavid Xu static int	realtimer_delete(struct itimer *);
10956c06c4bSDavid Xu static void	realtimer_clocktime(clockid_t, struct timespec *);
11086857b36SDavid Xu static void	realtimer_expire(void *);
11186857b36SDavid Xu 
11286857b36SDavid Xu int		register_posix_clock(int, struct kclock *);
11386857b36SDavid Xu void		itimer_fire(struct itimer *it);
11456c06c4bSDavid Xu int		itimespecfix(struct timespec *ts);
11586857b36SDavid Xu 
11686857b36SDavid Xu #define CLOCK_CALL(clock, call, arglist)		\
11786857b36SDavid Xu 	((*posix_clocks[clock].call) arglist)
11886857b36SDavid Xu 
11986857b36SDavid Xu SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
12086857b36SDavid Xu 
12194c8fcd8SPeter Wemm static int
12291afe087SPoul-Henning Kamp settime(struct thread *td, struct timeval *tv)
12394c8fcd8SPeter Wemm {
124fcae3aa6SNick Sayer 	struct timeval delta, tv1, tv2;
125c0bd94a7SNick Sayer 	static struct timeval maxtime, laststep;
1267ec73f64SPoul-Henning Kamp 	struct timespec ts;
12794c8fcd8SPeter Wemm 
1289c8fff87SBruce Evans 	microtime(&tv1);
12900af9731SPoul-Henning Kamp 	delta = *tv;
13000af9731SPoul-Henning Kamp 	timevalsub(&delta, &tv1);
13194c8fcd8SPeter Wemm 
13294c8fcd8SPeter Wemm 	/*
1339c8fff87SBruce Evans 	 * If the system is secure, we do not allow the time to be
134fcae3aa6SNick Sayer 	 * set to a value earlier than 1 second less than the highest
135fcae3aa6SNick Sayer 	 * time we have yet seen. The worst a miscreant can do in
136fcae3aa6SNick Sayer 	 * this circumstance is "freeze" time. He couldn't go
137fcae3aa6SNick Sayer 	 * back to the past.
138c0bd94a7SNick Sayer 	 *
139c0bd94a7SNick Sayer 	 * We similarly do not allow the clock to be stepped more
140c0bd94a7SNick Sayer 	 * than one second, nor more than once per second. This allows
141c0bd94a7SNick Sayer 	 * a miscreant to make the clock march double-time, but no worse.
14294c8fcd8SPeter Wemm 	 */
1437edfb592SJohn Baldwin 	if (securelevel_gt(td->td_ucred, 1) != 0) {
144fcae3aa6SNick Sayer 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
1453f92429aSMatt Jacob 			/*
146c0bd94a7SNick Sayer 			 * Update maxtime to latest time we've seen.
1473f92429aSMatt Jacob 			 */
148fcae3aa6SNick Sayer 			if (tv1.tv_sec > maxtime.tv_sec)
149fcae3aa6SNick Sayer 				maxtime = tv1;
150fcae3aa6SNick Sayer 			tv2 = *tv;
151fcae3aa6SNick Sayer 			timevalsub(&tv2, &maxtime);
152fcae3aa6SNick Sayer 			if (tv2.tv_sec < -1) {
1533f92429aSMatt Jacob 				tv->tv_sec = maxtime.tv_sec - 1;
154fcae3aa6SNick Sayer 				printf("Time adjustment clamped to -1 second\n");
155fcae3aa6SNick Sayer 			}
1563f92429aSMatt Jacob 		} else {
1571822421cSKonstantin Belousov 			if (tv1.tv_sec == laststep.tv_sec)
158c0bd94a7SNick Sayer 				return (EPERM);
159c0bd94a7SNick Sayer 			if (delta.tv_sec > 1) {
160c0bd94a7SNick Sayer 				tv->tv_sec = tv1.tv_sec + 1;
161c0bd94a7SNick Sayer 				printf("Time adjustment clamped to +1 second\n");
162c0bd94a7SNick Sayer 			}
163c0bd94a7SNick Sayer 			laststep = *tv;
164fcae3aa6SNick Sayer 		}
1659c8fff87SBruce Evans 	}
1669c8fff87SBruce Evans 
1677ec73f64SPoul-Henning Kamp 	ts.tv_sec = tv->tv_sec;
1687ec73f64SPoul-Henning Kamp 	ts.tv_nsec = tv->tv_usec * 1000;
16991266b96SPoul-Henning Kamp 	tc_setclock(&ts);
17094c8fcd8SPeter Wemm 	resettodr();
17194c8fcd8SPeter Wemm 	return (0);
17294c8fcd8SPeter Wemm }
17394c8fcd8SPeter Wemm 
17494c8fcd8SPeter Wemm #ifndef _SYS_SYSPROTO_H_
175d65f1abcSDavid Xu struct clock_getcpuclockid2_args {
176d65f1abcSDavid Xu 	id_t id;
177d65f1abcSDavid Xu 	int which,
178d65f1abcSDavid Xu 	clockid_t *clock_id;
179d65f1abcSDavid Xu };
180d65f1abcSDavid Xu #endif
181d65f1abcSDavid Xu /* ARGSUSED */
182d65f1abcSDavid Xu int
183d65f1abcSDavid Xu sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
184d65f1abcSDavid Xu {
185d65f1abcSDavid Xu 	clockid_t clk_id;
186d31e4b3aSKonstantin Belousov 	int error;
187d31e4b3aSKonstantin Belousov 
188d31e4b3aSKonstantin Belousov 	error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
189d31e4b3aSKonstantin Belousov 	if (error == 0)
190d31e4b3aSKonstantin Belousov 		error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
191d31e4b3aSKonstantin Belousov 	return (error);
192d31e4b3aSKonstantin Belousov }
193d31e4b3aSKonstantin Belousov 
194d31e4b3aSKonstantin Belousov int
195d31e4b3aSKonstantin Belousov kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
196d31e4b3aSKonstantin Belousov     clockid_t *clk_id)
197d31e4b3aSKonstantin Belousov {
198d65f1abcSDavid Xu 	struct proc *p;
199d65f1abcSDavid Xu 	pid_t pid;
200d65f1abcSDavid Xu 	lwpid_t tid;
201d65f1abcSDavid Xu 	int error;
202d65f1abcSDavid Xu 
203d31e4b3aSKonstantin Belousov 	switch (which) {
204d65f1abcSDavid Xu 	case CPUCLOCK_WHICH_PID:
205d31e4b3aSKonstantin Belousov 		if (id != 0) {
20647ce3e53SDmitry Chagin 			error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
207d31e4b3aSKonstantin Belousov 			if (error != 0)
208d65f1abcSDavid Xu 				return (error);
20947ce3e53SDmitry Chagin 			PROC_UNLOCK(p);
210d31e4b3aSKonstantin Belousov 			pid = id;
211d65f1abcSDavid Xu 		} else {
212d65f1abcSDavid Xu 			pid = td->td_proc->p_pid;
213d65f1abcSDavid Xu 		}
214d31e4b3aSKonstantin Belousov 		*clk_id = MAKE_PROCESS_CPUCLOCK(pid);
215d31e4b3aSKonstantin Belousov 		return (0);
216d65f1abcSDavid Xu 	case CPUCLOCK_WHICH_TID:
217d31e4b3aSKonstantin Belousov 		tid = id == 0 ? td->td_tid : id;
218d31e4b3aSKonstantin Belousov 		*clk_id = MAKE_THREAD_CPUCLOCK(tid);
219d31e4b3aSKonstantin Belousov 		return (0);
220d65f1abcSDavid Xu 	default:
221d65f1abcSDavid Xu 		return (EINVAL);
222d65f1abcSDavid Xu 	}
223d65f1abcSDavid Xu }
224d65f1abcSDavid Xu 
225d65f1abcSDavid Xu #ifndef _SYS_SYSPROTO_H_
22694c8fcd8SPeter Wemm struct clock_gettime_args {
22794c8fcd8SPeter Wemm 	clockid_t clock_id;
22894c8fcd8SPeter Wemm 	struct	timespec *tp;
22994c8fcd8SPeter Wemm };
23094c8fcd8SPeter Wemm #endif
23194c8fcd8SPeter Wemm /* ARGSUSED */
23294c8fcd8SPeter Wemm int
2338451d0ddSKip Macy sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
23494c8fcd8SPeter Wemm {
23594c8fcd8SPeter Wemm 	struct timespec ats;
236f0b479cdSPaul Saab 	int error;
237f0b479cdSPaul Saab 
238f0b479cdSPaul Saab 	error = kern_clock_gettime(td, uap->clock_id, &ats);
239f0b479cdSPaul Saab 	if (error == 0)
240f0b479cdSPaul Saab 		error = copyout(&ats, uap->tp, sizeof(ats));
241f0b479cdSPaul Saab 
242f0b479cdSPaul Saab 	return (error);
243f0b479cdSPaul Saab }
244f0b479cdSPaul Saab 
245d65f1abcSDavid Xu static inline void
246d65f1abcSDavid Xu cputick2timespec(uint64_t runtime, struct timespec *ats)
247d65f1abcSDavid Xu {
248d65f1abcSDavid Xu 	runtime = cputick2usec(runtime);
249d65f1abcSDavid Xu 	ats->tv_sec = runtime / 1000000;
250d65f1abcSDavid Xu 	ats->tv_nsec = runtime % 1000000 * 1000;
251d65f1abcSDavid Xu }
252d65f1abcSDavid Xu 
253*cbc10891SDmitry Chagin void
254*cbc10891SDmitry Chagin kern_thread_cputime(struct thread *targettd, struct timespec *ats)
255d65f1abcSDavid Xu {
256d65f1abcSDavid Xu 	uint64_t runtime, curtime, switchtime;
257*cbc10891SDmitry Chagin 	struct proc *p;
258d65f1abcSDavid Xu 
259d65f1abcSDavid Xu 	if (targettd == NULL) { /* current thread */
260*cbc10891SDmitry Chagin 		p = curthread->td_proc;
261*cbc10891SDmitry Chagin 		PROC_LOCK_ASSERT(p, MA_OWNED);
262d65f1abcSDavid Xu 		critical_enter();
263d65f1abcSDavid Xu 		switchtime = PCPU_GET(switchtime);
264d65f1abcSDavid Xu 		curtime = cpu_ticks();
265d65f1abcSDavid Xu 		runtime = curthread->td_runtime;
266d65f1abcSDavid Xu 		critical_exit();
267d65f1abcSDavid Xu 		runtime += curtime - switchtime;
268d65f1abcSDavid Xu 	} else {
269*cbc10891SDmitry Chagin 		p = targettd->td_proc;
270*cbc10891SDmitry Chagin 		PROC_LOCK_ASSERT(p, MA_OWNED);
271d65f1abcSDavid Xu 		thread_lock(targettd);
272d65f1abcSDavid Xu 		runtime = targettd->td_runtime;
273d65f1abcSDavid Xu 		thread_unlock(targettd);
274d65f1abcSDavid Xu 	}
275d65f1abcSDavid Xu 	cputick2timespec(runtime, ats);
276d65f1abcSDavid Xu }
277d65f1abcSDavid Xu 
278*cbc10891SDmitry Chagin void
279*cbc10891SDmitry Chagin kern_process_cputime(struct proc *targetp, struct timespec *ats)
280d65f1abcSDavid Xu {
281d65f1abcSDavid Xu 	uint64_t runtime;
282d65f1abcSDavid Xu 	struct rusage ru;
283d65f1abcSDavid Xu 
284*cbc10891SDmitry Chagin 	PROC_LOCK_ASSERT(targetp, MA_OWNED);
2855c7bebf9SKonstantin Belousov 	PROC_STATLOCK(targetp);
286d65f1abcSDavid Xu 	rufetch(targetp, &ru);
287d65f1abcSDavid Xu 	runtime = targetp->p_rux.rux_runtime;
2887e8db781SColin Percival 	if (curthread->td_proc == targetp)
2897e8db781SColin Percival 		runtime += cpu_ticks() - PCPU_GET(switchtime);
2905c7bebf9SKonstantin Belousov 	PROC_STATUNLOCK(targetp);
291d65f1abcSDavid Xu 	cputick2timespec(runtime, ats);
292d65f1abcSDavid Xu }
293d65f1abcSDavid Xu 
294d65f1abcSDavid Xu static int
295d65f1abcSDavid Xu get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
296d65f1abcSDavid Xu {
297d65f1abcSDavid Xu 	struct proc *p, *p2;
298d65f1abcSDavid Xu 	struct thread *td2;
299d65f1abcSDavid Xu 	lwpid_t tid;
300d65f1abcSDavid Xu 	pid_t pid;
301d65f1abcSDavid Xu 	int error;
302d65f1abcSDavid Xu 
303d65f1abcSDavid Xu 	p = td->td_proc;
304d65f1abcSDavid Xu 	if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
305d65f1abcSDavid Xu 		tid = clock_id & CPUCLOCK_ID_MASK;
306d65f1abcSDavid Xu 		td2 = tdfind(tid, p->p_pid);
307d65f1abcSDavid Xu 		if (td2 == NULL)
308d65f1abcSDavid Xu 			return (EINVAL);
309*cbc10891SDmitry Chagin 		kern_thread_cputime(td2, ats);
310d65f1abcSDavid Xu 		PROC_UNLOCK(td2->td_proc);
311d65f1abcSDavid Xu 	} else {
312d65f1abcSDavid Xu 		pid = clock_id & CPUCLOCK_ID_MASK;
313c7c536c7SKonstantin Belousov 		error = pget(pid, PGET_CANSEE, &p2);
314c7c536c7SKonstantin Belousov 		if (error != 0)
315d65f1abcSDavid Xu 			return (EINVAL);
316*cbc10891SDmitry Chagin 		kern_process_cputime(p2, ats);
317d65f1abcSDavid Xu 		PROC_UNLOCK(p2);
318d65f1abcSDavid Xu 	}
319d65f1abcSDavid Xu 	return (0);
320d65f1abcSDavid Xu }
321d65f1abcSDavid Xu 
322f0b479cdSPaul Saab int
323f0b479cdSPaul Saab kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
324f0b479cdSPaul Saab {
325de0a9241SKelly Yancey 	struct timeval sys, user;
32678c85e8dSJohn Baldwin 	struct proc *p;
32794c8fcd8SPeter Wemm 
32878c85e8dSJohn Baldwin 	p = td->td_proc;
329f0b479cdSPaul Saab 	switch (clock_id) {
3305e758b95SRobert Watson 	case CLOCK_REALTIME:		/* Default to precise. */
3315e758b95SRobert Watson 	case CLOCK_REALTIME_PRECISE:
332f0b479cdSPaul Saab 		nanotime(ats);
333b8817154SKelly Yancey 		break;
3345e758b95SRobert Watson 	case CLOCK_REALTIME_FAST:
3355e758b95SRobert Watson 		getnanotime(ats);
3365e758b95SRobert Watson 		break;
337b8817154SKelly Yancey 	case CLOCK_VIRTUAL:
33878c85e8dSJohn Baldwin 		PROC_LOCK(p);
3395c7bebf9SKonstantin Belousov 		PROC_STATLOCK(p);
34078c85e8dSJohn Baldwin 		calcru(p, &user, &sys);
3415c7bebf9SKonstantin Belousov 		PROC_STATUNLOCK(p);
34278c85e8dSJohn Baldwin 		PROC_UNLOCK(p);
343f0b479cdSPaul Saab 		TIMEVAL_TO_TIMESPEC(&user, ats);
344b8817154SKelly Yancey 		break;
345b8817154SKelly Yancey 	case CLOCK_PROF:
34678c85e8dSJohn Baldwin 		PROC_LOCK(p);
3475c7bebf9SKonstantin Belousov 		PROC_STATLOCK(p);
34878c85e8dSJohn Baldwin 		calcru(p, &user, &sys);
3495c7bebf9SKonstantin Belousov 		PROC_STATUNLOCK(p);
35078c85e8dSJohn Baldwin 		PROC_UNLOCK(p);
351de0a9241SKelly Yancey 		timevaladd(&user, &sys);
352f0b479cdSPaul Saab 		TIMEVAL_TO_TIMESPEC(&user, ats);
353de0a9241SKelly Yancey 		break;
3545e758b95SRobert Watson 	case CLOCK_MONOTONIC:		/* Default to precise. */
3555e758b95SRobert Watson 	case CLOCK_MONOTONIC_PRECISE:
3565eefd889SAndre Oppermann 	case CLOCK_UPTIME:
3575e758b95SRobert Watson 	case CLOCK_UPTIME_PRECISE:
358f0b479cdSPaul Saab 		nanouptime(ats);
359b8817154SKelly Yancey 		break;
3605e758b95SRobert Watson 	case CLOCK_UPTIME_FAST:
3615e758b95SRobert Watson 	case CLOCK_MONOTONIC_FAST:
3625e758b95SRobert Watson 		getnanouptime(ats);
3635e758b95SRobert Watson 		break;
3645e758b95SRobert Watson 	case CLOCK_SECOND:
3655e758b95SRobert Watson 		ats->tv_sec = time_second;
3665e758b95SRobert Watson 		ats->tv_nsec = 0;
3675e758b95SRobert Watson 		break;
36800d6ac63SDavid Xu 	case CLOCK_THREAD_CPUTIME_ID:
369*cbc10891SDmitry Chagin 		kern_thread_cputime(NULL, ats);
370d65f1abcSDavid Xu 		break;
371d65f1abcSDavid Xu 	case CLOCK_PROCESS_CPUTIME_ID:
372d65f1abcSDavid Xu 		PROC_LOCK(p);
373*cbc10891SDmitry Chagin 		kern_process_cputime(p, ats);
374d65f1abcSDavid Xu 		PROC_UNLOCK(p);
37500d6ac63SDavid Xu 		break;
376b8817154SKelly Yancey 	default:
377d65f1abcSDavid Xu 		if ((int)clock_id >= 0)
3785cb3dc8fSPoul-Henning Kamp 			return (EINVAL);
379d65f1abcSDavid Xu 		return (get_cputime(td, clock_id, ats));
380b8817154SKelly Yancey 	}
381f0b479cdSPaul Saab 	return (0);
38294c8fcd8SPeter Wemm }
38394c8fcd8SPeter Wemm 
38494c8fcd8SPeter Wemm #ifndef _SYS_SYSPROTO_H_
38594c8fcd8SPeter Wemm struct clock_settime_args {
38694c8fcd8SPeter Wemm 	clockid_t clock_id;
38794c8fcd8SPeter Wemm 	const struct	timespec *tp;
38894c8fcd8SPeter Wemm };
38994c8fcd8SPeter Wemm #endif
39094c8fcd8SPeter Wemm /* ARGSUSED */
39194c8fcd8SPeter Wemm int
3928451d0ddSKip Macy sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
39394c8fcd8SPeter Wemm {
39494c8fcd8SPeter Wemm 	struct timespec ats;
39594c8fcd8SPeter Wemm 	int error;
39694c8fcd8SPeter Wemm 
397f0b479cdSPaul Saab 	if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
398f0b479cdSPaul Saab 		return (error);
399f0b479cdSPaul Saab 	return (kern_clock_settime(td, uap->clock_id, &ats));
400f0b479cdSPaul Saab }
401f0b479cdSPaul Saab 
40290a79ac5SConrad Meyer static int allow_insane_settime = 0;
40390a79ac5SConrad Meyer SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
40490a79ac5SConrad Meyer     &allow_insane_settime, 0,
40590a79ac5SConrad Meyer     "do not perform possibly restrictive checks on settime(2) args");
40690a79ac5SConrad Meyer 
407f0b479cdSPaul Saab int
408f0b479cdSPaul Saab kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
409f0b479cdSPaul Saab {
410f0b479cdSPaul Saab 	struct timeval atv;
411f0b479cdSPaul Saab 	int error;
412f0b479cdSPaul Saab 
413acd3428bSRobert Watson 	if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
4147edfb592SJohn Baldwin 		return (error);
415f0b479cdSPaul Saab 	if (clock_id != CLOCK_REALTIME)
4167edfb592SJohn Baldwin 		return (EINVAL);
4173e18d701SDmitry Chagin 	if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
4183e18d701SDmitry Chagin 	    ats->tv_sec < 0)
4197edfb592SJohn Baldwin 		return (EINVAL);
420bc79b41cSMark Johnston 	if (!allow_insane_settime &&
421bc79b41cSMark Johnston 	    (ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60 ||
422bc79b41cSMark Johnston 	    ats->tv_sec < utc_offset()))
42390a79ac5SConrad Meyer 		return (EINVAL);
424a0502b19SPoul-Henning Kamp 	/* XXX Don't convert nsec->usec and back */
425f0b479cdSPaul Saab 	TIMESPEC_TO_TIMEVAL(&atv, ats);
4267edfb592SJohn Baldwin 	error = settime(td, &atv);
42794c8fcd8SPeter Wemm 	return (error);
42894c8fcd8SPeter Wemm }
42994c8fcd8SPeter Wemm 
43094c8fcd8SPeter Wemm #ifndef _SYS_SYSPROTO_H_
43194c8fcd8SPeter Wemm struct clock_getres_args {
43294c8fcd8SPeter Wemm 	clockid_t clock_id;
43394c8fcd8SPeter Wemm 	struct	timespec *tp;
43494c8fcd8SPeter Wemm };
43594c8fcd8SPeter Wemm #endif
43694c8fcd8SPeter Wemm int
4378451d0ddSKip Macy sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
43894c8fcd8SPeter Wemm {
43994c8fcd8SPeter Wemm 	struct timespec ts;
440f0b479cdSPaul Saab 	int error;
44194c8fcd8SPeter Wemm 
442f0b479cdSPaul Saab 	if (uap->tp == NULL)
443f0b479cdSPaul Saab 		return (0);
444f0b479cdSPaul Saab 
445f0b479cdSPaul Saab 	error = kern_clock_getres(td, uap->clock_id, &ts);
446f0b479cdSPaul Saab 	if (error == 0)
447f0b479cdSPaul Saab 		error = copyout(&ts, uap->tp, sizeof(ts));
448f0b479cdSPaul Saab 	return (error);
449f0b479cdSPaul Saab }
450f0b479cdSPaul Saab 
451f0b479cdSPaul Saab int
452f0b479cdSPaul Saab kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
453f0b479cdSPaul Saab {
454f0b479cdSPaul Saab 
455f0b479cdSPaul Saab 	ts->tv_sec = 0;
456f0b479cdSPaul Saab 	switch (clock_id) {
457b8817154SKelly Yancey 	case CLOCK_REALTIME:
4585e758b95SRobert Watson 	case CLOCK_REALTIME_FAST:
4595e758b95SRobert Watson 	case CLOCK_REALTIME_PRECISE:
460b8817154SKelly Yancey 	case CLOCK_MONOTONIC:
4615e758b95SRobert Watson 	case CLOCK_MONOTONIC_FAST:
4625e758b95SRobert Watson 	case CLOCK_MONOTONIC_PRECISE:
4635eefd889SAndre Oppermann 	case CLOCK_UPTIME:
4645e758b95SRobert Watson 	case CLOCK_UPTIME_FAST:
4655e758b95SRobert Watson 	case CLOCK_UPTIME_PRECISE:
466ac0653dcSBruce Evans 		/*
467ac0653dcSBruce Evans 		 * Round up the result of the division cheaply by adding 1.
468ac0653dcSBruce Evans 		 * Rounding up is especially important if rounding down
469ac0653dcSBruce Evans 		 * would give 0.  Perfect rounding is unimportant.
470ac0653dcSBruce Evans 		 */
471f0b479cdSPaul Saab 		ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
472b8817154SKelly Yancey 		break;
473b8817154SKelly Yancey 	case CLOCK_VIRTUAL:
474b8817154SKelly Yancey 	case CLOCK_PROF:
475b8817154SKelly Yancey 		/* Accurately round up here because we can do so cheaply. */
47655e0987aSPedro F. Giffuni 		ts->tv_nsec = howmany(1000000000, hz);
477b8817154SKelly Yancey 		break;
4785e758b95SRobert Watson 	case CLOCK_SECOND:
4795e758b95SRobert Watson 		ts->tv_sec = 1;
4805e758b95SRobert Watson 		ts->tv_nsec = 0;
4815e758b95SRobert Watson 		break;
48200d6ac63SDavid Xu 	case CLOCK_THREAD_CPUTIME_ID:
483d65f1abcSDavid Xu 	case CLOCK_PROCESS_CPUTIME_ID:
484d65f1abcSDavid Xu 	cputime:
48500d6ac63SDavid Xu 		/* sync with cputick2usec */
48600d6ac63SDavid Xu 		ts->tv_nsec = 1000000 / cpu_tickrate();
48700d6ac63SDavid Xu 		if (ts->tv_nsec == 0)
48800d6ac63SDavid Xu 			ts->tv_nsec = 1000;
48900d6ac63SDavid Xu 		break;
490b8817154SKelly Yancey 	default:
491d65f1abcSDavid Xu 		if ((int)clock_id < 0)
492d65f1abcSDavid Xu 			goto cputime;
493b8817154SKelly Yancey 		return (EINVAL);
49494c8fcd8SPeter Wemm 	}
495de0a9241SKelly Yancey 	return (0);
49694c8fcd8SPeter Wemm }
49794c8fcd8SPeter Wemm 
4987fdf2c85SPaul Saab int
4997fdf2c85SPaul Saab kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
5005b870b7bSPeter Wemm {
5013f8455b0SEric van Gyzen 
5023f8455b0SEric van Gyzen 	return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
5033f8455b0SEric van Gyzen 	    rmt));
5043f8455b0SEric van Gyzen }
5053f8455b0SEric van Gyzen 
5063f8455b0SEric van Gyzen static uint8_t nanowait[MAXCPU];
5073f8455b0SEric van Gyzen 
5083f8455b0SEric van Gyzen int
5093f8455b0SEric van Gyzen kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
5103f8455b0SEric van Gyzen     const struct timespec *rqt, struct timespec *rmt)
5113f8455b0SEric van Gyzen {
5123f8455b0SEric van Gyzen 	struct timespec ts, now;
513098176f0SDavide Italiano 	sbintime_t sbt, sbtt, prec, tmp;
514980c545dSAlexander Motin 	time_t over;
51533841826SPoul-Henning Kamp 	int error;
5163f8455b0SEric van Gyzen 	bool is_abs_real;
5175b870b7bSPeter Wemm 
5187d7fb492SBruce Evans 	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
519708e7684SPeter Wemm 		return (EINVAL);
5203f8455b0SEric van Gyzen 	if ((flags & ~TIMER_ABSTIME) != 0)
5213f8455b0SEric van Gyzen 		return (EINVAL);
5223f8455b0SEric van Gyzen 	switch (clock_id) {
5233f8455b0SEric van Gyzen 	case CLOCK_REALTIME:
5243f8455b0SEric van Gyzen 	case CLOCK_REALTIME_PRECISE:
5253f8455b0SEric van Gyzen 	case CLOCK_REALTIME_FAST:
5263f8455b0SEric van Gyzen 	case CLOCK_SECOND:
5273f8455b0SEric van Gyzen 		is_abs_real = (flags & TIMER_ABSTIME) != 0;
5283f8455b0SEric van Gyzen 		break;
5293f8455b0SEric van Gyzen 	case CLOCK_MONOTONIC:
5303f8455b0SEric van Gyzen 	case CLOCK_MONOTONIC_PRECISE:
5313f8455b0SEric van Gyzen 	case CLOCK_MONOTONIC_FAST:
5323f8455b0SEric van Gyzen 	case CLOCK_UPTIME:
5333f8455b0SEric van Gyzen 	case CLOCK_UPTIME_PRECISE:
5343f8455b0SEric van Gyzen 	case CLOCK_UPTIME_FAST:
5353f8455b0SEric van Gyzen 		is_abs_real = false;
5363f8455b0SEric van Gyzen 		break;
5373f8455b0SEric van Gyzen 	case CLOCK_VIRTUAL:
5383f8455b0SEric van Gyzen 	case CLOCK_PROF:
5393f8455b0SEric van Gyzen 	case CLOCK_PROCESS_CPUTIME_ID:
5403f8455b0SEric van Gyzen 		return (ENOTSUP);
5413f8455b0SEric van Gyzen 	case CLOCK_THREAD_CPUTIME_ID:
5423f8455b0SEric van Gyzen 	default:
5433f8455b0SEric van Gyzen 		return (EINVAL);
5443f8455b0SEric van Gyzen 	}
5453f8455b0SEric van Gyzen 	do {
546980c545dSAlexander Motin 		ts = *rqt;
5473f8455b0SEric van Gyzen 		if ((flags & TIMER_ABSTIME) != 0) {
5483f8455b0SEric van Gyzen 			if (is_abs_real)
5493f8455b0SEric van Gyzen 				td->td_rtcgen =
5503f8455b0SEric van Gyzen 				    atomic_load_acq_int(&rtc_generation);
5513f8455b0SEric van Gyzen 			error = kern_clock_gettime(td, clock_id, &now);
5523f8455b0SEric van Gyzen 			KASSERT(error == 0, ("kern_clock_gettime: %d", error));
5536040822cSAlan Somers 			timespecsub(&ts, &now, &ts);
5543f8455b0SEric van Gyzen 		}
5553f8455b0SEric van Gyzen 		if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
5563f8455b0SEric van Gyzen 			error = EWOULDBLOCK;
5573f8455b0SEric van Gyzen 			break;
5583f8455b0SEric van Gyzen 		}
559980c545dSAlexander Motin 		if (ts.tv_sec > INT32_MAX / 2) {
560980c545dSAlexander Motin 			over = ts.tv_sec - INT32_MAX / 2;
561980c545dSAlexander Motin 			ts.tv_sec -= over;
562980c545dSAlexander Motin 		} else
563980c545dSAlexander Motin 			over = 0;
564980c545dSAlexander Motin 		tmp = tstosbt(ts);
565098176f0SDavide Italiano 		prec = tmp;
566098176f0SDavide Italiano 		prec >>= tc_precexp;
567098176f0SDavide Italiano 		if (TIMESEL(&sbt, tmp))
568098176f0SDavide Italiano 			sbt += tc_tick_sbt;
569098176f0SDavide Italiano 		sbt += tmp;
5700dbf17e6SAlexander Motin 		error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
5710dbf17e6SAlexander Motin 		    sbt, prec, C_ABSOLUTE);
5723f8455b0SEric van Gyzen 	} while (error == 0 && is_abs_real && td->td_rtcgen == 0);
5733f8455b0SEric van Gyzen 	td->td_rtcgen = 0;
57433841826SPoul-Henning Kamp 	if (error != EWOULDBLOCK) {
57570c144dcSBryan Drewery 		if (TIMESEL(&sbtt, tmp))
57670c144dcSBryan Drewery 			sbtt += tc_tick_sbt;
5773f8455b0SEric van Gyzen 		if (sbtt >= sbt)
5783f8455b0SEric van Gyzen 			return (0);
57933841826SPoul-Henning Kamp 		if (error == ERESTART)
58094c8fcd8SPeter Wemm 			error = EINTR;
5813f8455b0SEric van Gyzen 		if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
582098176f0SDavide Italiano 			ts = sbttots(sbt - sbtt);
583980c545dSAlexander Motin 			ts.tv_sec += over;
58433841826SPoul-Henning Kamp 			if (ts.tv_sec < 0)
58533841826SPoul-Henning Kamp 				timespecclear(&ts);
58600af9731SPoul-Henning Kamp 			*rmt = ts;
58700af9731SPoul-Henning Kamp 		}
58833841826SPoul-Henning Kamp 		return (error);
58933841826SPoul-Henning Kamp 	}
59033841826SPoul-Henning Kamp 	return (0);
5915b870b7bSPeter Wemm }
59294c8fcd8SPeter Wemm 
5935b870b7bSPeter Wemm #ifndef _SYS_SYSPROTO_H_
5945b870b7bSPeter Wemm struct nanosleep_args {
5955b870b7bSPeter Wemm 	struct	timespec *rqtp;
5965b870b7bSPeter Wemm 	struct	timespec *rmtp;
5975b870b7bSPeter Wemm };
5985b870b7bSPeter Wemm #endif
5995b870b7bSPeter Wemm /* ARGSUSED */
6005b870b7bSPeter Wemm int
6018451d0ddSKip Macy sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
6025b870b7bSPeter Wemm {
6033f8455b0SEric van Gyzen 
6043f8455b0SEric van Gyzen 	return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
6053f8455b0SEric van Gyzen 	    uap->rqtp, uap->rmtp));
6063f8455b0SEric van Gyzen }
6073f8455b0SEric van Gyzen 
6083f8455b0SEric van Gyzen #ifndef _SYS_SYSPROTO_H_
6093f8455b0SEric van Gyzen struct clock_nanosleep_args {
6103f8455b0SEric van Gyzen 	clockid_t clock_id;
6113f8455b0SEric van Gyzen 	int 	  flags;
6123f8455b0SEric van Gyzen 	struct	timespec *rqtp;
6133f8455b0SEric van Gyzen 	struct	timespec *rmtp;
6143f8455b0SEric van Gyzen };
6153f8455b0SEric van Gyzen #endif
6163f8455b0SEric van Gyzen /* ARGSUSED */
6173f8455b0SEric van Gyzen int
6183f8455b0SEric van Gyzen sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
6193f8455b0SEric van Gyzen {
6203f8455b0SEric van Gyzen 	int error;
6213f8455b0SEric van Gyzen 
6223f8455b0SEric van Gyzen 	error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
6233f8455b0SEric van Gyzen 	    uap->rmtp);
6243f8455b0SEric van Gyzen 	return (kern_posix_error(td, error));
6253f8455b0SEric van Gyzen }
6263f8455b0SEric van Gyzen 
6273f8455b0SEric van Gyzen static int
6283f8455b0SEric van Gyzen user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
6293f8455b0SEric van Gyzen     const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
6303f8455b0SEric van Gyzen {
6315b870b7bSPeter Wemm 	struct timespec rmt, rqt;
632fb99ab88SMatthew Dillon 	int error;
6335b870b7bSPeter Wemm 
6343f8455b0SEric van Gyzen 	error = copyin(ua_rqtp, &rqt, sizeof(rqt));
6355b870b7bSPeter Wemm 	if (error)
6365b870b7bSPeter Wemm 		return (error);
6373f8455b0SEric van Gyzen 	if (ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0 &&
6383f8455b0SEric van Gyzen 	    !useracc(ua_rmtp, sizeof(rmt), VM_PROT_WRITE))
63931f3e2adSAlfred Perlstein 		return (EFAULT);
6403f8455b0SEric van Gyzen 	error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
6413f8455b0SEric van Gyzen 	if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
642fb99ab88SMatthew Dillon 		int error2;
643fb99ab88SMatthew Dillon 
6443f8455b0SEric van Gyzen 		error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
64531f3e2adSAlfred Perlstein 		if (error2)
646fb99ab88SMatthew Dillon 			error = error2;
647708e7684SPeter Wemm 	}
648708e7684SPeter Wemm 	return (error);
64994c8fcd8SPeter Wemm }
65094c8fcd8SPeter Wemm 
6515b870b7bSPeter Wemm #ifndef _SYS_SYSPROTO_H_
652df8bae1dSRodney W. Grimes struct gettimeofday_args {
653df8bae1dSRodney W. Grimes 	struct	timeval *tp;
654df8bae1dSRodney W. Grimes 	struct	timezone *tzp;
655df8bae1dSRodney W. Grimes };
656d2d3e875SBruce Evans #endif
657df8bae1dSRodney W. Grimes /* ARGSUSED */
65826f9a767SRodney W. Grimes int
6598451d0ddSKip Macy sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
660df8bae1dSRodney W. Grimes {
661df8bae1dSRodney W. Grimes 	struct timeval atv;
662411c25edSTim J. Robbins 	struct timezone rtz;
663df8bae1dSRodney W. Grimes 	int error = 0;
664df8bae1dSRodney W. Grimes 
665df8bae1dSRodney W. Grimes 	if (uap->tp) {
666df8bae1dSRodney W. Grimes 		microtime(&atv);
66701609114SAlfred Perlstein 		error = copyout(&atv, uap->tp, sizeof (atv));
668df8bae1dSRodney W. Grimes 	}
66921dcdb38SPoul-Henning Kamp 	if (error == 0 && uap->tzp != NULL) {
670329f0aa9SWarner Losh 		rtz.tz_minuteswest = 0;
671329f0aa9SWarner Losh 		rtz.tz_dsttime = 0;
672411c25edSTim J. Robbins 		error = copyout(&rtz, uap->tzp, sizeof (rtz));
67321dcdb38SPoul-Henning Kamp 	}
674df8bae1dSRodney W. Grimes 	return (error);
675df8bae1dSRodney W. Grimes }
676df8bae1dSRodney W. Grimes 
677d2d3e875SBruce Evans #ifndef _SYS_SYSPROTO_H_
678df8bae1dSRodney W. Grimes struct settimeofday_args {
679df8bae1dSRodney W. Grimes 	struct	timeval *tv;
680df8bae1dSRodney W. Grimes 	struct	timezone *tzp;
681df8bae1dSRodney W. Grimes };
682d2d3e875SBruce Evans #endif
683df8bae1dSRodney W. Grimes /* ARGSUSED */
68426f9a767SRodney W. Grimes int
6858451d0ddSKip Macy sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
686df8bae1dSRodney W. Grimes {
687b88ec951SJohn Baldwin 	struct timeval atv, *tvp;
688b88ec951SJohn Baldwin 	struct timezone atz, *tzp;
689b88ec951SJohn Baldwin 	int error;
690b88ec951SJohn Baldwin 
691b88ec951SJohn Baldwin 	if (uap->tv) {
692b88ec951SJohn Baldwin 		error = copyin(uap->tv, &atv, sizeof(atv));
693b88ec951SJohn Baldwin 		if (error)
694b88ec951SJohn Baldwin 			return (error);
695b88ec951SJohn Baldwin 		tvp = &atv;
696b88ec951SJohn Baldwin 	} else
697b88ec951SJohn Baldwin 		tvp = NULL;
698b88ec951SJohn Baldwin 	if (uap->tzp) {
699b88ec951SJohn Baldwin 		error = copyin(uap->tzp, &atz, sizeof(atz));
700b88ec951SJohn Baldwin 		if (error)
701b88ec951SJohn Baldwin 			return (error);
702b88ec951SJohn Baldwin 		tzp = &atz;
703b88ec951SJohn Baldwin 	} else
704b88ec951SJohn Baldwin 		tzp = NULL;
705b88ec951SJohn Baldwin 	return (kern_settimeofday(td, tvp, tzp));
706b88ec951SJohn Baldwin }
707b88ec951SJohn Baldwin 
708b88ec951SJohn Baldwin int
709b88ec951SJohn Baldwin kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
710b88ec951SJohn Baldwin {
711b88ec951SJohn Baldwin 	int error;
712fb99ab88SMatthew Dillon 
713acd3428bSRobert Watson 	error = priv_check(td, PRIV_SETTIMEOFDAY);
714b88ec951SJohn Baldwin 	if (error)
7157edfb592SJohn Baldwin 		return (error);
716df8bae1dSRodney W. Grimes 	/* Verify all parameters before changing time. */
717b88ec951SJohn Baldwin 	if (tv) {
7183e18d701SDmitry Chagin 		if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
7193e18d701SDmitry Chagin 		    tv->tv_sec < 0)
7207edfb592SJohn Baldwin 			return (EINVAL);
721b88ec951SJohn Baldwin 		error = settime(td, tv);
722708e7684SPeter Wemm 	}
7237edfb592SJohn Baldwin 	return (error);
724b88ec951SJohn Baldwin }
7257edfb592SJohn Baldwin 
726df8bae1dSRodney W. Grimes /*
727873fbcd7SRobert Watson  * Get value of an interval timer.  The process virtual and profiling virtual
728873fbcd7SRobert Watson  * time timers are kept in the p_stats area, since they can be swapped out.
729873fbcd7SRobert Watson  * These are kept internally in the way they are specified externally: in
730873fbcd7SRobert Watson  * time until they expire.
731df8bae1dSRodney W. Grimes  *
732873fbcd7SRobert Watson  * The real time interval timer is kept in the process table slot for the
733873fbcd7SRobert Watson  * process, and its value (it_value) is kept as an absolute time rather than
734873fbcd7SRobert Watson  * as a delta, so that it is easy to keep periodic real-time signals from
735873fbcd7SRobert Watson  * drifting.
736df8bae1dSRodney W. Grimes  *
737df8bae1dSRodney W. Grimes  * Virtual time timers are processed in the hardclock() routine of
738873fbcd7SRobert Watson  * kern_clock.c.  The real time timer is processed by a timeout routine,
739873fbcd7SRobert Watson  * called from the softclock() routine.  Since a callout may be delayed in
740873fbcd7SRobert Watson  * real time due to interrupt processing in the system, it is possible for
741873fbcd7SRobert Watson  * the real time timeout routine (realitexpire, given below), to be delayed
742873fbcd7SRobert Watson  * in real time past when it is supposed to occur.  It does not suffice,
743873fbcd7SRobert Watson  * therefore, to reload the real timer .it_value from the real time timers
744873fbcd7SRobert Watson  * .it_interval.  Rather, we compute the next time in absolute time the timer
745873fbcd7SRobert Watson  * should go off.
746df8bae1dSRodney W. Grimes  */
747d2d3e875SBruce Evans #ifndef _SYS_SYSPROTO_H_
748df8bae1dSRodney W. Grimes struct getitimer_args {
749df8bae1dSRodney W. Grimes 	u_int	which;
750df8bae1dSRodney W. Grimes 	struct	itimerval *itv;
751df8bae1dSRodney W. Grimes };
752d2d3e875SBruce Evans #endif
75326f9a767SRodney W. Grimes int
7548451d0ddSKip Macy sys_getitimer(struct thread *td, struct getitimer_args *uap)
755df8bae1dSRodney W. Grimes {
756df8bae1dSRodney W. Grimes 	struct itimerval aitv;
757c90110d6SJohn Baldwin 	int error;
758df8bae1dSRodney W. Grimes 
759cfa0efe7SMaxim Sobolev 	error = kern_getitimer(td, uap->which, &aitv);
760cfa0efe7SMaxim Sobolev 	if (error != 0)
761cfa0efe7SMaxim Sobolev 		return (error);
762cfa0efe7SMaxim Sobolev 	return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
763cfa0efe7SMaxim Sobolev }
764cfa0efe7SMaxim Sobolev 
765cfa0efe7SMaxim Sobolev int
766cfa0efe7SMaxim Sobolev kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
767cfa0efe7SMaxim Sobolev {
768cfa0efe7SMaxim Sobolev 	struct proc *p = td->td_proc;
769cfa0efe7SMaxim Sobolev 	struct timeval ctv;
770cfa0efe7SMaxim Sobolev 
771cfa0efe7SMaxim Sobolev 	if (which > ITIMER_PROF)
772df8bae1dSRodney W. Grimes 		return (EINVAL);
773fb99ab88SMatthew Dillon 
774cfa0efe7SMaxim Sobolev 	if (which == ITIMER_REAL) {
775df8bae1dSRodney W. Grimes 		/*
776ee002b68SBruce Evans 		 * Convert from absolute to relative time in .it_value
777df8bae1dSRodney W. Grimes 		 * part of real time timer.  If time for real time timer
778df8bae1dSRodney W. Grimes 		 * has passed return 0, else return difference between
779df8bae1dSRodney W. Grimes 		 * current time and time for the timer to go off.
780df8bae1dSRodney W. Grimes 		 */
78196d7f8efSTim J. Robbins 		PROC_LOCK(p);
782cfa0efe7SMaxim Sobolev 		*aitv = p->p_realtimer;
78396d7f8efSTim J. Robbins 		PROC_UNLOCK(p);
784cfa0efe7SMaxim Sobolev 		if (timevalisset(&aitv->it_value)) {
785b5ea3779SAlexander Motin 			microuptime(&ctv);
786cfa0efe7SMaxim Sobolev 			if (timevalcmp(&aitv->it_value, &ctv, <))
787cfa0efe7SMaxim Sobolev 				timevalclear(&aitv->it_value);
788df8bae1dSRodney W. Grimes 			else
789cfa0efe7SMaxim Sobolev 				timevalsub(&aitv->it_value, &ctv);
790227ee8a1SPoul-Henning Kamp 		}
791fb99ab88SMatthew Dillon 	} else {
7925c7bebf9SKonstantin Belousov 		PROC_ITIMLOCK(p);
793cfa0efe7SMaxim Sobolev 		*aitv = p->p_stats->p_timer[which];
7945c7bebf9SKonstantin Belousov 		PROC_ITIMUNLOCK(p);
795fb99ab88SMatthew Dillon 	}
796de56aee0SKonstantin Belousov #ifdef KTRACE
797de56aee0SKonstantin Belousov 	if (KTRPOINT(td, KTR_STRUCT))
798de56aee0SKonstantin Belousov 		ktritimerval(aitv);
799de56aee0SKonstantin Belousov #endif
800cfa0efe7SMaxim Sobolev 	return (0);
801df8bae1dSRodney W. Grimes }
802df8bae1dSRodney W. Grimes 
803d2d3e875SBruce Evans #ifndef _SYS_SYSPROTO_H_
804df8bae1dSRodney W. Grimes struct setitimer_args {
805df8bae1dSRodney W. Grimes 	u_int	which;
806df8bae1dSRodney W. Grimes 	struct	itimerval *itv, *oitv;
807df8bae1dSRodney W. Grimes };
808d2d3e875SBruce Evans #endif
80926f9a767SRodney W. Grimes int
8108451d0ddSKip Macy sys_setitimer(struct thread *td, struct setitimer_args *uap)
811df8bae1dSRodney W. Grimes {
812cfa0efe7SMaxim Sobolev 	struct itimerval aitv, oitv;
813c90110d6SJohn Baldwin 	int error;
81496d7f8efSTim J. Robbins 
81596d7f8efSTim J. Robbins 	if (uap->itv == NULL) {
81696d7f8efSTim J. Robbins 		uap->itv = uap->oitv;
8178451d0ddSKip Macy 		return (sys_getitimer(td, (struct getitimer_args *)uap));
81896d7f8efSTim J. Robbins 	}
819df8bae1dSRodney W. Grimes 
82096d7f8efSTim J. Robbins 	if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
821df8bae1dSRodney W. Grimes 		return (error);
822cfa0efe7SMaxim Sobolev 	error = kern_setitimer(td, uap->which, &aitv, &oitv);
823cfa0efe7SMaxim Sobolev 	if (error != 0 || uap->oitv == NULL)
824cfa0efe7SMaxim Sobolev 		return (error);
825cfa0efe7SMaxim Sobolev 	return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
826cfa0efe7SMaxim Sobolev }
827cfa0efe7SMaxim Sobolev 
828cfa0efe7SMaxim Sobolev int
829c90110d6SJohn Baldwin kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
830c90110d6SJohn Baldwin     struct itimerval *oitv)
831cfa0efe7SMaxim Sobolev {
832cfa0efe7SMaxim Sobolev 	struct proc *p = td->td_proc;
833cfa0efe7SMaxim Sobolev 	struct timeval ctv;
834b5ea3779SAlexander Motin 	sbintime_t sbt, pr;
835cfa0efe7SMaxim Sobolev 
8365e85ac17SJohn Baldwin 	if (aitv == NULL)
8375e85ac17SJohn Baldwin 		return (kern_getitimer(td, which, oitv));
8385e85ac17SJohn Baldwin 
839cfa0efe7SMaxim Sobolev 	if (which > ITIMER_PROF)
84096d7f8efSTim J. Robbins 		return (EINVAL);
841de56aee0SKonstantin Belousov #ifdef KTRACE
842de56aee0SKonstantin Belousov 	if (KTRPOINT(td, KTR_STRUCT))
843de56aee0SKonstantin Belousov 		ktritimerval(aitv);
844de56aee0SKonstantin Belousov #endif
845b5ea3779SAlexander Motin 	if (itimerfix(&aitv->it_value) ||
846b5ea3779SAlexander Motin 	    aitv->it_value.tv_sec > INT32_MAX / 2)
847cfa0efe7SMaxim Sobolev 		return (EINVAL);
848cfa0efe7SMaxim Sobolev 	if (!timevalisset(&aitv->it_value))
849cfa0efe7SMaxim Sobolev 		timevalclear(&aitv->it_interval);
850b5ea3779SAlexander Motin 	else if (itimerfix(&aitv->it_interval) ||
851b5ea3779SAlexander Motin 	    aitv->it_interval.tv_sec > INT32_MAX / 2)
85296d7f8efSTim J. Robbins 		return (EINVAL);
85396d7f8efSTim J. Robbins 
854cfa0efe7SMaxim Sobolev 	if (which == ITIMER_REAL) {
85596d7f8efSTim J. Robbins 		PROC_LOCK(p);
8564cf41af3SPoul-Henning Kamp 		if (timevalisset(&p->p_realtimer.it_value))
8574f559836SJake Burkholder 			callout_stop(&p->p_itcallout);
858b5ea3779SAlexander Motin 		microuptime(&ctv);
859cfa0efe7SMaxim Sobolev 		if (timevalisset(&aitv->it_value)) {
860b5ea3779SAlexander Motin 			pr = tvtosbt(aitv->it_value) >> tc_precexp;
861cfa0efe7SMaxim Sobolev 			timevaladd(&aitv->it_value, &ctv);
862b5ea3779SAlexander Motin 			sbt = tvtosbt(aitv->it_value);
863b5ea3779SAlexander Motin 			callout_reset_sbt(&p->p_itcallout, sbt, pr,
864b5ea3779SAlexander Motin 			    realitexpire, p, C_ABSOLUTE);
86525b4d3a8SJohn Baldwin 		}
866cfa0efe7SMaxim Sobolev 		*oitv = p->p_realtimer;
867cfa0efe7SMaxim Sobolev 		p->p_realtimer = *aitv;
86896d7f8efSTim J. Robbins 		PROC_UNLOCK(p);
869cfa0efe7SMaxim Sobolev 		if (timevalisset(&oitv->it_value)) {
870cfa0efe7SMaxim Sobolev 			if (timevalcmp(&oitv->it_value, &ctv, <))
871cfa0efe7SMaxim Sobolev 				timevalclear(&oitv->it_value);
87296d7f8efSTim J. Robbins 			else
873cfa0efe7SMaxim Sobolev 				timevalsub(&oitv->it_value, &ctv);
874fb99ab88SMatthew Dillon 		}
87596d7f8efSTim J. Robbins 	} else {
876d10a1df8SAlexander Motin 		if (aitv->it_interval.tv_sec == 0 &&
877d10a1df8SAlexander Motin 		    aitv->it_interval.tv_usec != 0 &&
878d10a1df8SAlexander Motin 		    aitv->it_interval.tv_usec < tick)
879d10a1df8SAlexander Motin 			aitv->it_interval.tv_usec = tick;
880d10a1df8SAlexander Motin 		if (aitv->it_value.tv_sec == 0 &&
881d10a1df8SAlexander Motin 		    aitv->it_value.tv_usec != 0 &&
882d10a1df8SAlexander Motin 		    aitv->it_value.tv_usec < tick)
883d10a1df8SAlexander Motin 			aitv->it_value.tv_usec = tick;
8845c7bebf9SKonstantin Belousov 		PROC_ITIMLOCK(p);
885cfa0efe7SMaxim Sobolev 		*oitv = p->p_stats->p_timer[which];
886cfa0efe7SMaxim Sobolev 		p->p_stats->p_timer[which] = *aitv;
8875c7bebf9SKonstantin Belousov 		PROC_ITIMUNLOCK(p);
88896d7f8efSTim J. Robbins 	}
889de56aee0SKonstantin Belousov #ifdef KTRACE
890de56aee0SKonstantin Belousov 	if (KTRPOINT(td, KTR_STRUCT))
891de56aee0SKonstantin Belousov 		ktritimerval(oitv);
892de56aee0SKonstantin Belousov #endif
89396d7f8efSTim J. Robbins 	return (0);
894df8bae1dSRodney W. Grimes }
895df8bae1dSRodney W. Grimes 
896df8bae1dSRodney W. Grimes /*
897df8bae1dSRodney W. Grimes  * Real interval timer expired:
898df8bae1dSRodney W. Grimes  * send process whose timer expired an alarm signal.
899df8bae1dSRodney W. Grimes  * If time is not set up to reload, then just return.
900df8bae1dSRodney W. Grimes  * Else compute next time timer should go off which is > current time.
901df8bae1dSRodney W. Grimes  * This is where delay in processing this timeout causes multiple
902df8bae1dSRodney W. Grimes  * SIGALRM calls to be compressed into one.
903c8b47828SBruce Evans  * tvtohz() always adds 1 to allow for the time until the next clock
9049207f00aSBruce Evans  * interrupt being strictly less than 1 clock tick, but we don't want
9059207f00aSBruce Evans  * that here since we want to appear to be in sync with the clock
9069207f00aSBruce Evans  * interrupt even when we're delayed.
907df8bae1dSRodney W. Grimes  */
908df8bae1dSRodney W. Grimes void
90991afe087SPoul-Henning Kamp realitexpire(void *arg)
910df8bae1dSRodney W. Grimes {
91191afe087SPoul-Henning Kamp 	struct proc *p;
912b5ea3779SAlexander Motin 	struct timeval ctv;
913b5ea3779SAlexander Motin 	sbintime_t isbt;
914df8bae1dSRodney W. Grimes 
915df8bae1dSRodney W. Grimes 	p = (struct proc *)arg;
9168451d0ddSKip Macy 	kern_psignal(p, SIGALRM);
9174cf41af3SPoul-Henning Kamp 	if (!timevalisset(&p->p_realtimer.it_interval)) {
9184cf41af3SPoul-Henning Kamp 		timevalclear(&p->p_realtimer.it_value);
9195499ea01SJohn Baldwin 		if (p->p_flag & P_WEXIT)
9205499ea01SJohn Baldwin 			wakeup(&p->p_itcallout);
921df8bae1dSRodney W. Grimes 		return;
922df8bae1dSRodney W. Grimes 	}
923b5ea3779SAlexander Motin 	isbt = tvtosbt(p->p_realtimer.it_interval);
924b5ea3779SAlexander Motin 	if (isbt >= sbt_timethreshold)
925b5ea3779SAlexander Motin 		getmicrouptime(&ctv);
926b5ea3779SAlexander Motin 	else
927b5ea3779SAlexander Motin 		microuptime(&ctv);
928b5ea3779SAlexander Motin 	do {
929df8bae1dSRodney W. Grimes 		timevaladd(&p->p_realtimer.it_value,
930df8bae1dSRodney W. Grimes 		    &p->p_realtimer.it_interval);
931b5ea3779SAlexander Motin 	} while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
932b5ea3779SAlexander Motin 	callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
933b5ea3779SAlexander Motin 	    isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
934df8bae1dSRodney W. Grimes }
935df8bae1dSRodney W. Grimes 
936df8bae1dSRodney W. Grimes /*
937df8bae1dSRodney W. Grimes  * Check that a proposed value to load into the .it_value or
938df8bae1dSRodney W. Grimes  * .it_interval part of an interval timer is acceptable, and
939df8bae1dSRodney W. Grimes  * fix it to have at least minimal value (i.e. if it is less
940df8bae1dSRodney W. Grimes  * than the resolution of the clock, round it up.)
941df8bae1dSRodney W. Grimes  */
94226f9a767SRodney W. Grimes int
94391afe087SPoul-Henning Kamp itimerfix(struct timeval *tv)
944df8bae1dSRodney W. Grimes {
945df8bae1dSRodney W. Grimes 
94686857b36SDavid Xu 	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
947df8bae1dSRodney W. Grimes 		return (EINVAL);
948b5ea3779SAlexander Motin 	if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
949b5ea3779SAlexander Motin 	    tv->tv_usec < (u_int)tick / 16)
950b5ea3779SAlexander Motin 		tv->tv_usec = (u_int)tick / 16;
951df8bae1dSRodney W. Grimes 	return (0);
952df8bae1dSRodney W. Grimes }
953df8bae1dSRodney W. Grimes 
954df8bae1dSRodney W. Grimes /*
955df8bae1dSRodney W. Grimes  * Decrement an interval timer by a specified number
956df8bae1dSRodney W. Grimes  * of microseconds, which must be less than a second,
957df8bae1dSRodney W. Grimes  * i.e. < 1000000.  If the timer expires, then reload
958df8bae1dSRodney W. Grimes  * it.  In this case, carry over (usec - old value) to
959df8bae1dSRodney W. Grimes  * reduce the value reloaded into the timer so that
960df8bae1dSRodney W. Grimes  * the timer does not drift.  This routine assumes
961df8bae1dSRodney W. Grimes  * that it is called in a context where the timers
962df8bae1dSRodney W. Grimes  * on which it is operating cannot change in value.
963df8bae1dSRodney W. Grimes  */
96426f9a767SRodney W. Grimes int
96591afe087SPoul-Henning Kamp itimerdecr(struct itimerval *itp, int usec)
966df8bae1dSRodney W. Grimes {
967df8bae1dSRodney W. Grimes 
968df8bae1dSRodney W. Grimes 	if (itp->it_value.tv_usec < usec) {
969df8bae1dSRodney W. Grimes 		if (itp->it_value.tv_sec == 0) {
970df8bae1dSRodney W. Grimes 			/* expired, and already in next interval */
971df8bae1dSRodney W. Grimes 			usec -= itp->it_value.tv_usec;
972df8bae1dSRodney W. Grimes 			goto expire;
973df8bae1dSRodney W. Grimes 		}
974df8bae1dSRodney W. Grimes 		itp->it_value.tv_usec += 1000000;
975df8bae1dSRodney W. Grimes 		itp->it_value.tv_sec--;
976df8bae1dSRodney W. Grimes 	}
977df8bae1dSRodney W. Grimes 	itp->it_value.tv_usec -= usec;
978df8bae1dSRodney W. Grimes 	usec = 0;
9794cf41af3SPoul-Henning Kamp 	if (timevalisset(&itp->it_value))
980df8bae1dSRodney W. Grimes 		return (1);
981df8bae1dSRodney W. Grimes 	/* expired, exactly at end of interval */
982df8bae1dSRodney W. Grimes expire:
9834cf41af3SPoul-Henning Kamp 	if (timevalisset(&itp->it_interval)) {
984df8bae1dSRodney W. Grimes 		itp->it_value = itp->it_interval;
985df8bae1dSRodney W. Grimes 		itp->it_value.tv_usec -= usec;
986df8bae1dSRodney W. Grimes 		if (itp->it_value.tv_usec < 0) {
987df8bae1dSRodney W. Grimes 			itp->it_value.tv_usec += 1000000;
988df8bae1dSRodney W. Grimes 			itp->it_value.tv_sec--;
989df8bae1dSRodney W. Grimes 		}
990df8bae1dSRodney W. Grimes 	} else
991df8bae1dSRodney W. Grimes 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
992df8bae1dSRodney W. Grimes 	return (0);
993df8bae1dSRodney W. Grimes }
994df8bae1dSRodney W. Grimes 
995df8bae1dSRodney W. Grimes /*
996df8bae1dSRodney W. Grimes  * Add and subtract routines for timevals.
997df8bae1dSRodney W. Grimes  * N.B.: subtract routine doesn't deal with
998df8bae1dSRodney W. Grimes  * results which are before the beginning,
999df8bae1dSRodney W. Grimes  * it just gets very confused in this case.
1000df8bae1dSRodney W. Grimes  * Caveat emptor.
1001df8bae1dSRodney W. Grimes  */
100226f9a767SRodney W. Grimes void
10036ff7636eSAlfred Perlstein timevaladd(struct timeval *t1, const struct timeval *t2)
1004df8bae1dSRodney W. Grimes {
1005df8bae1dSRodney W. Grimes 
1006df8bae1dSRodney W. Grimes 	t1->tv_sec += t2->tv_sec;
1007df8bae1dSRodney W. Grimes 	t1->tv_usec += t2->tv_usec;
1008df8bae1dSRodney W. Grimes 	timevalfix(t1);
1009df8bae1dSRodney W. Grimes }
1010df8bae1dSRodney W. Grimes 
101126f9a767SRodney W. Grimes void
10126ff7636eSAlfred Perlstein timevalsub(struct timeval *t1, const struct timeval *t2)
1013df8bae1dSRodney W. Grimes {
1014df8bae1dSRodney W. Grimes 
1015df8bae1dSRodney W. Grimes 	t1->tv_sec -= t2->tv_sec;
1016df8bae1dSRodney W. Grimes 	t1->tv_usec -= t2->tv_usec;
1017df8bae1dSRodney W. Grimes 	timevalfix(t1);
1018df8bae1dSRodney W. Grimes }
1019df8bae1dSRodney W. Grimes 
102087b6de2bSPoul-Henning Kamp static void
102191afe087SPoul-Henning Kamp timevalfix(struct timeval *t1)
1022df8bae1dSRodney W. Grimes {
1023df8bae1dSRodney W. Grimes 
1024df8bae1dSRodney W. Grimes 	if (t1->tv_usec < 0) {
1025df8bae1dSRodney W. Grimes 		t1->tv_sec--;
1026df8bae1dSRodney W. Grimes 		t1->tv_usec += 1000000;
1027df8bae1dSRodney W. Grimes 	}
1028df8bae1dSRodney W. Grimes 	if (t1->tv_usec >= 1000000) {
1029df8bae1dSRodney W. Grimes 		t1->tv_sec++;
1030df8bae1dSRodney W. Grimes 		t1->tv_usec -= 1000000;
1031df8bae1dSRodney W. Grimes 	}
1032df8bae1dSRodney W. Grimes }
103391974ce1SSam Leffler 
103491974ce1SSam Leffler /*
1035addea9d4SSam Leffler  * ratecheck(): simple time-based rate-limit checking.
103691974ce1SSam Leffler  */
103791974ce1SSam Leffler int
103891974ce1SSam Leffler ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
103991974ce1SSam Leffler {
104091974ce1SSam Leffler 	struct timeval tv, delta;
104191974ce1SSam Leffler 	int rv = 0;
104291974ce1SSam Leffler 
1043addea9d4SSam Leffler 	getmicrouptime(&tv);		/* NB: 10ms precision */
1044addea9d4SSam Leffler 	delta = tv;
1045addea9d4SSam Leffler 	timevalsub(&delta, lasttime);
104691974ce1SSam Leffler 
104791974ce1SSam Leffler 	/*
104891974ce1SSam Leffler 	 * check for 0,0 is so that the message will be seen at least once,
104991974ce1SSam Leffler 	 * even if interval is huge.
105091974ce1SSam Leffler 	 */
105191974ce1SSam Leffler 	if (timevalcmp(&delta, mininterval, >=) ||
105291974ce1SSam Leffler 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
105391974ce1SSam Leffler 		*lasttime = tv;
105491974ce1SSam Leffler 		rv = 1;
105591974ce1SSam Leffler 	}
105691974ce1SSam Leffler 
105791974ce1SSam Leffler 	return (rv);
105891974ce1SSam Leffler }
105991974ce1SSam Leffler 
106091974ce1SSam Leffler /*
106191974ce1SSam Leffler  * ppsratecheck(): packets (or events) per second limitation.
1062addea9d4SSam Leffler  *
1063addea9d4SSam Leffler  * Return 0 if the limit is to be enforced (e.g. the caller
1064addea9d4SSam Leffler  * should drop a packet because of the rate limitation).
1065addea9d4SSam Leffler  *
1066893bec80SSam Leffler  * maxpps of 0 always causes zero to be returned.  maxpps of -1
1067893bec80SSam Leffler  * always causes 1 to be returned; this effectively defeats rate
1068893bec80SSam Leffler  * limiting.
1069893bec80SSam Leffler  *
1070addea9d4SSam Leffler  * Note that we maintain the struct timeval for compatibility
1071addea9d4SSam Leffler  * with other bsd systems.  We reuse the storage and just monitor
1072addea9d4SSam Leffler  * clock ticks for minimal overhead.
107391974ce1SSam Leffler  */
107491974ce1SSam Leffler int
107591974ce1SSam Leffler ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
107691974ce1SSam Leffler {
1077addea9d4SSam Leffler 	int now;
107891974ce1SSam Leffler 
107991974ce1SSam Leffler 	/*
1080addea9d4SSam Leffler 	 * Reset the last time and counter if this is the first call
1081addea9d4SSam Leffler 	 * or more than a second has passed since the last update of
1082addea9d4SSam Leffler 	 * lasttime.
108391974ce1SSam Leffler 	 */
1084addea9d4SSam Leffler 	now = ticks;
1085addea9d4SSam Leffler 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1086addea9d4SSam Leffler 		lasttime->tv_sec = now;
1087addea9d4SSam Leffler 		*curpps = 1;
1088893bec80SSam Leffler 		return (maxpps != 0);
1089addea9d4SSam Leffler 	} else {
1090addea9d4SSam Leffler 		(*curpps)++;		/* NB: ignore potential overflow */
1091f8f02928SIan Lepore 		return (maxpps < 0 || *curpps <= maxpps);
1092addea9d4SSam Leffler 	}
109391974ce1SSam Leffler }
109486857b36SDavid Xu 
109586857b36SDavid Xu static void
109686857b36SDavid Xu itimer_start(void)
109786857b36SDavid Xu {
109886857b36SDavid Xu 	struct kclock rt_clock = {
109986857b36SDavid Xu 		.timer_create  = realtimer_create,
110086857b36SDavid Xu 		.timer_delete  = realtimer_delete,
110186857b36SDavid Xu 		.timer_settime = realtimer_settime,
110286857b36SDavid Xu 		.timer_gettime = realtimer_gettime,
1103843b99c6SDavid Xu 		.event_hook    = NULL
110486857b36SDavid Xu 	};
110586857b36SDavid Xu 
110686857b36SDavid Xu 	itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
110786857b36SDavid Xu 		NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
110886857b36SDavid Xu 	register_posix_clock(CLOCK_REALTIME,  &rt_clock);
110986857b36SDavid Xu 	register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
111077e718f7SDavid Xu 	p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
111177e718f7SDavid Xu 	p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
111277e718f7SDavid Xu 	p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1113993182e5SAlexander Leidinger 	EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
1114d26b1a1fSDavid Xu 		(void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
1115993182e5SAlexander Leidinger 	EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
1116d26b1a1fSDavid Xu 		(void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
111786857b36SDavid Xu }
111886857b36SDavid Xu 
111986857b36SDavid Xu int
112086857b36SDavid Xu register_posix_clock(int clockid, struct kclock *clk)
112186857b36SDavid Xu {
112286857b36SDavid Xu 	if ((unsigned)clockid >= MAX_CLOCKS) {
112386857b36SDavid Xu 		printf("%s: invalid clockid\n", __func__);
112486857b36SDavid Xu 		return (0);
112586857b36SDavid Xu 	}
112686857b36SDavid Xu 	posix_clocks[clockid] = *clk;
112786857b36SDavid Xu 	return (1);
112886857b36SDavid Xu }
112986857b36SDavid Xu 
113086857b36SDavid Xu static int
113186857b36SDavid Xu itimer_init(void *mem, int size, int flags)
113286857b36SDavid Xu {
113386857b36SDavid Xu 	struct itimer *it;
113486857b36SDavid Xu 
113586857b36SDavid Xu 	it = (struct itimer *)mem;
113686857b36SDavid Xu 	mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
113786857b36SDavid Xu 	return (0);
113886857b36SDavid Xu }
113986857b36SDavid Xu 
114086857b36SDavid Xu static void
114186857b36SDavid Xu itimer_fini(void *mem, int size)
114286857b36SDavid Xu {
114386857b36SDavid Xu 	struct itimer *it;
114486857b36SDavid Xu 
114586857b36SDavid Xu 	it = (struct itimer *)mem;
114686857b36SDavid Xu 	mtx_destroy(&it->it_mtx);
114786857b36SDavid Xu }
114886857b36SDavid Xu 
114986857b36SDavid Xu static void
115086857b36SDavid Xu itimer_enter(struct itimer *it)
115186857b36SDavid Xu {
115286857b36SDavid Xu 
115386857b36SDavid Xu 	mtx_assert(&it->it_mtx, MA_OWNED);
115486857b36SDavid Xu 	it->it_usecount++;
115586857b36SDavid Xu }
115686857b36SDavid Xu 
115786857b36SDavid Xu static void
115886857b36SDavid Xu itimer_leave(struct itimer *it)
115986857b36SDavid Xu {
116086857b36SDavid Xu 
116186857b36SDavid Xu 	mtx_assert(&it->it_mtx, MA_OWNED);
116286857b36SDavid Xu 	KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
116386857b36SDavid Xu 
116486857b36SDavid Xu 	if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
116586857b36SDavid Xu 		wakeup(it);
116686857b36SDavid Xu }
116786857b36SDavid Xu 
116886857b36SDavid Xu #ifndef _SYS_SYSPROTO_H_
116961d3a4efSDavid Xu struct ktimer_create_args {
117086857b36SDavid Xu 	clockid_t clock_id;
117186857b36SDavid Xu 	struct sigevent * evp;
117261d3a4efSDavid Xu 	int * timerid;
117386857b36SDavid Xu };
117486857b36SDavid Xu #endif
117586857b36SDavid Xu int
11768451d0ddSKip Macy sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
117786857b36SDavid Xu {
1178643ee871SKonstantin Belousov 	struct sigevent *evp, ev;
117961d3a4efSDavid Xu 	int id;
118086857b36SDavid Xu 	int error;
118186857b36SDavid Xu 
1182643ee871SKonstantin Belousov 	if (uap->evp == NULL) {
1183643ee871SKonstantin Belousov 		evp = NULL;
1184643ee871SKonstantin Belousov 	} else {
118586857b36SDavid Xu 		error = copyin(uap->evp, &ev, sizeof(ev));
118686857b36SDavid Xu 		if (error != 0)
118786857b36SDavid Xu 			return (error);
1188643ee871SKonstantin Belousov 		evp = &ev;
1189643ee871SKonstantin Belousov 	}
1190643ee871SKonstantin Belousov 	error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
119186857b36SDavid Xu 	if (error == 0) {
119261d3a4efSDavid Xu 		error = copyout(&id, uap->timerid, sizeof(int));
119386857b36SDavid Xu 		if (error != 0)
1194643ee871SKonstantin Belousov 			kern_ktimer_delete(td, id);
119586857b36SDavid Xu 	}
119686857b36SDavid Xu 	return (error);
119786857b36SDavid Xu }
119886857b36SDavid Xu 
1199643ee871SKonstantin Belousov int
1200643ee871SKonstantin Belousov kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1201643ee871SKonstantin Belousov     int *timerid, int preset_id)
120286857b36SDavid Xu {
120386857b36SDavid Xu 	struct proc *p = td->td_proc;
120486857b36SDavid Xu 	struct itimer *it;
120586857b36SDavid Xu 	int id;
120686857b36SDavid Xu 	int error;
120786857b36SDavid Xu 
120886857b36SDavid Xu 	if (clock_id < 0 || clock_id >= MAX_CLOCKS)
120986857b36SDavid Xu 		return (EINVAL);
121086857b36SDavid Xu 
121186857b36SDavid Xu 	if (posix_clocks[clock_id].timer_create == NULL)
121286857b36SDavid Xu 		return (EINVAL);
121386857b36SDavid Xu 
121486857b36SDavid Xu 	if (evp != NULL) {
121586857b36SDavid Xu 		if (evp->sigev_notify != SIGEV_NONE &&
121656c06c4bSDavid Xu 		    evp->sigev_notify != SIGEV_SIGNAL &&
121756c06c4bSDavid Xu 		    evp->sigev_notify != SIGEV_THREAD_ID)
121886857b36SDavid Xu 			return (EINVAL);
121956c06c4bSDavid Xu 		if ((evp->sigev_notify == SIGEV_SIGNAL ||
122056c06c4bSDavid Xu 		     evp->sigev_notify == SIGEV_THREAD_ID) &&
122186857b36SDavid Xu 			!_SIG_VALID(evp->sigev_signo))
122286857b36SDavid Xu 			return (EINVAL);
122386857b36SDavid Xu 	}
122486857b36SDavid Xu 
122560354683SDavid Xu 	if (p->p_itimers == NULL)
122686857b36SDavid Xu 		itimers_alloc(p);
122786857b36SDavid Xu 
122886857b36SDavid Xu 	it = uma_zalloc(itimer_zone, M_WAITOK);
122986857b36SDavid Xu 	it->it_flags = 0;
123086857b36SDavid Xu 	it->it_usecount = 0;
123186857b36SDavid Xu 	it->it_active = 0;
123256c06c4bSDavid Xu 	timespecclear(&it->it_time.it_value);
123356c06c4bSDavid Xu 	timespecclear(&it->it_time.it_interval);
123486857b36SDavid Xu 	it->it_overrun = 0;
123586857b36SDavid Xu 	it->it_overrun_last = 0;
123686857b36SDavid Xu 	it->it_clockid = clock_id;
123786857b36SDavid Xu 	it->it_timerid = -1;
123886857b36SDavid Xu 	it->it_proc = p;
123986857b36SDavid Xu 	ksiginfo_init(&it->it_ksi);
124086857b36SDavid Xu 	it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
124186857b36SDavid Xu 	error = CLOCK_CALL(clock_id, timer_create, (it));
124286857b36SDavid Xu 	if (error != 0)
124386857b36SDavid Xu 		goto out;
124486857b36SDavid Xu 
124586857b36SDavid Xu 	PROC_LOCK(p);
124686857b36SDavid Xu 	if (preset_id != -1) {
124786857b36SDavid Xu 		KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
124886857b36SDavid Xu 		id = preset_id;
124960354683SDavid Xu 		if (p->p_itimers->its_timers[id] != NULL) {
125086857b36SDavid Xu 			PROC_UNLOCK(p);
125186857b36SDavid Xu 			error = 0;
125286857b36SDavid Xu 			goto out;
125386857b36SDavid Xu 		}
125486857b36SDavid Xu 	} else {
125586857b36SDavid Xu 		/*
125686857b36SDavid Xu 		 * Find a free timer slot, skipping those reserved
125786857b36SDavid Xu 		 * for setitimer().
125886857b36SDavid Xu 		 */
125986857b36SDavid Xu 		for (id = 3; id < TIMER_MAX; id++)
126060354683SDavid Xu 			if (p->p_itimers->its_timers[id] == NULL)
126186857b36SDavid Xu 				break;
126286857b36SDavid Xu 		if (id == TIMER_MAX) {
126386857b36SDavid Xu 			PROC_UNLOCK(p);
126486857b36SDavid Xu 			error = EAGAIN;
126586857b36SDavid Xu 			goto out;
126686857b36SDavid Xu 		}
126786857b36SDavid Xu 	}
126886857b36SDavid Xu 	it->it_timerid = id;
126960354683SDavid Xu 	p->p_itimers->its_timers[id] = it;
127086857b36SDavid Xu 	if (evp != NULL)
127186857b36SDavid Xu 		it->it_sigev = *evp;
127286857b36SDavid Xu 	else {
127386857b36SDavid Xu 		it->it_sigev.sigev_notify = SIGEV_SIGNAL;
127486857b36SDavid Xu 		switch (clock_id) {
127586857b36SDavid Xu 		default:
127686857b36SDavid Xu 		case CLOCK_REALTIME:
127786857b36SDavid Xu 			it->it_sigev.sigev_signo = SIGALRM;
127886857b36SDavid Xu 			break;
127986857b36SDavid Xu 		case CLOCK_VIRTUAL:
128086857b36SDavid Xu  			it->it_sigev.sigev_signo = SIGVTALRM;
128186857b36SDavid Xu 			break;
128286857b36SDavid Xu 		case CLOCK_PROF:
128386857b36SDavid Xu 			it->it_sigev.sigev_signo = SIGPROF;
128486857b36SDavid Xu 			break;
128586857b36SDavid Xu 		}
12868f0371f1SDavid Xu 		it->it_sigev.sigev_value.sival_int = id;
128786857b36SDavid Xu 	}
128886857b36SDavid Xu 
128956c06c4bSDavid Xu 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
129056c06c4bSDavid Xu 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
129186857b36SDavid Xu 		it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
129286857b36SDavid Xu 		it->it_ksi.ksi_code = SI_TIMER;
129386857b36SDavid Xu 		it->it_ksi.ksi_value = it->it_sigev.sigev_value;
129486857b36SDavid Xu 		it->it_ksi.ksi_timerid = id;
129586857b36SDavid Xu 	}
129686857b36SDavid Xu 	PROC_UNLOCK(p);
129786857b36SDavid Xu 	*timerid = id;
129886857b36SDavid Xu 	return (0);
129986857b36SDavid Xu 
130086857b36SDavid Xu out:
130186857b36SDavid Xu 	ITIMER_LOCK(it);
130286857b36SDavid Xu 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
130386857b36SDavid Xu 	ITIMER_UNLOCK(it);
130486857b36SDavid Xu 	uma_zfree(itimer_zone, it);
130586857b36SDavid Xu 	return (error);
130686857b36SDavid Xu }
130786857b36SDavid Xu 
130886857b36SDavid Xu #ifndef _SYS_SYSPROTO_H_
130961d3a4efSDavid Xu struct ktimer_delete_args {
131061d3a4efSDavid Xu 	int timerid;
131186857b36SDavid Xu };
131286857b36SDavid Xu #endif
131386857b36SDavid Xu int
13148451d0ddSKip Macy sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
131586857b36SDavid Xu {
1316643ee871SKonstantin Belousov 
1317643ee871SKonstantin Belousov 	return (kern_ktimer_delete(td, uap->timerid));
131886857b36SDavid Xu }
131986857b36SDavid Xu 
132086857b36SDavid Xu static struct itimer *
1321843b99c6SDavid Xu itimer_find(struct proc *p, int timerid)
132286857b36SDavid Xu {
132386857b36SDavid Xu 	struct itimer *it;
132486857b36SDavid Xu 
132586857b36SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
13263f935cf3SColin Percival 	if ((p->p_itimers == NULL) ||
13273f935cf3SColin Percival 	    (timerid < 0) || (timerid >= TIMER_MAX) ||
132860354683SDavid Xu 	    (it = p->p_itimers->its_timers[timerid]) == NULL) {
132986857b36SDavid Xu 		return (NULL);
133086857b36SDavid Xu 	}
133186857b36SDavid Xu 	ITIMER_LOCK(it);
1332843b99c6SDavid Xu 	if ((it->it_flags & ITF_DELETING) != 0) {
133386857b36SDavid Xu 		ITIMER_UNLOCK(it);
133486857b36SDavid Xu 		it = NULL;
133586857b36SDavid Xu 	}
133686857b36SDavid Xu 	return (it);
133786857b36SDavid Xu }
133886857b36SDavid Xu 
1339643ee871SKonstantin Belousov int
1340643ee871SKonstantin Belousov kern_ktimer_delete(struct thread *td, int timerid)
134186857b36SDavid Xu {
134286857b36SDavid Xu 	struct proc *p = td->td_proc;
134386857b36SDavid Xu 	struct itimer *it;
134486857b36SDavid Xu 
134586857b36SDavid Xu 	PROC_LOCK(p);
1346843b99c6SDavid Xu 	it = itimer_find(p, timerid);
134786857b36SDavid Xu 	if (it == NULL) {
134886857b36SDavid Xu 		PROC_UNLOCK(p);
134986857b36SDavid Xu 		return (EINVAL);
135086857b36SDavid Xu 	}
135186857b36SDavid Xu 	PROC_UNLOCK(p);
135286857b36SDavid Xu 
135386857b36SDavid Xu 	it->it_flags |= ITF_DELETING;
135486857b36SDavid Xu 	while (it->it_usecount > 0) {
135586857b36SDavid Xu 		it->it_flags |= ITF_WANTED;
135686857b36SDavid Xu 		msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
135786857b36SDavid Xu 	}
135886857b36SDavid Xu 	it->it_flags &= ~ITF_WANTED;
135986857b36SDavid Xu 	CLOCK_CALL(it->it_clockid, timer_delete, (it));
136086857b36SDavid Xu 	ITIMER_UNLOCK(it);
136186857b36SDavid Xu 
136286857b36SDavid Xu 	PROC_LOCK(p);
136386857b36SDavid Xu 	if (KSI_ONQ(&it->it_ksi))
136486857b36SDavid Xu 		sigqueue_take(&it->it_ksi);
136560354683SDavid Xu 	p->p_itimers->its_timers[timerid] = NULL;
136686857b36SDavid Xu 	PROC_UNLOCK(p);
136786857b36SDavid Xu 	uma_zfree(itimer_zone, it);
136886857b36SDavid Xu 	return (0);
136986857b36SDavid Xu }
137086857b36SDavid Xu 
137186857b36SDavid Xu #ifndef _SYS_SYSPROTO_H_
137261d3a4efSDavid Xu struct ktimer_settime_args {
137361d3a4efSDavid Xu 	int timerid;
137486857b36SDavid Xu 	int flags;
137586857b36SDavid Xu 	const struct itimerspec * value;
137686857b36SDavid Xu 	struct itimerspec * ovalue;
137786857b36SDavid Xu };
137886857b36SDavid Xu #endif
137986857b36SDavid Xu int
13808451d0ddSKip Macy sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
138186857b36SDavid Xu {
138286857b36SDavid Xu 	struct itimerspec val, oval, *ovalp;
138386857b36SDavid Xu 	int error;
138486857b36SDavid Xu 
138586857b36SDavid Xu 	error = copyin(uap->value, &val, sizeof(val));
138686857b36SDavid Xu 	if (error != 0)
138786857b36SDavid Xu 		return (error);
1388643ee871SKonstantin Belousov 	ovalp = uap->ovalue != NULL ? &oval : NULL;
1389643ee871SKonstantin Belousov 	error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1390643ee871SKonstantin Belousov 	if (error == 0 && uap->ovalue != NULL)
1391643ee871SKonstantin Belousov 		error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1392643ee871SKonstantin Belousov 	return (error);
1393643ee871SKonstantin Belousov }
139486857b36SDavid Xu 
1395643ee871SKonstantin Belousov int
1396643ee871SKonstantin Belousov kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1397643ee871SKonstantin Belousov     struct itimerspec *val, struct itimerspec *oval)
1398643ee871SKonstantin Belousov {
1399643ee871SKonstantin Belousov 	struct proc *p;
1400643ee871SKonstantin Belousov 	struct itimer *it;
1401643ee871SKonstantin Belousov 	int error;
140286857b36SDavid Xu 
1403643ee871SKonstantin Belousov 	p = td->td_proc;
140486857b36SDavid Xu 	PROC_LOCK(p);
1405643ee871SKonstantin Belousov 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
140686857b36SDavid Xu 		PROC_UNLOCK(p);
140786857b36SDavid Xu 		error = EINVAL;
140886857b36SDavid Xu 	} else {
140986857b36SDavid Xu 		PROC_UNLOCK(p);
141086857b36SDavid Xu 		itimer_enter(it);
1411643ee871SKonstantin Belousov 		error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1412643ee871SKonstantin Belousov 		    flags, val, oval));
141386857b36SDavid Xu 		itimer_leave(it);
141486857b36SDavid Xu 		ITIMER_UNLOCK(it);
141586857b36SDavid Xu 	}
141686857b36SDavid Xu 	return (error);
141786857b36SDavid Xu }
141886857b36SDavid Xu 
141986857b36SDavid Xu #ifndef _SYS_SYSPROTO_H_
142061d3a4efSDavid Xu struct ktimer_gettime_args {
142161d3a4efSDavid Xu 	int timerid;
142286857b36SDavid Xu 	struct itimerspec * value;
142386857b36SDavid Xu };
142486857b36SDavid Xu #endif
142586857b36SDavid Xu int
14268451d0ddSKip Macy sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
142786857b36SDavid Xu {
142886857b36SDavid Xu 	struct itimerspec val;
142986857b36SDavid Xu 	int error;
143086857b36SDavid Xu 
1431643ee871SKonstantin Belousov 	error = kern_ktimer_gettime(td, uap->timerid, &val);
1432643ee871SKonstantin Belousov 	if (error == 0)
1433643ee871SKonstantin Belousov 		error = copyout(&val, uap->value, sizeof(val));
1434643ee871SKonstantin Belousov 	return (error);
1435643ee871SKonstantin Belousov }
1436643ee871SKonstantin Belousov 
1437643ee871SKonstantin Belousov int
1438643ee871SKonstantin Belousov kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1439643ee871SKonstantin Belousov {
1440643ee871SKonstantin Belousov 	struct proc *p;
1441643ee871SKonstantin Belousov 	struct itimer *it;
1442643ee871SKonstantin Belousov 	int error;
1443643ee871SKonstantin Belousov 
1444643ee871SKonstantin Belousov 	p = td->td_proc;
144586857b36SDavid Xu 	PROC_LOCK(p);
1446643ee871SKonstantin Belousov 	if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
144786857b36SDavid Xu 		PROC_UNLOCK(p);
144886857b36SDavid Xu 		error = EINVAL;
144986857b36SDavid Xu 	} else {
145086857b36SDavid Xu 		PROC_UNLOCK(p);
145186857b36SDavid Xu 		itimer_enter(it);
1452643ee871SKonstantin Belousov 		error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
145386857b36SDavid Xu 		itimer_leave(it);
145486857b36SDavid Xu 		ITIMER_UNLOCK(it);
145586857b36SDavid Xu 	}
145686857b36SDavid Xu 	return (error);
145786857b36SDavid Xu }
145886857b36SDavid Xu 
145986857b36SDavid Xu #ifndef _SYS_SYSPROTO_H_
146086857b36SDavid Xu struct timer_getoverrun_args {
146161d3a4efSDavid Xu 	int timerid;
146286857b36SDavid Xu };
146386857b36SDavid Xu #endif
146486857b36SDavid Xu int
14658451d0ddSKip Macy sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
146686857b36SDavid Xu {
1467e346f8c4SBjoern A. Zeeb 
1468e346f8c4SBjoern A. Zeeb 	return (kern_ktimer_getoverrun(td, uap->timerid));
1469e346f8c4SBjoern A. Zeeb }
1470e346f8c4SBjoern A. Zeeb 
1471e346f8c4SBjoern A. Zeeb int
1472e346f8c4SBjoern A. Zeeb kern_ktimer_getoverrun(struct thread *td, int timer_id)
1473e346f8c4SBjoern A. Zeeb {
147486857b36SDavid Xu 	struct proc *p = td->td_proc;
147586857b36SDavid Xu 	struct itimer *it;
147686857b36SDavid Xu 	int error ;
147786857b36SDavid Xu 
147886857b36SDavid Xu 	PROC_LOCK(p);
1479e346f8c4SBjoern A. Zeeb 	if (timer_id < 3 ||
1480e346f8c4SBjoern A. Zeeb 	    (it = itimer_find(p, timer_id)) == NULL) {
148186857b36SDavid Xu 		PROC_UNLOCK(p);
148286857b36SDavid Xu 		error = EINVAL;
148386857b36SDavid Xu 	} else {
148486857b36SDavid Xu 		td->td_retval[0] = it->it_overrun_last;
148586857b36SDavid Xu 		ITIMER_UNLOCK(it);
148656c06c4bSDavid Xu 		PROC_UNLOCK(p);
148786857b36SDavid Xu 		error = 0;
148886857b36SDavid Xu 	}
148986857b36SDavid Xu 	return (error);
149086857b36SDavid Xu }
149186857b36SDavid Xu 
149286857b36SDavid Xu static int
149386857b36SDavid Xu realtimer_create(struct itimer *it)
149486857b36SDavid Xu {
149586857b36SDavid Xu 	callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
149686857b36SDavid Xu 	return (0);
149786857b36SDavid Xu }
149886857b36SDavid Xu 
149986857b36SDavid Xu static int
150086857b36SDavid Xu realtimer_delete(struct itimer *it)
150186857b36SDavid Xu {
150286857b36SDavid Xu 	mtx_assert(&it->it_mtx, MA_OWNED);
1503843b99c6SDavid Xu 
1504d6b6592eSDavid Xu 	/*
1505d6b6592eSDavid Xu 	 * clear timer's value and interval to tell realtimer_expire
1506d6b6592eSDavid Xu 	 * to not rearm the timer.
1507d6b6592eSDavid Xu 	 */
1508d6b6592eSDavid Xu 	timespecclear(&it->it_time.it_value);
1509d6b6592eSDavid Xu 	timespecclear(&it->it_time.it_interval);
1510843b99c6SDavid Xu 	ITIMER_UNLOCK(it);
1511843b99c6SDavid Xu 	callout_drain(&it->it_callout);
1512843b99c6SDavid Xu 	ITIMER_LOCK(it);
151386857b36SDavid Xu 	return (0);
151486857b36SDavid Xu }
151586857b36SDavid Xu 
151686857b36SDavid Xu static int
151786857b36SDavid Xu realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
151886857b36SDavid Xu {
151956c06c4bSDavid Xu 	struct timespec cts;
152086857b36SDavid Xu 
152186857b36SDavid Xu 	mtx_assert(&it->it_mtx, MA_OWNED);
152286857b36SDavid Xu 
152356c06c4bSDavid Xu 	realtimer_clocktime(it->it_clockid, &cts);
152456c06c4bSDavid Xu 	*ovalue = it->it_time;
152586857b36SDavid Xu 	if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
15266040822cSAlan Somers 		timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
152786857b36SDavid Xu 		if (ovalue->it_value.tv_sec < 0 ||
152886857b36SDavid Xu 		    (ovalue->it_value.tv_sec == 0 &&
152986857b36SDavid Xu 		     ovalue->it_value.tv_nsec == 0)) {
153086857b36SDavid Xu 			ovalue->it_value.tv_sec  = 0;
153186857b36SDavid Xu 			ovalue->it_value.tv_nsec = 1;
153286857b36SDavid Xu 		}
153386857b36SDavid Xu 	}
153486857b36SDavid Xu 	return (0);
153586857b36SDavid Xu }
153686857b36SDavid Xu 
153786857b36SDavid Xu static int
153886857b36SDavid Xu realtimer_settime(struct itimer *it, int flags,
153986857b36SDavid Xu 	struct itimerspec *value, struct itimerspec *ovalue)
154086857b36SDavid Xu {
154156c06c4bSDavid Xu 	struct timespec cts, ts;
154256c06c4bSDavid Xu 	struct timeval tv;
154356c06c4bSDavid Xu 	struct itimerspec val;
154486857b36SDavid Xu 
154586857b36SDavid Xu 	mtx_assert(&it->it_mtx, MA_OWNED);
154686857b36SDavid Xu 
154756c06c4bSDavid Xu 	val = *value;
154856c06c4bSDavid Xu 	if (itimespecfix(&val.it_value))
154986857b36SDavid Xu 		return (EINVAL);
155086857b36SDavid Xu 
155156c06c4bSDavid Xu 	if (timespecisset(&val.it_value)) {
155256c06c4bSDavid Xu 		if (itimespecfix(&val.it_interval))
155386857b36SDavid Xu 			return (EINVAL);
155486857b36SDavid Xu 	} else {
155556c06c4bSDavid Xu 		timespecclear(&val.it_interval);
155686857b36SDavid Xu 	}
155786857b36SDavid Xu 
155886857b36SDavid Xu 	if (ovalue != NULL)
155986857b36SDavid Xu 		realtimer_gettime(it, ovalue);
156086857b36SDavid Xu 
156186857b36SDavid Xu 	it->it_time = val;
156256c06c4bSDavid Xu 	if (timespecisset(&val.it_value)) {
156356c06c4bSDavid Xu 		realtimer_clocktime(it->it_clockid, &cts);
156456c06c4bSDavid Xu 		ts = val.it_value;
156586857b36SDavid Xu 		if ((flags & TIMER_ABSTIME) == 0) {
156686857b36SDavid Xu 			/* Convert to absolute time. */
15676040822cSAlan Somers 			timespecadd(&it->it_time.it_value, &cts,
15686040822cSAlan Somers 				&it->it_time.it_value);
156986857b36SDavid Xu 		} else {
15706040822cSAlan Somers 			timespecsub(&ts, &cts, &ts);
157186857b36SDavid Xu 			/*
157256c06c4bSDavid Xu 			 * We don't care if ts is negative, tztohz will
157386857b36SDavid Xu 			 * fix it.
157486857b36SDavid Xu 			 */
157586857b36SDavid Xu 		}
157656c06c4bSDavid Xu 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
157756c06c4bSDavid Xu 		callout_reset(&it->it_callout, tvtohz(&tv),
157886857b36SDavid Xu 			realtimer_expire, it);
157986857b36SDavid Xu 	} else {
158086857b36SDavid Xu 		callout_stop(&it->it_callout);
158186857b36SDavid Xu 	}
158286857b36SDavid Xu 
158386857b36SDavid Xu 	return (0);
158486857b36SDavid Xu }
158586857b36SDavid Xu 
158686857b36SDavid Xu static void
158756c06c4bSDavid Xu realtimer_clocktime(clockid_t id, struct timespec *ts)
158886857b36SDavid Xu {
158986857b36SDavid Xu 	if (id == CLOCK_REALTIME)
159056c06c4bSDavid Xu 		getnanotime(ts);
159186857b36SDavid Xu 	else	/* CLOCK_MONOTONIC */
159256c06c4bSDavid Xu 		getnanouptime(ts);
159356c06c4bSDavid Xu }
159456c06c4bSDavid Xu 
159556c06c4bSDavid Xu int
159661d3a4efSDavid Xu itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
159756c06c4bSDavid Xu {
159856c06c4bSDavid Xu 	struct itimer *it;
159956c06c4bSDavid Xu 
160056c06c4bSDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
1601843b99c6SDavid Xu 	it = itimer_find(p, timerid);
160256c06c4bSDavid Xu 	if (it != NULL) {
160356c06c4bSDavid Xu 		ksi->ksi_overrun = it->it_overrun;
160456c06c4bSDavid Xu 		it->it_overrun_last = it->it_overrun;
160556c06c4bSDavid Xu 		it->it_overrun = 0;
160656c06c4bSDavid Xu 		ITIMER_UNLOCK(it);
160756c06c4bSDavid Xu 		return (0);
160856c06c4bSDavid Xu 	}
160956c06c4bSDavid Xu 	return (EINVAL);
161056c06c4bSDavid Xu }
161156c06c4bSDavid Xu 
161256c06c4bSDavid Xu int
161356c06c4bSDavid Xu itimespecfix(struct timespec *ts)
161456c06c4bSDavid Xu {
161556c06c4bSDavid Xu 
161656c06c4bSDavid Xu 	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
161756c06c4bSDavid Xu 		return (EINVAL);
161856c06c4bSDavid Xu 	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
161956c06c4bSDavid Xu 		ts->tv_nsec = tick * 1000;
162056c06c4bSDavid Xu 	return (0);
162186857b36SDavid Xu }
162286857b36SDavid Xu 
162386857b36SDavid Xu /* Timeout callback for realtime timer */
162486857b36SDavid Xu static void
162586857b36SDavid Xu realtimer_expire(void *arg)
162686857b36SDavid Xu {
162756c06c4bSDavid Xu 	struct timespec cts, ts;
162856c06c4bSDavid Xu 	struct timeval tv;
162986857b36SDavid Xu 	struct itimer *it;
163086857b36SDavid Xu 
163186857b36SDavid Xu 	it = (struct itimer *)arg;
163286857b36SDavid Xu 
163356c06c4bSDavid Xu 	realtimer_clocktime(it->it_clockid, &cts);
163486857b36SDavid Xu 	/* Only fire if time is reached. */
163556c06c4bSDavid Xu 	if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
163656c06c4bSDavid Xu 		if (timespecisset(&it->it_time.it_interval)) {
163756c06c4bSDavid Xu 			timespecadd(&it->it_time.it_value,
16386040822cSAlan Somers 				    &it->it_time.it_interval,
16396040822cSAlan Somers 				    &it->it_time.it_value);
164056c06c4bSDavid Xu 			while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
164177e718f7SDavid Xu 				if (it->it_overrun < INT_MAX)
164286857b36SDavid Xu 					it->it_overrun++;
164377e718f7SDavid Xu 				else
164477e718f7SDavid Xu 					it->it_ksi.ksi_errno = ERANGE;
164556c06c4bSDavid Xu 				timespecadd(&it->it_time.it_value,
16466040822cSAlan Somers 					    &it->it_time.it_interval,
16476040822cSAlan Somers 					    &it->it_time.it_value);
164886857b36SDavid Xu 			}
164986857b36SDavid Xu 		} else {
165086857b36SDavid Xu 			/* single shot timer ? */
165156c06c4bSDavid Xu 			timespecclear(&it->it_time.it_value);
165286857b36SDavid Xu 		}
165356c06c4bSDavid Xu 		if (timespecisset(&it->it_time.it_value)) {
16546040822cSAlan Somers 			timespecsub(&it->it_time.it_value, &cts, &ts);
165556c06c4bSDavid Xu 			TIMESPEC_TO_TIMEVAL(&tv, &ts);
165656c06c4bSDavid Xu 			callout_reset(&it->it_callout, tvtohz(&tv),
165786857b36SDavid Xu 				 realtimer_expire, it);
165886857b36SDavid Xu 		}
1659d6b6592eSDavid Xu 		itimer_enter(it);
166086857b36SDavid Xu 		ITIMER_UNLOCK(it);
166186857b36SDavid Xu 		itimer_fire(it);
166286857b36SDavid Xu 		ITIMER_LOCK(it);
1663d6b6592eSDavid Xu 		itimer_leave(it);
166456c06c4bSDavid Xu 	} else if (timespecisset(&it->it_time.it_value)) {
166556c06c4bSDavid Xu 		ts = it->it_time.it_value;
16666040822cSAlan Somers 		timespecsub(&ts, &cts, &ts);
166756c06c4bSDavid Xu 		TIMESPEC_TO_TIMEVAL(&tv, &ts);
166856c06c4bSDavid Xu 		callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
166986857b36SDavid Xu  			it);
167086857b36SDavid Xu 	}
167186857b36SDavid Xu }
167286857b36SDavid Xu 
167386857b36SDavid Xu void
167486857b36SDavid Xu itimer_fire(struct itimer *it)
167586857b36SDavid Xu {
167686857b36SDavid Xu 	struct proc *p = it->it_proc;
1677cf7d9a8cSDavid Xu 	struct thread *td;
167886857b36SDavid Xu 
167956c06c4bSDavid Xu 	if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
168056c06c4bSDavid Xu 	    it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1681cf7d9a8cSDavid Xu 		if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
168256c06c4bSDavid Xu 			ITIMER_LOCK(it);
168356c06c4bSDavid Xu 			timespecclear(&it->it_time.it_value);
168456c06c4bSDavid Xu 			timespecclear(&it->it_time.it_interval);
168556c06c4bSDavid Xu 			callout_stop(&it->it_callout);
168656c06c4bSDavid Xu 			ITIMER_UNLOCK(it);
1687cf7d9a8cSDavid Xu 			return;
16886d7b314bSDavid Xu 		}
1689cf7d9a8cSDavid Xu 		if (!KSI_ONQ(&it->it_ksi)) {
1690cf7d9a8cSDavid Xu 			it->it_ksi.ksi_errno = 0;
1691cf7d9a8cSDavid Xu 			ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1692cf7d9a8cSDavid Xu 			tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
169356c06c4bSDavid Xu 		} else {
169477e718f7SDavid Xu 			if (it->it_overrun < INT_MAX)
16956d7b314bSDavid Xu 				it->it_overrun++;
169677e718f7SDavid Xu 			else
169777e718f7SDavid Xu 				it->it_ksi.ksi_errno = ERANGE;
169856c06c4bSDavid Xu 		}
169986857b36SDavid Xu 		PROC_UNLOCK(p);
170086857b36SDavid Xu 	}
170186857b36SDavid Xu }
170286857b36SDavid Xu 
170386857b36SDavid Xu static void
170486857b36SDavid Xu itimers_alloc(struct proc *p)
170586857b36SDavid Xu {
170660354683SDavid Xu 	struct itimers *its;
170760354683SDavid Xu 	int i;
170886857b36SDavid Xu 
170960354683SDavid Xu 	its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
171086857b36SDavid Xu 	LIST_INIT(&its->its_virtual);
171186857b36SDavid Xu 	LIST_INIT(&its->its_prof);
171286857b36SDavid Xu 	TAILQ_INIT(&its->its_worklist);
171360354683SDavid Xu 	for (i = 0; i < TIMER_MAX; i++)
171460354683SDavid Xu 		its->its_timers[i] = NULL;
171560354683SDavid Xu 	PROC_LOCK(p);
171660354683SDavid Xu 	if (p->p_itimers == NULL) {
171760354683SDavid Xu 		p->p_itimers = its;
171860354683SDavid Xu 		PROC_UNLOCK(p);
171960354683SDavid Xu 	}
172060354683SDavid Xu 	else {
172160354683SDavid Xu 		PROC_UNLOCK(p);
172260354683SDavid Xu 		free(its, M_SUBPROC);
172360354683SDavid Xu 	}
172486857b36SDavid Xu }
172586857b36SDavid Xu 
1726993182e5SAlexander Leidinger static void
1727993182e5SAlexander Leidinger itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1728993182e5SAlexander Leidinger {
1729993182e5SAlexander Leidinger 	itimers_event_hook_exit(arg, p);
1730993182e5SAlexander Leidinger }
1731993182e5SAlexander Leidinger 
173286857b36SDavid Xu /* Clean up timers when some process events are being triggered. */
1733d26b1a1fSDavid Xu static void
1734993182e5SAlexander Leidinger itimers_event_hook_exit(void *arg, struct proc *p)
173586857b36SDavid Xu {
173686857b36SDavid Xu 	struct itimers *its;
173786857b36SDavid Xu 	struct itimer *it;
17383e70c6f0SDavid Xu 	int event = (int)(intptr_t)arg;
173986857b36SDavid Xu 	int i;
174086857b36SDavid Xu 
174160354683SDavid Xu 	if (p->p_itimers != NULL) {
174260354683SDavid Xu 		its = p->p_itimers;
174386857b36SDavid Xu 		for (i = 0; i < MAX_CLOCKS; ++i) {
174486857b36SDavid Xu 			if (posix_clocks[i].event_hook != NULL)
174586857b36SDavid Xu 				CLOCK_CALL(i, event_hook, (p, i, event));
174686857b36SDavid Xu 		}
174786857b36SDavid Xu 		/*
174886857b36SDavid Xu 		 * According to susv3, XSI interval timers should be inherited
174986857b36SDavid Xu 		 * by new image.
175086857b36SDavid Xu 		 */
175186857b36SDavid Xu 		if (event == ITIMER_EV_EXEC)
175286857b36SDavid Xu 			i = 3;
175386857b36SDavid Xu 		else if (event == ITIMER_EV_EXIT)
175486857b36SDavid Xu 			i = 0;
175586857b36SDavid Xu 		else
175686857b36SDavid Xu 			panic("unhandled event");
175786857b36SDavid Xu 		for (; i < TIMER_MAX; ++i) {
1758843b99c6SDavid Xu 			if ((it = its->its_timers[i]) != NULL)
1759643ee871SKonstantin Belousov 				kern_ktimer_delete(curthread, i);
176086857b36SDavid Xu 		}
176186857b36SDavid Xu 		if (its->its_timers[0] == NULL &&
176286857b36SDavid Xu 		    its->its_timers[1] == NULL &&
176386857b36SDavid Xu 		    its->its_timers[2] == NULL) {
176460354683SDavid Xu 			free(its, M_SUBPROC);
176560354683SDavid Xu 			p->p_itimers = NULL;
176686857b36SDavid Xu 		}
176786857b36SDavid Xu 	}
176886857b36SDavid Xu }
1769