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