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