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