xref: /netbsd-src/sys/kern/kern_time.c (revision 62f324d0121177eaf2e0384f92fd9ca2a751c795)
1 /*	$NetBSD: kern_time.c,v 1.178 2013/03/31 16:45:06 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Christopher G. Demetriou, and by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1982, 1986, 1989, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
61  */
62 
63 #include <sys/cdefs.h>
64 __KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.178 2013/03/31 16:45:06 christos Exp $");
65 
66 #include <sys/param.h>
67 #include <sys/resourcevar.h>
68 #include <sys/kernel.h>
69 #include <sys/systm.h>
70 #include <sys/proc.h>
71 #include <sys/vnode.h>
72 #include <sys/signalvar.h>
73 #include <sys/syslog.h>
74 #include <sys/timetc.h>
75 #include <sys/timex.h>
76 #include <sys/kauth.h>
77 #include <sys/mount.h>
78 #include <sys/syscallargs.h>
79 #include <sys/cpu.h>
80 
81 static void	timer_intr(void *);
82 static void	itimerfire(struct ptimer *);
83 static void	itimerfree(struct ptimers *, int);
84 
85 kmutex_t	timer_lock;
86 
87 static void	*timer_sih;
88 static TAILQ_HEAD(, ptimer) timer_queue;
89 
90 struct pool ptimer_pool, ptimers_pool;
91 
92 #define	CLOCK_VIRTUAL_P(clockid)	\
93 	((clockid) == CLOCK_VIRTUAL || (clockid) == CLOCK_PROF)
94 
95 CTASSERT(ITIMER_REAL == CLOCK_REALTIME);
96 CTASSERT(ITIMER_VIRTUAL == CLOCK_VIRTUAL);
97 CTASSERT(ITIMER_PROF == CLOCK_PROF);
98 CTASSERT(ITIMER_MONOTONIC == CLOCK_MONOTONIC);
99 
100 /*
101  * Initialize timekeeping.
102  */
103 void
104 time_init(void)
105 {
106 
107 	pool_init(&ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
108 	    &pool_allocator_nointr, IPL_NONE);
109 	pool_init(&ptimers_pool, sizeof(struct ptimers), 0, 0, 0, "ptimerspl",
110 	    &pool_allocator_nointr, IPL_NONE);
111 }
112 
113 void
114 time_init2(void)
115 {
116 
117 	TAILQ_INIT(&timer_queue);
118 	mutex_init(&timer_lock, MUTEX_DEFAULT, IPL_SCHED);
119 	timer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
120 	    timer_intr, NULL);
121 }
122 
123 /* Time of day and interval timer support.
124  *
125  * These routines provide the kernel entry points to get and set
126  * the time-of-day and per-process interval timers.  Subroutines
127  * here provide support for adding and subtracting timeval structures
128  * and decrementing interval timers, optionally reloading the interval
129  * timers when they expire.
130  */
131 
132 /* This function is used by clock_settime and settimeofday */
133 static int
134 settime1(struct proc *p, const struct timespec *ts, bool check_kauth)
135 {
136 	struct timespec delta, now;
137 	int s;
138 
139 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
140 	s = splclock();
141 	nanotime(&now);
142 	timespecsub(ts, &now, &delta);
143 
144 	if (check_kauth && kauth_authorize_system(kauth_cred_get(),
145 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, __UNCONST(ts),
146 	    &delta, KAUTH_ARG(check_kauth ? false : true)) != 0) {
147 		splx(s);
148 		return (EPERM);
149 	}
150 
151 #ifdef notyet
152 	if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */
153 		splx(s);
154 		return (EPERM);
155 	}
156 #endif
157 
158 	tc_setclock(ts);
159 
160 	timespecadd(&boottime, &delta, &boottime);
161 
162 	resettodr();
163 	splx(s);
164 
165 	return (0);
166 }
167 
168 int
169 settime(struct proc *p, struct timespec *ts)
170 {
171 	return (settime1(p, ts, true));
172 }
173 
174 /* ARGSUSED */
175 int
176 sys___clock_gettime50(struct lwp *l,
177     const struct sys___clock_gettime50_args *uap, register_t *retval)
178 {
179 	/* {
180 		syscallarg(clockid_t) clock_id;
181 		syscallarg(struct timespec *) tp;
182 	} */
183 	int error;
184 	struct timespec ats;
185 
186 	error = clock_gettime1(SCARG(uap, clock_id), &ats);
187 	if (error != 0)
188 		return error;
189 
190 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
191 }
192 
193 /* ARGSUSED */
194 int
195 sys___clock_settime50(struct lwp *l,
196     const struct sys___clock_settime50_args *uap, register_t *retval)
197 {
198 	/* {
199 		syscallarg(clockid_t) clock_id;
200 		syscallarg(const struct timespec *) tp;
201 	} */
202 	int error;
203 	struct timespec ats;
204 
205 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
206 		return error;
207 
208 	return clock_settime1(l->l_proc, SCARG(uap, clock_id), &ats, true);
209 }
210 
211 
212 int
213 clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp,
214     bool check_kauth)
215 {
216 	int error;
217 
218 	switch (clock_id) {
219 	case CLOCK_REALTIME:
220 		if ((error = settime1(p, tp, check_kauth)) != 0)
221 			return (error);
222 		break;
223 	case CLOCK_MONOTONIC:
224 		return (EINVAL);	/* read-only clock */
225 	default:
226 		return (EINVAL);
227 	}
228 
229 	return 0;
230 }
231 
232 int
233 sys___clock_getres50(struct lwp *l, const struct sys___clock_getres50_args *uap,
234     register_t *retval)
235 {
236 	/* {
237 		syscallarg(clockid_t) clock_id;
238 		syscallarg(struct timespec *) tp;
239 	} */
240 	struct timespec ts;
241 	int error = 0;
242 
243 	if ((error = clock_getres1(SCARG(uap, clock_id), &ts)) != 0)
244 		return error;
245 
246 	if (SCARG(uap, tp))
247 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
248 
249 	return error;
250 }
251 
252 int
253 clock_getres1(clockid_t clock_id, struct timespec *ts)
254 {
255 
256 	switch (clock_id) {
257 	case CLOCK_REALTIME:
258 	case CLOCK_MONOTONIC:
259 		ts->tv_sec = 0;
260 		if (tc_getfrequency() > 1000000000)
261 			ts->tv_nsec = 1;
262 		else
263 			ts->tv_nsec = 1000000000 / tc_getfrequency();
264 		break;
265 	default:
266 		return EINVAL;
267 	}
268 
269 	return 0;
270 }
271 
272 /* ARGSUSED */
273 int
274 sys___nanosleep50(struct lwp *l, const struct sys___nanosleep50_args *uap,
275     register_t *retval)
276 {
277 	/* {
278 		syscallarg(struct timespec *) rqtp;
279 		syscallarg(struct timespec *) rmtp;
280 	} */
281 	struct timespec rmt, rqt;
282 	int error, error1;
283 
284 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
285 	if (error)
286 		return (error);
287 
288 	error = nanosleep1(l, CLOCK_MONOTONIC, 0, &rqt,
289 	    SCARG(uap, rmtp) ? &rmt : NULL);
290 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
291 		return error;
292 
293 	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
294 	return error1 ? error1 : error;
295 }
296 
297 /* ARGSUSED */
298 int
299 sys_clock_nanosleep(struct lwp *l, const struct sys_clock_nanosleep_args *uap,
300     register_t *retval)
301 {
302 	/* {
303 		syscallarg(clockid_t) clock_id;
304 		syscallarg(int) flags;
305 		syscallarg(struct timespec *) rqtp;
306 		syscallarg(struct timespec *) rmtp;
307 	} */
308 	struct timespec rmt, rqt;
309 	int error, error1;
310 
311 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
312 	if (error)
313 		return (error);
314 
315 	error = nanosleep1(l, SCARG(uap, clock_id), SCARG(uap, flags), &rqt,
316 	    SCARG(uap, rmtp) ? &rmt : NULL);
317 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
318 		return error;
319 
320 	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
321 	return error1 ? error1 : error;
322 }
323 
324 int
325 nanosleep1(struct lwp *l, clockid_t clock_id, int flags, struct timespec *rqt,
326     struct timespec *rmt)
327 {
328 	struct timespec rmtstart;
329 	int error, timo;
330 
331 	if ((error = ts2timo(clock_id, flags, rqt, &timo, &rmtstart)) != 0)
332 		return error == ETIMEDOUT ? 0 : error;
333 
334 	/*
335 	 * Avoid inadvertently sleeping forever
336 	 */
337 	if (timo == 0)
338 		timo = 1;
339 again:
340 	error = kpause("nanoslp", true, timo, NULL);
341 	if (rmt != NULL || error == 0) {
342 		struct timespec rmtend;
343 		struct timespec t0;
344 		struct timespec *t;
345 
346 		(void)clock_gettime1(clock_id, &rmtend);
347 		t = (rmt != NULL) ? rmt : &t0;
348 		timespecsub(&rmtend, &rmtstart, t);
349 		timespecsub(rqt, t, t);
350 		if (t->tv_sec < 0)
351 			timespecclear(t);
352 		if (error == 0) {
353 			timo = tstohz(t);
354 			if (timo > 0)
355 				goto again;
356 		}
357 	}
358 
359 	if (error == ERESTART)
360 		error = EINTR;
361 	if (error == EWOULDBLOCK)
362 		error = 0;
363 
364 	return error;
365 }
366 
367 /* ARGSUSED */
368 int
369 sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap,
370     register_t *retval)
371 {
372 	/* {
373 		syscallarg(struct timeval *) tp;
374 		syscallarg(void *) tzp;		really "struct timezone *";
375 	} */
376 	struct timeval atv;
377 	int error = 0;
378 	struct timezone tzfake;
379 
380 	if (SCARG(uap, tp)) {
381 		microtime(&atv);
382 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
383 		if (error)
384 			return (error);
385 	}
386 	if (SCARG(uap, tzp)) {
387 		/*
388 		 * NetBSD has no kernel notion of time zone, so we just
389 		 * fake up a timezone struct and return it if demanded.
390 		 */
391 		tzfake.tz_minuteswest = 0;
392 		tzfake.tz_dsttime = 0;
393 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
394 	}
395 	return (error);
396 }
397 
398 /* ARGSUSED */
399 int
400 sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap,
401     register_t *retval)
402 {
403 	/* {
404 		syscallarg(const struct timeval *) tv;
405 		syscallarg(const void *) tzp; really "const struct timezone *";
406 	} */
407 
408 	return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
409 }
410 
411 int
412 settimeofday1(const struct timeval *utv, bool userspace,
413     const void *utzp, struct lwp *l, bool check_kauth)
414 {
415 	struct timeval atv;
416 	struct timespec ts;
417 	int error;
418 
419 	/* Verify all parameters before changing time. */
420 
421 	/*
422 	 * NetBSD has no kernel notion of time zone, and only an
423 	 * obsolete program would try to set it, so we log a warning.
424 	 */
425 	if (utzp)
426 		log(LOG_WARNING, "pid %d attempted to set the "
427 		    "(obsolete) kernel time zone\n", l->l_proc->p_pid);
428 
429 	if (utv == NULL)
430 		return 0;
431 
432 	if (userspace) {
433 		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
434 			return error;
435 		utv = &atv;
436 	}
437 
438 	TIMEVAL_TO_TIMESPEC(utv, &ts);
439 	return settime1(l->l_proc, &ts, check_kauth);
440 }
441 
442 int	time_adjusted;			/* set if an adjustment is made */
443 
444 /* ARGSUSED */
445 int
446 sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap,
447     register_t *retval)
448 {
449 	/* {
450 		syscallarg(const struct timeval *) delta;
451 		syscallarg(struct timeval *) olddelta;
452 	} */
453 	int error = 0;
454 	struct timeval atv, oldatv;
455 
456 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
457 	    KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
458 		return error;
459 
460 	if (SCARG(uap, delta)) {
461 		error = copyin(SCARG(uap, delta), &atv,
462 		    sizeof(*SCARG(uap, delta)));
463 		if (error)
464 			return (error);
465 	}
466 	adjtime1(SCARG(uap, delta) ? &atv : NULL,
467 	    SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc);
468 	if (SCARG(uap, olddelta))
469 		error = copyout(&oldatv, SCARG(uap, olddelta),
470 		    sizeof(*SCARG(uap, olddelta)));
471 	return error;
472 }
473 
474 void
475 adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
476 {
477 	extern int64_t time_adjtime;  /* in kern_ntptime.c */
478 
479 	if (olddelta) {
480 		mutex_spin_enter(&timecounter_lock);
481 		olddelta->tv_sec = time_adjtime / 1000000;
482 		olddelta->tv_usec = time_adjtime % 1000000;
483 		if (olddelta->tv_usec < 0) {
484 			olddelta->tv_usec += 1000000;
485 			olddelta->tv_sec--;
486 		}
487 		mutex_spin_exit(&timecounter_lock);
488 	}
489 
490 	if (delta) {
491 		mutex_spin_enter(&timecounter_lock);
492 		time_adjtime = delta->tv_sec * 1000000 + delta->tv_usec;
493 
494 		if (time_adjtime) {
495 			/* We need to save the system time during shutdown */
496 			time_adjusted |= 1;
497 		}
498 		mutex_spin_exit(&timecounter_lock);
499 	}
500 }
501 
502 /*
503  * Interval timer support. Both the BSD getitimer() family and the POSIX
504  * timer_*() family of routines are supported.
505  *
506  * All timers are kept in an array pointed to by p_timers, which is
507  * allocated on demand - many processes don't use timers at all. The
508  * first three elements in this array are reserved for the BSD timers:
509  * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element
510  * 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be
511  * allocated by the timer_create() syscall.
512  *
513  * Realtime timers are kept in the ptimer structure as an absolute
514  * time; virtual time timers are kept as a linked list of deltas.
515  * Virtual time timers are processed in the hardclock() routine of
516  * kern_clock.c.  The real time timer is processed by a callout
517  * routine, called from the softclock() routine.  Since a callout may
518  * be delayed in real time due to interrupt processing in the system,
519  * it is possible for the real time timeout routine (realtimeexpire,
520  * given below), to be delayed in real time past when it is supposed
521  * to occur.  It does not suffice, therefore, to reload the real timer
522  * .it_value from the real time timers .it_interval.  Rather, we
523  * compute the next time in absolute time the timer should go off.  */
524 
525 /* Allocate a POSIX realtime timer. */
526 int
527 sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap,
528     register_t *retval)
529 {
530 	/* {
531 		syscallarg(clockid_t) clock_id;
532 		syscallarg(struct sigevent *) evp;
533 		syscallarg(timer_t *) timerid;
534 	} */
535 
536 	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
537 	    SCARG(uap, evp), copyin, l);
538 }
539 
540 int
541 timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
542     copyin_t fetch_event, struct lwp *l)
543 {
544 	int error;
545 	timer_t timerid;
546 	struct ptimers *pts;
547 	struct ptimer *pt;
548 	struct proc *p;
549 
550 	p = l->l_proc;
551 
552 	if ((u_int)id > CLOCK_MONOTONIC)
553 		return (EINVAL);
554 
555 	if ((pts = p->p_timers) == NULL)
556 		pts = timers_alloc(p);
557 
558 	pt = pool_get(&ptimer_pool, PR_WAITOK);
559 	if (evp != NULL) {
560 		if (((error =
561 		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
562 		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
563 			(pt->pt_ev.sigev_notify > SIGEV_SA)) ||
564 			(pt->pt_ev.sigev_notify == SIGEV_SIGNAL &&
565 			 (pt->pt_ev.sigev_signo <= 0 ||
566 			  pt->pt_ev.sigev_signo >= NSIG))) {
567 			pool_put(&ptimer_pool, pt);
568 			return (error ? error : EINVAL);
569 		}
570 	}
571 
572 	/* Find a free timer slot, skipping those reserved for setitimer(). */
573 	mutex_spin_enter(&timer_lock);
574 	for (timerid = 3; timerid < TIMER_MAX; timerid++)
575 		if (pts->pts_timers[timerid] == NULL)
576 			break;
577 	if (timerid == TIMER_MAX) {
578 		mutex_spin_exit(&timer_lock);
579 		pool_put(&ptimer_pool, pt);
580 		return EAGAIN;
581 	}
582 	if (evp == NULL) {
583 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
584 		switch (id) {
585 		case CLOCK_REALTIME:
586 		case CLOCK_MONOTONIC:
587 			pt->pt_ev.sigev_signo = SIGALRM;
588 			break;
589 		case CLOCK_VIRTUAL:
590 			pt->pt_ev.sigev_signo = SIGVTALRM;
591 			break;
592 		case CLOCK_PROF:
593 			pt->pt_ev.sigev_signo = SIGPROF;
594 			break;
595 		}
596 		pt->pt_ev.sigev_value.sival_int = timerid;
597 	}
598 	pt->pt_info.ksi_signo = pt->pt_ev.sigev_signo;
599 	pt->pt_info.ksi_errno = 0;
600 	pt->pt_info.ksi_code = 0;
601 	pt->pt_info.ksi_pid = p->p_pid;
602 	pt->pt_info.ksi_uid = kauth_cred_getuid(l->l_cred);
603 	pt->pt_info.ksi_value = pt->pt_ev.sigev_value;
604 	pt->pt_type = id;
605 	pt->pt_proc = p;
606 	pt->pt_overruns = 0;
607 	pt->pt_poverruns = 0;
608 	pt->pt_entry = timerid;
609 	pt->pt_queued = false;
610 	timespecclear(&pt->pt_time.it_value);
611 	if (!CLOCK_VIRTUAL_P(id))
612 		callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
613 	else
614 		pt->pt_active = 0;
615 
616 	pts->pts_timers[timerid] = pt;
617 	mutex_spin_exit(&timer_lock);
618 
619 	return copyout(&timerid, tid, sizeof(timerid));
620 }
621 
622 /* Delete a POSIX realtime timer */
623 int
624 sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
625     register_t *retval)
626 {
627 	/* {
628 		syscallarg(timer_t) timerid;
629 	} */
630 	struct proc *p = l->l_proc;
631 	timer_t timerid;
632 	struct ptimers *pts;
633 	struct ptimer *pt, *ptn;
634 
635 	timerid = SCARG(uap, timerid);
636 	pts = p->p_timers;
637 
638 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
639 		return (EINVAL);
640 
641 	mutex_spin_enter(&timer_lock);
642 	if ((pt = pts->pts_timers[timerid]) == NULL) {
643 		mutex_spin_exit(&timer_lock);
644 		return (EINVAL);
645 	}
646 	if (CLOCK_VIRTUAL_P(pt->pt_type)) {
647 		if (pt->pt_active) {
648 			ptn = LIST_NEXT(pt, pt_list);
649 			LIST_REMOVE(pt, pt_list);
650 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
651 				timespecadd(&pt->pt_time.it_value,
652 				    &ptn->pt_time.it_value,
653 				    &ptn->pt_time.it_value);
654 			pt->pt_active = 0;
655 		}
656 	}
657 	itimerfree(pts, timerid);
658 
659 	return (0);
660 }
661 
662 /*
663  * Set up the given timer. The value in pt->pt_time.it_value is taken
664  * to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC timers and
665  * a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
666  */
667 void
668 timer_settime(struct ptimer *pt)
669 {
670 	struct ptimer *ptn, *pptn;
671 	struct ptlist *ptl;
672 
673 	KASSERT(mutex_owned(&timer_lock));
674 
675 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
676 		callout_halt(&pt->pt_ch, &timer_lock);
677 		if (timespecisset(&pt->pt_time.it_value)) {
678 			/*
679 			 * Don't need to check tshzto() return value, here.
680 			 * callout_reset() does it for us.
681 			 */
682 			callout_reset(&pt->pt_ch,
683 			    pt->pt_type == CLOCK_MONOTONIC ?
684 			    tshztoup(&pt->pt_time.it_value) :
685 			    tshzto(&pt->pt_time.it_value),
686 			    realtimerexpire, pt);
687 		}
688 	} else {
689 		if (pt->pt_active) {
690 			ptn = LIST_NEXT(pt, pt_list);
691 			LIST_REMOVE(pt, pt_list);
692 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
693 				timespecadd(&pt->pt_time.it_value,
694 				    &ptn->pt_time.it_value,
695 				    &ptn->pt_time.it_value);
696 		}
697 		if (timespecisset(&pt->pt_time.it_value)) {
698 			if (pt->pt_type == CLOCK_VIRTUAL)
699 				ptl = &pt->pt_proc->p_timers->pts_virtual;
700 			else
701 				ptl = &pt->pt_proc->p_timers->pts_prof;
702 
703 			for (ptn = LIST_FIRST(ptl), pptn = NULL;
704 			     ptn && timespeccmp(&pt->pt_time.it_value,
705 				 &ptn->pt_time.it_value, >);
706 			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
707 				timespecsub(&pt->pt_time.it_value,
708 				    &ptn->pt_time.it_value,
709 				    &pt->pt_time.it_value);
710 
711 			if (pptn)
712 				LIST_INSERT_AFTER(pptn, pt, pt_list);
713 			else
714 				LIST_INSERT_HEAD(ptl, pt, pt_list);
715 
716 			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
717 				timespecsub(&ptn->pt_time.it_value,
718 				    &pt->pt_time.it_value,
719 				    &ptn->pt_time.it_value);
720 
721 			pt->pt_active = 1;
722 		} else
723 			pt->pt_active = 0;
724 	}
725 }
726 
727 void
728 timer_gettime(struct ptimer *pt, struct itimerspec *aits)
729 {
730 	struct timespec now;
731 	struct ptimer *ptn;
732 
733 	KASSERT(mutex_owned(&timer_lock));
734 
735 	*aits = pt->pt_time;
736 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
737 		/*
738 		 * Convert from absolute to relative time in .it_value
739 		 * part of real time timer.  If time for real time
740 		 * timer has passed return 0, else return difference
741 		 * between current time and time for the timer to go
742 		 * off.
743 		 */
744 		if (timespecisset(&aits->it_value)) {
745 			if (pt->pt_type == CLOCK_REALTIME) {
746 				getnanotime(&now);
747 			} else { /* CLOCK_MONOTONIC */
748 				getnanouptime(&now);
749 			}
750 			if (timespeccmp(&aits->it_value, &now, <))
751 				timespecclear(&aits->it_value);
752 			else
753 				timespecsub(&aits->it_value, &now,
754 				    &aits->it_value);
755 		}
756 	} else if (pt->pt_active) {
757 		if (pt->pt_type == CLOCK_VIRTUAL)
758 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
759 		else
760 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
761 		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
762 			timespecadd(&aits->it_value,
763 			    &ptn->pt_time.it_value, &aits->it_value);
764 		KASSERT(ptn != NULL); /* pt should be findable on the list */
765 	} else
766 		timespecclear(&aits->it_value);
767 }
768 
769 
770 
771 /* Set and arm a POSIX realtime timer */
772 int
773 sys___timer_settime50(struct lwp *l,
774     const struct sys___timer_settime50_args *uap,
775     register_t *retval)
776 {
777 	/* {
778 		syscallarg(timer_t) timerid;
779 		syscallarg(int) flags;
780 		syscallarg(const struct itimerspec *) value;
781 		syscallarg(struct itimerspec *) ovalue;
782 	} */
783 	int error;
784 	struct itimerspec value, ovalue, *ovp = NULL;
785 
786 	if ((error = copyin(SCARG(uap, value), &value,
787 	    sizeof(struct itimerspec))) != 0)
788 		return (error);
789 
790 	if (SCARG(uap, ovalue))
791 		ovp = &ovalue;
792 
793 	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
794 	    SCARG(uap, flags), l->l_proc)) != 0)
795 		return error;
796 
797 	if (ovp)
798 		return copyout(&ovalue, SCARG(uap, ovalue),
799 		    sizeof(struct itimerspec));
800 	return 0;
801 }
802 
803 int
804 dotimer_settime(int timerid, struct itimerspec *value,
805     struct itimerspec *ovalue, int flags, struct proc *p)
806 {
807 	struct timespec now;
808 	struct itimerspec val, oval;
809 	struct ptimers *pts;
810 	struct ptimer *pt;
811 	int error;
812 
813 	pts = p->p_timers;
814 
815 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
816 		return EINVAL;
817 	val = *value;
818 	if ((error = itimespecfix(&val.it_value)) != 0 ||
819 	    (error = itimespecfix(&val.it_interval)) != 0)
820 		return error;
821 
822 	mutex_spin_enter(&timer_lock);
823 	if ((pt = pts->pts_timers[timerid]) == NULL) {
824 		mutex_spin_exit(&timer_lock);
825 		return EINVAL;
826 	}
827 
828 	oval = pt->pt_time;
829 	pt->pt_time = val;
830 
831 	/*
832 	 * If we've been passed a relative time for a realtime timer,
833 	 * convert it to absolute; if an absolute time for a virtual
834 	 * timer, convert it to relative and make sure we don't set it
835 	 * to zero, which would cancel the timer, or let it go
836 	 * negative, which would confuse the comparison tests.
837 	 */
838 	if (timespecisset(&pt->pt_time.it_value)) {
839 		if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
840 			if ((flags & TIMER_ABSTIME) == 0) {
841 				if (pt->pt_type == CLOCK_REALTIME) {
842 					getnanotime(&now);
843 				} else { /* CLOCK_MONOTONIC */
844 					getnanouptime(&now);
845 				}
846 				timespecadd(&pt->pt_time.it_value, &now,
847 				    &pt->pt_time.it_value);
848 			}
849 		} else {
850 			if ((flags & TIMER_ABSTIME) != 0) {
851 				getnanotime(&now);
852 				timespecsub(&pt->pt_time.it_value, &now,
853 				    &pt->pt_time.it_value);
854 				if (!timespecisset(&pt->pt_time.it_value) ||
855 				    pt->pt_time.it_value.tv_sec < 0) {
856 					pt->pt_time.it_value.tv_sec = 0;
857 					pt->pt_time.it_value.tv_nsec = 1;
858 				}
859 			}
860 		}
861 	}
862 
863 	timer_settime(pt);
864 	mutex_spin_exit(&timer_lock);
865 
866 	if (ovalue)
867 		*ovalue = oval;
868 
869 	return (0);
870 }
871 
872 /* Return the time remaining until a POSIX timer fires. */
873 int
874 sys___timer_gettime50(struct lwp *l,
875     const struct sys___timer_gettime50_args *uap, register_t *retval)
876 {
877 	/* {
878 		syscallarg(timer_t) timerid;
879 		syscallarg(struct itimerspec *) value;
880 	} */
881 	struct itimerspec its;
882 	int error;
883 
884 	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
885 	    &its)) != 0)
886 		return error;
887 
888 	return copyout(&its, SCARG(uap, value), sizeof(its));
889 }
890 
891 int
892 dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
893 {
894 	struct ptimer *pt;
895 	struct ptimers *pts;
896 
897 	pts = p->p_timers;
898 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
899 		return (EINVAL);
900 	mutex_spin_enter(&timer_lock);
901 	if ((pt = pts->pts_timers[timerid]) == NULL) {
902 		mutex_spin_exit(&timer_lock);
903 		return (EINVAL);
904 	}
905 	timer_gettime(pt, its);
906 	mutex_spin_exit(&timer_lock);
907 
908 	return 0;
909 }
910 
911 /*
912  * Return the count of the number of times a periodic timer expired
913  * while a notification was already pending. The counter is reset when
914  * a timer expires and a notification can be posted.
915  */
916 int
917 sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
918     register_t *retval)
919 {
920 	/* {
921 		syscallarg(timer_t) timerid;
922 	} */
923 	struct proc *p = l->l_proc;
924 	struct ptimers *pts;
925 	int timerid;
926 	struct ptimer *pt;
927 
928 	timerid = SCARG(uap, timerid);
929 
930 	pts = p->p_timers;
931 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
932 		return (EINVAL);
933 	mutex_spin_enter(&timer_lock);
934 	if ((pt = pts->pts_timers[timerid]) == NULL) {
935 		mutex_spin_exit(&timer_lock);
936 		return (EINVAL);
937 	}
938 	*retval = pt->pt_poverruns;
939 	mutex_spin_exit(&timer_lock);
940 
941 	return (0);
942 }
943 
944 /*
945  * Real interval timer expired:
946  * send process whose timer expired an alarm signal.
947  * If time is not set up to reload, then just return.
948  * Else compute next time timer should go off which is > current time.
949  * This is where delay in processing this timeout causes multiple
950  * SIGALRM calls to be compressed into one.
951  */
952 void
953 realtimerexpire(void *arg)
954 {
955 	uint64_t last_val, next_val, interval, now_ns;
956 	struct timespec now, next;
957 	struct ptimer *pt;
958 	int backwards;
959 
960 	pt = arg;
961 
962 	mutex_spin_enter(&timer_lock);
963 	itimerfire(pt);
964 
965 	if (!timespecisset(&pt->pt_time.it_interval)) {
966 		timespecclear(&pt->pt_time.it_value);
967 		mutex_spin_exit(&timer_lock);
968 		return;
969 	}
970 
971 	if (pt->pt_type == CLOCK_MONOTONIC) {
972 		getnanouptime(&now);
973 	} else {
974 		getnanotime(&now);
975 	}
976 	backwards = (timespeccmp(&pt->pt_time.it_value, &now, >));
977 	timespecadd(&pt->pt_time.it_value, &pt->pt_time.it_interval, &next);
978 	/* Handle the easy case of non-overflown timers first. */
979 	if (!backwards && timespeccmp(&next, &now, >)) {
980 		pt->pt_time.it_value = next;
981 	} else {
982 		now_ns = timespec2ns(&now);
983 		last_val = timespec2ns(&pt->pt_time.it_value);
984 		interval = timespec2ns(&pt->pt_time.it_interval);
985 
986 		next_val = now_ns +
987 		    (now_ns - last_val + interval - 1) % interval;
988 
989 		if (backwards)
990 			next_val += interval;
991 		else
992 			pt->pt_overruns += (now_ns - last_val) / interval;
993 
994 		pt->pt_time.it_value.tv_sec = next_val / 1000000000;
995 		pt->pt_time.it_value.tv_nsec = next_val % 1000000000;
996 	}
997 
998 	/*
999 	 * Don't need to check tshzto() return value, here.
1000 	 * callout_reset() does it for us.
1001 	 */
1002 	callout_reset(&pt->pt_ch, pt->pt_type == CLOCK_MONOTONIC ?
1003 	    tshztoup(&pt->pt_time.it_value) : tshzto(&pt->pt_time.it_value),
1004 	    realtimerexpire, pt);
1005 	mutex_spin_exit(&timer_lock);
1006 }
1007 
1008 /* BSD routine to get the value of an interval timer. */
1009 /* ARGSUSED */
1010 int
1011 sys___getitimer50(struct lwp *l, const struct sys___getitimer50_args *uap,
1012     register_t *retval)
1013 {
1014 	/* {
1015 		syscallarg(int) which;
1016 		syscallarg(struct itimerval *) itv;
1017 	} */
1018 	struct proc *p = l->l_proc;
1019 	struct itimerval aitv;
1020 	int error;
1021 
1022 	error = dogetitimer(p, SCARG(uap, which), &aitv);
1023 	if (error)
1024 		return error;
1025 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
1026 }
1027 
1028 int
1029 dogetitimer(struct proc *p, int which, struct itimerval *itvp)
1030 {
1031 	struct ptimers *pts;
1032 	struct ptimer *pt;
1033 	struct itimerspec its;
1034 
1035 	if ((u_int)which > ITIMER_MONOTONIC)
1036 		return (EINVAL);
1037 
1038 	mutex_spin_enter(&timer_lock);
1039 	pts = p->p_timers;
1040 	if (pts == NULL || (pt = pts->pts_timers[which]) == NULL) {
1041 		timerclear(&itvp->it_value);
1042 		timerclear(&itvp->it_interval);
1043 	} else {
1044 		timer_gettime(pt, &its);
1045 		TIMESPEC_TO_TIMEVAL(&itvp->it_value, &its.it_value);
1046 		TIMESPEC_TO_TIMEVAL(&itvp->it_interval, &its.it_interval);
1047 	}
1048 	mutex_spin_exit(&timer_lock);
1049 
1050 	return 0;
1051 }
1052 
1053 /* BSD routine to set/arm an interval timer. */
1054 /* ARGSUSED */
1055 int
1056 sys___setitimer50(struct lwp *l, const struct sys___setitimer50_args *uap,
1057     register_t *retval)
1058 {
1059 	/* {
1060 		syscallarg(int) which;
1061 		syscallarg(const struct itimerval *) itv;
1062 		syscallarg(struct itimerval *) oitv;
1063 	} */
1064 	struct proc *p = l->l_proc;
1065 	int which = SCARG(uap, which);
1066 	struct sys___getitimer50_args getargs;
1067 	const struct itimerval *itvp;
1068 	struct itimerval aitv;
1069 	int error;
1070 
1071 	if ((u_int)which > ITIMER_MONOTONIC)
1072 		return (EINVAL);
1073 	itvp = SCARG(uap, itv);
1074 	if (itvp &&
1075 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval))) != 0)
1076 		return (error);
1077 	if (SCARG(uap, oitv) != NULL) {
1078 		SCARG(&getargs, which) = which;
1079 		SCARG(&getargs, itv) = SCARG(uap, oitv);
1080 		if ((error = sys___getitimer50(l, &getargs, retval)) != 0)
1081 			return (error);
1082 	}
1083 	if (itvp == 0)
1084 		return (0);
1085 
1086 	return dosetitimer(p, which, &aitv);
1087 }
1088 
1089 int
1090 dosetitimer(struct proc *p, int which, struct itimerval *itvp)
1091 {
1092 	struct timespec now;
1093 	struct ptimers *pts;
1094 	struct ptimer *pt, *spare;
1095 
1096 	KASSERT((u_int)which <= CLOCK_MONOTONIC);
1097 	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
1098 		return (EINVAL);
1099 
1100 	/*
1101 	 * Don't bother allocating data structures if the process just
1102 	 * wants to clear the timer.
1103 	 */
1104 	spare = NULL;
1105 	pts = p->p_timers;
1106  retry:
1107 	if (!timerisset(&itvp->it_value) && (pts == NULL ||
1108 	    pts->pts_timers[which] == NULL))
1109 		return (0);
1110 	if (pts == NULL)
1111 		pts = timers_alloc(p);
1112 	mutex_spin_enter(&timer_lock);
1113 	pt = pts->pts_timers[which];
1114 	if (pt == NULL) {
1115 		if (spare == NULL) {
1116 			mutex_spin_exit(&timer_lock);
1117 			spare = pool_get(&ptimer_pool, PR_WAITOK);
1118 			goto retry;
1119 		}
1120 		pt = spare;
1121 		spare = NULL;
1122 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
1123 		pt->pt_ev.sigev_value.sival_int = which;
1124 		pt->pt_overruns = 0;
1125 		pt->pt_proc = p;
1126 		pt->pt_type = which;
1127 		pt->pt_entry = which;
1128 		pt->pt_queued = false;
1129 		if (pt->pt_type == CLOCK_REALTIME)
1130 			callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
1131 		else
1132 			pt->pt_active = 0;
1133 
1134 		switch (which) {
1135 		case ITIMER_REAL:
1136 		case ITIMER_MONOTONIC:
1137 			pt->pt_ev.sigev_signo = SIGALRM;
1138 			break;
1139 		case ITIMER_VIRTUAL:
1140 			pt->pt_ev.sigev_signo = SIGVTALRM;
1141 			break;
1142 		case ITIMER_PROF:
1143 			pt->pt_ev.sigev_signo = SIGPROF;
1144 			break;
1145 		}
1146 		pts->pts_timers[which] = pt;
1147 	}
1148 
1149 	TIMEVAL_TO_TIMESPEC(&itvp->it_value, &pt->pt_time.it_value);
1150 	TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &pt->pt_time.it_interval);
1151 
1152 	if (timespecisset(&pt->pt_time.it_value)) {
1153 		/* Convert to absolute time */
1154 		/* XXX need to wrap in splclock for timecounters case? */
1155 		switch (which) {
1156 		case ITIMER_REAL:
1157 			getnanotime(&now);
1158 			timespecadd(&pt->pt_time.it_value, &now,
1159 			    &pt->pt_time.it_value);
1160 			break;
1161 		case ITIMER_MONOTONIC:
1162 			getnanouptime(&now);
1163 			timespecadd(&pt->pt_time.it_value, &now,
1164 			    &pt->pt_time.it_value);
1165 			break;
1166 		default:
1167 			break;
1168 		}
1169 	}
1170 	timer_settime(pt);
1171 	mutex_spin_exit(&timer_lock);
1172 	if (spare != NULL)
1173 		pool_put(&ptimer_pool, spare);
1174 
1175 	return (0);
1176 }
1177 
1178 /* Utility routines to manage the array of pointers to timers. */
1179 struct ptimers *
1180 timers_alloc(struct proc *p)
1181 {
1182 	struct ptimers *pts;
1183 	int i;
1184 
1185 	pts = pool_get(&ptimers_pool, PR_WAITOK);
1186 	LIST_INIT(&pts->pts_virtual);
1187 	LIST_INIT(&pts->pts_prof);
1188 	for (i = 0; i < TIMER_MAX; i++)
1189 		pts->pts_timers[i] = NULL;
1190 	pts->pts_fired = 0;
1191 	mutex_spin_enter(&timer_lock);
1192 	if (p->p_timers == NULL) {
1193 		p->p_timers = pts;
1194 		mutex_spin_exit(&timer_lock);
1195 		return pts;
1196 	}
1197 	mutex_spin_exit(&timer_lock);
1198 	pool_put(&ptimers_pool, pts);
1199 	return p->p_timers;
1200 }
1201 
1202 /*
1203  * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
1204  * then clean up all timers and free all the data structures. If
1205  * "which" is set to TIMERS_POSIX, only clean up the timers allocated
1206  * by timer_create(), not the BSD setitimer() timers, and only free the
1207  * structure if none of those remain.
1208  */
1209 void
1210 timers_free(struct proc *p, int which)
1211 {
1212 	struct ptimers *pts;
1213 	struct ptimer *ptn;
1214 	struct timespec ts;
1215 	int i;
1216 
1217 	if (p->p_timers == NULL)
1218 		return;
1219 
1220 	pts = p->p_timers;
1221 	mutex_spin_enter(&timer_lock);
1222 	if (which == TIMERS_ALL) {
1223 		p->p_timers = NULL;
1224 		i = 0;
1225 	} else {
1226 		timespecclear(&ts);
1227 		for (ptn = LIST_FIRST(&pts->pts_virtual);
1228 		     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
1229 		     ptn = LIST_NEXT(ptn, pt_list)) {
1230 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
1231 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
1232 		}
1233 		LIST_FIRST(&pts->pts_virtual) = NULL;
1234 		if (ptn) {
1235 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
1236 			timespecadd(&ts, &ptn->pt_time.it_value,
1237 			    &ptn->pt_time.it_value);
1238 			LIST_INSERT_HEAD(&pts->pts_virtual, ptn, pt_list);
1239 		}
1240 		timespecclear(&ts);
1241 		for (ptn = LIST_FIRST(&pts->pts_prof);
1242 		     ptn && ptn != pts->pts_timers[ITIMER_PROF];
1243 		     ptn = LIST_NEXT(ptn, pt_list)) {
1244 			KASSERT(ptn->pt_type == CLOCK_PROF);
1245 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
1246 		}
1247 		LIST_FIRST(&pts->pts_prof) = NULL;
1248 		if (ptn) {
1249 			KASSERT(ptn->pt_type == CLOCK_PROF);
1250 			timespecadd(&ts, &ptn->pt_time.it_value,
1251 			    &ptn->pt_time.it_value);
1252 			LIST_INSERT_HEAD(&pts->pts_prof, ptn, pt_list);
1253 		}
1254 		i = 3;
1255 	}
1256 	for ( ; i < TIMER_MAX; i++) {
1257 		if (pts->pts_timers[i] != NULL) {
1258 			itimerfree(pts, i);
1259 			mutex_spin_enter(&timer_lock);
1260 		}
1261 	}
1262 	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
1263 	    pts->pts_timers[2] == NULL) {
1264 		p->p_timers = NULL;
1265 		mutex_spin_exit(&timer_lock);
1266 		pool_put(&ptimers_pool, pts);
1267 	} else
1268 		mutex_spin_exit(&timer_lock);
1269 }
1270 
1271 static void
1272 itimerfree(struct ptimers *pts, int index)
1273 {
1274 	struct ptimer *pt;
1275 
1276 	KASSERT(mutex_owned(&timer_lock));
1277 
1278 	pt = pts->pts_timers[index];
1279 	pts->pts_timers[index] = NULL;
1280 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
1281 		callout_halt(&pt->pt_ch, &timer_lock);
1282 	if (pt->pt_queued)
1283 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1284 	mutex_spin_exit(&timer_lock);
1285 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
1286 		callout_destroy(&pt->pt_ch);
1287 	pool_put(&ptimer_pool, pt);
1288 }
1289 
1290 /*
1291  * Decrement an interval timer by a specified number
1292  * of nanoseconds, which must be less than a second,
1293  * i.e. < 1000000000.  If the timer expires, then reload
1294  * it.  In this case, carry over (nsec - old value) to
1295  * reduce the value reloaded into the timer so that
1296  * the timer does not drift.  This routine assumes
1297  * that it is called in a context where the timers
1298  * on which it is operating cannot change in value.
1299  */
1300 static int
1301 itimerdecr(struct ptimer *pt, int nsec)
1302 {
1303 	struct itimerspec *itp;
1304 
1305 	KASSERT(mutex_owned(&timer_lock));
1306 	KASSERT(CLOCK_VIRTUAL_P(pt->pt_type));
1307 
1308 	itp = &pt->pt_time;
1309 	if (itp->it_value.tv_nsec < nsec) {
1310 		if (itp->it_value.tv_sec == 0) {
1311 			/* expired, and already in next interval */
1312 			nsec -= itp->it_value.tv_nsec;
1313 			goto expire;
1314 		}
1315 		itp->it_value.tv_nsec += 1000000000;
1316 		itp->it_value.tv_sec--;
1317 	}
1318 	itp->it_value.tv_nsec -= nsec;
1319 	nsec = 0;
1320 	if (timespecisset(&itp->it_value))
1321 		return (1);
1322 	/* expired, exactly at end of interval */
1323 expire:
1324 	if (timespecisset(&itp->it_interval)) {
1325 		itp->it_value = itp->it_interval;
1326 		itp->it_value.tv_nsec -= nsec;
1327 		if (itp->it_value.tv_nsec < 0) {
1328 			itp->it_value.tv_nsec += 1000000000;
1329 			itp->it_value.tv_sec--;
1330 		}
1331 		timer_settime(pt);
1332 	} else
1333 		itp->it_value.tv_nsec = 0;		/* sec is already 0 */
1334 	return (0);
1335 }
1336 
1337 static void
1338 itimerfire(struct ptimer *pt)
1339 {
1340 
1341 	KASSERT(mutex_owned(&timer_lock));
1342 
1343 	/*
1344 	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
1345 	 * XXX Relying on the clock interrupt is stupid.
1346 	 */
1347 	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL || pt->pt_queued) {
1348 		return;
1349 	}
1350 	TAILQ_INSERT_TAIL(&timer_queue, pt, pt_chain);
1351 	pt->pt_queued = true;
1352 	softint_schedule(timer_sih);
1353 }
1354 
1355 void
1356 timer_tick(lwp_t *l, bool user)
1357 {
1358 	struct ptimers *pts;
1359 	struct ptimer *pt;
1360 	proc_t *p;
1361 
1362 	p = l->l_proc;
1363 	if (p->p_timers == NULL)
1364 		return;
1365 
1366 	mutex_spin_enter(&timer_lock);
1367 	if ((pts = l->l_proc->p_timers) != NULL) {
1368 		/*
1369 		 * Run current process's virtual and profile time, as needed.
1370 		 */
1371 		if (user && (pt = LIST_FIRST(&pts->pts_virtual)) != NULL)
1372 			if (itimerdecr(pt, tick * 1000) == 0)
1373 				itimerfire(pt);
1374 		if ((pt = LIST_FIRST(&pts->pts_prof)) != NULL)
1375 			if (itimerdecr(pt, tick * 1000) == 0)
1376 				itimerfire(pt);
1377 	}
1378 	mutex_spin_exit(&timer_lock);
1379 }
1380 
1381 static void
1382 timer_intr(void *cookie)
1383 {
1384 	ksiginfo_t ksi;
1385 	struct ptimer *pt;
1386 	proc_t *p;
1387 
1388 	mutex_enter(proc_lock);
1389 	mutex_spin_enter(&timer_lock);
1390 	while ((pt = TAILQ_FIRST(&timer_queue)) != NULL) {
1391 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1392 		KASSERT(pt->pt_queued);
1393 		pt->pt_queued = false;
1394 
1395 		if (pt->pt_proc->p_timers == NULL) {
1396 			/* Process is dying. */
1397 			continue;
1398 		}
1399 		p = pt->pt_proc;
1400 		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
1401 			continue;
1402 		}
1403 		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
1404 			pt->pt_overruns++;
1405 			continue;
1406 		}
1407 
1408 		KSI_INIT(&ksi);
1409 		ksi.ksi_signo = pt->pt_ev.sigev_signo;
1410 		ksi.ksi_code = SI_TIMER;
1411 		ksi.ksi_value = pt->pt_ev.sigev_value;
1412 		pt->pt_poverruns = pt->pt_overruns;
1413 		pt->pt_overruns = 0;
1414 		mutex_spin_exit(&timer_lock);
1415 		kpsignal(p, &ksi, NULL);
1416 		mutex_spin_enter(&timer_lock);
1417 	}
1418 	mutex_spin_exit(&timer_lock);
1419 	mutex_exit(proc_lock);
1420 }
1421 
1422 /*
1423  * Check if the time will wrap if set to ts.
1424  *
1425  * ts - timespec describing the new time
1426  * delta - the delta between the current time and ts
1427  */
1428 bool
1429 time_wraps(struct timespec *ts, struct timespec *delta)
1430 {
1431 
1432 	/*
1433 	 * Don't allow the time to be set forward so far it
1434 	 * will wrap and become negative, thus allowing an
1435 	 * attacker to bypass the next check below.  The
1436 	 * cutoff is 1 year before rollover occurs, so even
1437 	 * if the attacker uses adjtime(2) to move the time
1438 	 * past the cutoff, it will take a very long time
1439 	 * to get to the wrap point.
1440 	 */
1441 	if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
1442 	    (delta->tv_sec < 0 || delta->tv_nsec < 0))
1443 		return true;
1444 
1445 	return false;
1446 }
1447