xref: /netbsd-src/sys/kern/kern_time.c (revision 4d12bfcd155352508213ace5ccc59ce930ea2974)
1 /*	$NetBSD: kern_time.c,v 1.179 2013/05/22 16:00:52 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.179 2013/05/22 16:00:52 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 		if (flags & TIMER_ABSTIME) {
349 			timespecsub(rqt, &rmtend, t);
350 		} else {
351 			timespecsub(&rmtend, &rmtstart, t);
352 			timespecsub(rqt, t, t);
353 		}
354 		if (t->tv_sec < 0)
355 			timespecclear(t);
356 		if (error == 0) {
357 			timo = tstohz(t);
358 			if (timo > 0)
359 				goto again;
360 		}
361 	}
362 
363 	if (error == ERESTART)
364 		error = EINTR;
365 	if (error == EWOULDBLOCK)
366 		error = 0;
367 
368 	return error;
369 }
370 
371 /* ARGSUSED */
372 int
373 sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap,
374     register_t *retval)
375 {
376 	/* {
377 		syscallarg(struct timeval *) tp;
378 		syscallarg(void *) tzp;		really "struct timezone *";
379 	} */
380 	struct timeval atv;
381 	int error = 0;
382 	struct timezone tzfake;
383 
384 	if (SCARG(uap, tp)) {
385 		microtime(&atv);
386 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
387 		if (error)
388 			return (error);
389 	}
390 	if (SCARG(uap, tzp)) {
391 		/*
392 		 * NetBSD has no kernel notion of time zone, so we just
393 		 * fake up a timezone struct and return it if demanded.
394 		 */
395 		tzfake.tz_minuteswest = 0;
396 		tzfake.tz_dsttime = 0;
397 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
398 	}
399 	return (error);
400 }
401 
402 /* ARGSUSED */
403 int
404 sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap,
405     register_t *retval)
406 {
407 	/* {
408 		syscallarg(const struct timeval *) tv;
409 		syscallarg(const void *) tzp; really "const struct timezone *";
410 	} */
411 
412 	return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
413 }
414 
415 int
416 settimeofday1(const struct timeval *utv, bool userspace,
417     const void *utzp, struct lwp *l, bool check_kauth)
418 {
419 	struct timeval atv;
420 	struct timespec ts;
421 	int error;
422 
423 	/* Verify all parameters before changing time. */
424 
425 	/*
426 	 * NetBSD has no kernel notion of time zone, and only an
427 	 * obsolete program would try to set it, so we log a warning.
428 	 */
429 	if (utzp)
430 		log(LOG_WARNING, "pid %d attempted to set the "
431 		    "(obsolete) kernel time zone\n", l->l_proc->p_pid);
432 
433 	if (utv == NULL)
434 		return 0;
435 
436 	if (userspace) {
437 		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
438 			return error;
439 		utv = &atv;
440 	}
441 
442 	TIMEVAL_TO_TIMESPEC(utv, &ts);
443 	return settime1(l->l_proc, &ts, check_kauth);
444 }
445 
446 int	time_adjusted;			/* set if an adjustment is made */
447 
448 /* ARGSUSED */
449 int
450 sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap,
451     register_t *retval)
452 {
453 	/* {
454 		syscallarg(const struct timeval *) delta;
455 		syscallarg(struct timeval *) olddelta;
456 	} */
457 	int error = 0;
458 	struct timeval atv, oldatv;
459 
460 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
461 	    KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
462 		return error;
463 
464 	if (SCARG(uap, delta)) {
465 		error = copyin(SCARG(uap, delta), &atv,
466 		    sizeof(*SCARG(uap, delta)));
467 		if (error)
468 			return (error);
469 	}
470 	adjtime1(SCARG(uap, delta) ? &atv : NULL,
471 	    SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc);
472 	if (SCARG(uap, olddelta))
473 		error = copyout(&oldatv, SCARG(uap, olddelta),
474 		    sizeof(*SCARG(uap, olddelta)));
475 	return error;
476 }
477 
478 void
479 adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
480 {
481 	extern int64_t time_adjtime;  /* in kern_ntptime.c */
482 
483 	if (olddelta) {
484 		mutex_spin_enter(&timecounter_lock);
485 		olddelta->tv_sec = time_adjtime / 1000000;
486 		olddelta->tv_usec = time_adjtime % 1000000;
487 		if (olddelta->tv_usec < 0) {
488 			olddelta->tv_usec += 1000000;
489 			olddelta->tv_sec--;
490 		}
491 		mutex_spin_exit(&timecounter_lock);
492 	}
493 
494 	if (delta) {
495 		mutex_spin_enter(&timecounter_lock);
496 		time_adjtime = delta->tv_sec * 1000000 + delta->tv_usec;
497 
498 		if (time_adjtime) {
499 			/* We need to save the system time during shutdown */
500 			time_adjusted |= 1;
501 		}
502 		mutex_spin_exit(&timecounter_lock);
503 	}
504 }
505 
506 /*
507  * Interval timer support. Both the BSD getitimer() family and the POSIX
508  * timer_*() family of routines are supported.
509  *
510  * All timers are kept in an array pointed to by p_timers, which is
511  * allocated on demand - many processes don't use timers at all. The
512  * first three elements in this array are reserved for the BSD timers:
513  * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element
514  * 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be
515  * allocated by the timer_create() syscall.
516  *
517  * Realtime timers are kept in the ptimer structure as an absolute
518  * time; virtual time timers are kept as a linked list of deltas.
519  * Virtual time timers are processed in the hardclock() routine of
520  * kern_clock.c.  The real time timer is processed by a callout
521  * routine, called from the softclock() routine.  Since a callout may
522  * be delayed in real time due to interrupt processing in the system,
523  * it is possible for the real time timeout routine (realtimeexpire,
524  * given below), to be delayed in real time past when it is supposed
525  * to occur.  It does not suffice, therefore, to reload the real timer
526  * .it_value from the real time timers .it_interval.  Rather, we
527  * compute the next time in absolute time the timer should go off.  */
528 
529 /* Allocate a POSIX realtime timer. */
530 int
531 sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap,
532     register_t *retval)
533 {
534 	/* {
535 		syscallarg(clockid_t) clock_id;
536 		syscallarg(struct sigevent *) evp;
537 		syscallarg(timer_t *) timerid;
538 	} */
539 
540 	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
541 	    SCARG(uap, evp), copyin, l);
542 }
543 
544 int
545 timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
546     copyin_t fetch_event, struct lwp *l)
547 {
548 	int error;
549 	timer_t timerid;
550 	struct ptimers *pts;
551 	struct ptimer *pt;
552 	struct proc *p;
553 
554 	p = l->l_proc;
555 
556 	if ((u_int)id > CLOCK_MONOTONIC)
557 		return (EINVAL);
558 
559 	if ((pts = p->p_timers) == NULL)
560 		pts = timers_alloc(p);
561 
562 	pt = pool_get(&ptimer_pool, PR_WAITOK);
563 	if (evp != NULL) {
564 		if (((error =
565 		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
566 		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
567 			(pt->pt_ev.sigev_notify > SIGEV_SA)) ||
568 			(pt->pt_ev.sigev_notify == SIGEV_SIGNAL &&
569 			 (pt->pt_ev.sigev_signo <= 0 ||
570 			  pt->pt_ev.sigev_signo >= NSIG))) {
571 			pool_put(&ptimer_pool, pt);
572 			return (error ? error : EINVAL);
573 		}
574 	}
575 
576 	/* Find a free timer slot, skipping those reserved for setitimer(). */
577 	mutex_spin_enter(&timer_lock);
578 	for (timerid = 3; timerid < TIMER_MAX; timerid++)
579 		if (pts->pts_timers[timerid] == NULL)
580 			break;
581 	if (timerid == TIMER_MAX) {
582 		mutex_spin_exit(&timer_lock);
583 		pool_put(&ptimer_pool, pt);
584 		return EAGAIN;
585 	}
586 	if (evp == NULL) {
587 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
588 		switch (id) {
589 		case CLOCK_REALTIME:
590 		case CLOCK_MONOTONIC:
591 			pt->pt_ev.sigev_signo = SIGALRM;
592 			break;
593 		case CLOCK_VIRTUAL:
594 			pt->pt_ev.sigev_signo = SIGVTALRM;
595 			break;
596 		case CLOCK_PROF:
597 			pt->pt_ev.sigev_signo = SIGPROF;
598 			break;
599 		}
600 		pt->pt_ev.sigev_value.sival_int = timerid;
601 	}
602 	pt->pt_info.ksi_signo = pt->pt_ev.sigev_signo;
603 	pt->pt_info.ksi_errno = 0;
604 	pt->pt_info.ksi_code = 0;
605 	pt->pt_info.ksi_pid = p->p_pid;
606 	pt->pt_info.ksi_uid = kauth_cred_getuid(l->l_cred);
607 	pt->pt_info.ksi_value = pt->pt_ev.sigev_value;
608 	pt->pt_type = id;
609 	pt->pt_proc = p;
610 	pt->pt_overruns = 0;
611 	pt->pt_poverruns = 0;
612 	pt->pt_entry = timerid;
613 	pt->pt_queued = false;
614 	timespecclear(&pt->pt_time.it_value);
615 	if (!CLOCK_VIRTUAL_P(id))
616 		callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
617 	else
618 		pt->pt_active = 0;
619 
620 	pts->pts_timers[timerid] = pt;
621 	mutex_spin_exit(&timer_lock);
622 
623 	return copyout(&timerid, tid, sizeof(timerid));
624 }
625 
626 /* Delete a POSIX realtime timer */
627 int
628 sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
629     register_t *retval)
630 {
631 	/* {
632 		syscallarg(timer_t) timerid;
633 	} */
634 	struct proc *p = l->l_proc;
635 	timer_t timerid;
636 	struct ptimers *pts;
637 	struct ptimer *pt, *ptn;
638 
639 	timerid = SCARG(uap, timerid);
640 	pts = p->p_timers;
641 
642 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
643 		return (EINVAL);
644 
645 	mutex_spin_enter(&timer_lock);
646 	if ((pt = pts->pts_timers[timerid]) == NULL) {
647 		mutex_spin_exit(&timer_lock);
648 		return (EINVAL);
649 	}
650 	if (CLOCK_VIRTUAL_P(pt->pt_type)) {
651 		if (pt->pt_active) {
652 			ptn = LIST_NEXT(pt, pt_list);
653 			LIST_REMOVE(pt, pt_list);
654 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
655 				timespecadd(&pt->pt_time.it_value,
656 				    &ptn->pt_time.it_value,
657 				    &ptn->pt_time.it_value);
658 			pt->pt_active = 0;
659 		}
660 	}
661 	itimerfree(pts, timerid);
662 
663 	return (0);
664 }
665 
666 /*
667  * Set up the given timer. The value in pt->pt_time.it_value is taken
668  * to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC timers and
669  * a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
670  */
671 void
672 timer_settime(struct ptimer *pt)
673 {
674 	struct ptimer *ptn, *pptn;
675 	struct ptlist *ptl;
676 
677 	KASSERT(mutex_owned(&timer_lock));
678 
679 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
680 		callout_halt(&pt->pt_ch, &timer_lock);
681 		if (timespecisset(&pt->pt_time.it_value)) {
682 			/*
683 			 * Don't need to check tshzto() return value, here.
684 			 * callout_reset() does it for us.
685 			 */
686 			callout_reset(&pt->pt_ch,
687 			    pt->pt_type == CLOCK_MONOTONIC ?
688 			    tshztoup(&pt->pt_time.it_value) :
689 			    tshzto(&pt->pt_time.it_value),
690 			    realtimerexpire, pt);
691 		}
692 	} else {
693 		if (pt->pt_active) {
694 			ptn = LIST_NEXT(pt, pt_list);
695 			LIST_REMOVE(pt, pt_list);
696 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
697 				timespecadd(&pt->pt_time.it_value,
698 				    &ptn->pt_time.it_value,
699 				    &ptn->pt_time.it_value);
700 		}
701 		if (timespecisset(&pt->pt_time.it_value)) {
702 			if (pt->pt_type == CLOCK_VIRTUAL)
703 				ptl = &pt->pt_proc->p_timers->pts_virtual;
704 			else
705 				ptl = &pt->pt_proc->p_timers->pts_prof;
706 
707 			for (ptn = LIST_FIRST(ptl), pptn = NULL;
708 			     ptn && timespeccmp(&pt->pt_time.it_value,
709 				 &ptn->pt_time.it_value, >);
710 			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
711 				timespecsub(&pt->pt_time.it_value,
712 				    &ptn->pt_time.it_value,
713 				    &pt->pt_time.it_value);
714 
715 			if (pptn)
716 				LIST_INSERT_AFTER(pptn, pt, pt_list);
717 			else
718 				LIST_INSERT_HEAD(ptl, pt, pt_list);
719 
720 			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
721 				timespecsub(&ptn->pt_time.it_value,
722 				    &pt->pt_time.it_value,
723 				    &ptn->pt_time.it_value);
724 
725 			pt->pt_active = 1;
726 		} else
727 			pt->pt_active = 0;
728 	}
729 }
730 
731 void
732 timer_gettime(struct ptimer *pt, struct itimerspec *aits)
733 {
734 	struct timespec now;
735 	struct ptimer *ptn;
736 
737 	KASSERT(mutex_owned(&timer_lock));
738 
739 	*aits = pt->pt_time;
740 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
741 		/*
742 		 * Convert from absolute to relative time in .it_value
743 		 * part of real time timer.  If time for real time
744 		 * timer has passed return 0, else return difference
745 		 * between current time and time for the timer to go
746 		 * off.
747 		 */
748 		if (timespecisset(&aits->it_value)) {
749 			if (pt->pt_type == CLOCK_REALTIME) {
750 				getnanotime(&now);
751 			} else { /* CLOCK_MONOTONIC */
752 				getnanouptime(&now);
753 			}
754 			if (timespeccmp(&aits->it_value, &now, <))
755 				timespecclear(&aits->it_value);
756 			else
757 				timespecsub(&aits->it_value, &now,
758 				    &aits->it_value);
759 		}
760 	} else if (pt->pt_active) {
761 		if (pt->pt_type == CLOCK_VIRTUAL)
762 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
763 		else
764 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
765 		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
766 			timespecadd(&aits->it_value,
767 			    &ptn->pt_time.it_value, &aits->it_value);
768 		KASSERT(ptn != NULL); /* pt should be findable on the list */
769 	} else
770 		timespecclear(&aits->it_value);
771 }
772 
773 
774 
775 /* Set and arm a POSIX realtime timer */
776 int
777 sys___timer_settime50(struct lwp *l,
778     const struct sys___timer_settime50_args *uap,
779     register_t *retval)
780 {
781 	/* {
782 		syscallarg(timer_t) timerid;
783 		syscallarg(int) flags;
784 		syscallarg(const struct itimerspec *) value;
785 		syscallarg(struct itimerspec *) ovalue;
786 	} */
787 	int error;
788 	struct itimerspec value, ovalue, *ovp = NULL;
789 
790 	if ((error = copyin(SCARG(uap, value), &value,
791 	    sizeof(struct itimerspec))) != 0)
792 		return (error);
793 
794 	if (SCARG(uap, ovalue))
795 		ovp = &ovalue;
796 
797 	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
798 	    SCARG(uap, flags), l->l_proc)) != 0)
799 		return error;
800 
801 	if (ovp)
802 		return copyout(&ovalue, SCARG(uap, ovalue),
803 		    sizeof(struct itimerspec));
804 	return 0;
805 }
806 
807 int
808 dotimer_settime(int timerid, struct itimerspec *value,
809     struct itimerspec *ovalue, int flags, struct proc *p)
810 {
811 	struct timespec now;
812 	struct itimerspec val, oval;
813 	struct ptimers *pts;
814 	struct ptimer *pt;
815 	int error;
816 
817 	pts = p->p_timers;
818 
819 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
820 		return EINVAL;
821 	val = *value;
822 	if ((error = itimespecfix(&val.it_value)) != 0 ||
823 	    (error = itimespecfix(&val.it_interval)) != 0)
824 		return error;
825 
826 	mutex_spin_enter(&timer_lock);
827 	if ((pt = pts->pts_timers[timerid]) == NULL) {
828 		mutex_spin_exit(&timer_lock);
829 		return EINVAL;
830 	}
831 
832 	oval = pt->pt_time;
833 	pt->pt_time = val;
834 
835 	/*
836 	 * If we've been passed a relative time for a realtime timer,
837 	 * convert it to absolute; if an absolute time for a virtual
838 	 * timer, convert it to relative and make sure we don't set it
839 	 * to zero, which would cancel the timer, or let it go
840 	 * negative, which would confuse the comparison tests.
841 	 */
842 	if (timespecisset(&pt->pt_time.it_value)) {
843 		if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
844 			if ((flags & TIMER_ABSTIME) == 0) {
845 				if (pt->pt_type == CLOCK_REALTIME) {
846 					getnanotime(&now);
847 				} else { /* CLOCK_MONOTONIC */
848 					getnanouptime(&now);
849 				}
850 				timespecadd(&pt->pt_time.it_value, &now,
851 				    &pt->pt_time.it_value);
852 			}
853 		} else {
854 			if ((flags & TIMER_ABSTIME) != 0) {
855 				getnanotime(&now);
856 				timespecsub(&pt->pt_time.it_value, &now,
857 				    &pt->pt_time.it_value);
858 				if (!timespecisset(&pt->pt_time.it_value) ||
859 				    pt->pt_time.it_value.tv_sec < 0) {
860 					pt->pt_time.it_value.tv_sec = 0;
861 					pt->pt_time.it_value.tv_nsec = 1;
862 				}
863 			}
864 		}
865 	}
866 
867 	timer_settime(pt);
868 	mutex_spin_exit(&timer_lock);
869 
870 	if (ovalue)
871 		*ovalue = oval;
872 
873 	return (0);
874 }
875 
876 /* Return the time remaining until a POSIX timer fires. */
877 int
878 sys___timer_gettime50(struct lwp *l,
879     const struct sys___timer_gettime50_args *uap, register_t *retval)
880 {
881 	/* {
882 		syscallarg(timer_t) timerid;
883 		syscallarg(struct itimerspec *) value;
884 	} */
885 	struct itimerspec its;
886 	int error;
887 
888 	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
889 	    &its)) != 0)
890 		return error;
891 
892 	return copyout(&its, SCARG(uap, value), sizeof(its));
893 }
894 
895 int
896 dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
897 {
898 	struct ptimer *pt;
899 	struct ptimers *pts;
900 
901 	pts = p->p_timers;
902 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
903 		return (EINVAL);
904 	mutex_spin_enter(&timer_lock);
905 	if ((pt = pts->pts_timers[timerid]) == NULL) {
906 		mutex_spin_exit(&timer_lock);
907 		return (EINVAL);
908 	}
909 	timer_gettime(pt, its);
910 	mutex_spin_exit(&timer_lock);
911 
912 	return 0;
913 }
914 
915 /*
916  * Return the count of the number of times a periodic timer expired
917  * while a notification was already pending. The counter is reset when
918  * a timer expires and a notification can be posted.
919  */
920 int
921 sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
922     register_t *retval)
923 {
924 	/* {
925 		syscallarg(timer_t) timerid;
926 	} */
927 	struct proc *p = l->l_proc;
928 	struct ptimers *pts;
929 	int timerid;
930 	struct ptimer *pt;
931 
932 	timerid = SCARG(uap, timerid);
933 
934 	pts = p->p_timers;
935 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
936 		return (EINVAL);
937 	mutex_spin_enter(&timer_lock);
938 	if ((pt = pts->pts_timers[timerid]) == NULL) {
939 		mutex_spin_exit(&timer_lock);
940 		return (EINVAL);
941 	}
942 	*retval = pt->pt_poverruns;
943 	mutex_spin_exit(&timer_lock);
944 
945 	return (0);
946 }
947 
948 /*
949  * Real interval timer expired:
950  * send process whose timer expired an alarm signal.
951  * If time is not set up to reload, then just return.
952  * Else compute next time timer should go off which is > current time.
953  * This is where delay in processing this timeout causes multiple
954  * SIGALRM calls to be compressed into one.
955  */
956 void
957 realtimerexpire(void *arg)
958 {
959 	uint64_t last_val, next_val, interval, now_ns;
960 	struct timespec now, next;
961 	struct ptimer *pt;
962 	int backwards;
963 
964 	pt = arg;
965 
966 	mutex_spin_enter(&timer_lock);
967 	itimerfire(pt);
968 
969 	if (!timespecisset(&pt->pt_time.it_interval)) {
970 		timespecclear(&pt->pt_time.it_value);
971 		mutex_spin_exit(&timer_lock);
972 		return;
973 	}
974 
975 	if (pt->pt_type == CLOCK_MONOTONIC) {
976 		getnanouptime(&now);
977 	} else {
978 		getnanotime(&now);
979 	}
980 	backwards = (timespeccmp(&pt->pt_time.it_value, &now, >));
981 	timespecadd(&pt->pt_time.it_value, &pt->pt_time.it_interval, &next);
982 	/* Handle the easy case of non-overflown timers first. */
983 	if (!backwards && timespeccmp(&next, &now, >)) {
984 		pt->pt_time.it_value = next;
985 	} else {
986 		now_ns = timespec2ns(&now);
987 		last_val = timespec2ns(&pt->pt_time.it_value);
988 		interval = timespec2ns(&pt->pt_time.it_interval);
989 
990 		next_val = now_ns +
991 		    (now_ns - last_val + interval - 1) % interval;
992 
993 		if (backwards)
994 			next_val += interval;
995 		else
996 			pt->pt_overruns += (now_ns - last_val) / interval;
997 
998 		pt->pt_time.it_value.tv_sec = next_val / 1000000000;
999 		pt->pt_time.it_value.tv_nsec = next_val % 1000000000;
1000 	}
1001 
1002 	/*
1003 	 * Don't need to check tshzto() return value, here.
1004 	 * callout_reset() does it for us.
1005 	 */
1006 	callout_reset(&pt->pt_ch, pt->pt_type == CLOCK_MONOTONIC ?
1007 	    tshztoup(&pt->pt_time.it_value) : tshzto(&pt->pt_time.it_value),
1008 	    realtimerexpire, pt);
1009 	mutex_spin_exit(&timer_lock);
1010 }
1011 
1012 /* BSD routine to get the value of an interval timer. */
1013 /* ARGSUSED */
1014 int
1015 sys___getitimer50(struct lwp *l, const struct sys___getitimer50_args *uap,
1016     register_t *retval)
1017 {
1018 	/* {
1019 		syscallarg(int) which;
1020 		syscallarg(struct itimerval *) itv;
1021 	} */
1022 	struct proc *p = l->l_proc;
1023 	struct itimerval aitv;
1024 	int error;
1025 
1026 	error = dogetitimer(p, SCARG(uap, which), &aitv);
1027 	if (error)
1028 		return error;
1029 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
1030 }
1031 
1032 int
1033 dogetitimer(struct proc *p, int which, struct itimerval *itvp)
1034 {
1035 	struct ptimers *pts;
1036 	struct ptimer *pt;
1037 	struct itimerspec its;
1038 
1039 	if ((u_int)which > ITIMER_MONOTONIC)
1040 		return (EINVAL);
1041 
1042 	mutex_spin_enter(&timer_lock);
1043 	pts = p->p_timers;
1044 	if (pts == NULL || (pt = pts->pts_timers[which]) == NULL) {
1045 		timerclear(&itvp->it_value);
1046 		timerclear(&itvp->it_interval);
1047 	} else {
1048 		timer_gettime(pt, &its);
1049 		TIMESPEC_TO_TIMEVAL(&itvp->it_value, &its.it_value);
1050 		TIMESPEC_TO_TIMEVAL(&itvp->it_interval, &its.it_interval);
1051 	}
1052 	mutex_spin_exit(&timer_lock);
1053 
1054 	return 0;
1055 }
1056 
1057 /* BSD routine to set/arm an interval timer. */
1058 /* ARGSUSED */
1059 int
1060 sys___setitimer50(struct lwp *l, const struct sys___setitimer50_args *uap,
1061     register_t *retval)
1062 {
1063 	/* {
1064 		syscallarg(int) which;
1065 		syscallarg(const struct itimerval *) itv;
1066 		syscallarg(struct itimerval *) oitv;
1067 	} */
1068 	struct proc *p = l->l_proc;
1069 	int which = SCARG(uap, which);
1070 	struct sys___getitimer50_args getargs;
1071 	const struct itimerval *itvp;
1072 	struct itimerval aitv;
1073 	int error;
1074 
1075 	if ((u_int)which > ITIMER_MONOTONIC)
1076 		return (EINVAL);
1077 	itvp = SCARG(uap, itv);
1078 	if (itvp &&
1079 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval))) != 0)
1080 		return (error);
1081 	if (SCARG(uap, oitv) != NULL) {
1082 		SCARG(&getargs, which) = which;
1083 		SCARG(&getargs, itv) = SCARG(uap, oitv);
1084 		if ((error = sys___getitimer50(l, &getargs, retval)) != 0)
1085 			return (error);
1086 	}
1087 	if (itvp == 0)
1088 		return (0);
1089 
1090 	return dosetitimer(p, which, &aitv);
1091 }
1092 
1093 int
1094 dosetitimer(struct proc *p, int which, struct itimerval *itvp)
1095 {
1096 	struct timespec now;
1097 	struct ptimers *pts;
1098 	struct ptimer *pt, *spare;
1099 
1100 	KASSERT((u_int)which <= CLOCK_MONOTONIC);
1101 	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
1102 		return (EINVAL);
1103 
1104 	/*
1105 	 * Don't bother allocating data structures if the process just
1106 	 * wants to clear the timer.
1107 	 */
1108 	spare = NULL;
1109 	pts = p->p_timers;
1110  retry:
1111 	if (!timerisset(&itvp->it_value) && (pts == NULL ||
1112 	    pts->pts_timers[which] == NULL))
1113 		return (0);
1114 	if (pts == NULL)
1115 		pts = timers_alloc(p);
1116 	mutex_spin_enter(&timer_lock);
1117 	pt = pts->pts_timers[which];
1118 	if (pt == NULL) {
1119 		if (spare == NULL) {
1120 			mutex_spin_exit(&timer_lock);
1121 			spare = pool_get(&ptimer_pool, PR_WAITOK);
1122 			goto retry;
1123 		}
1124 		pt = spare;
1125 		spare = NULL;
1126 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
1127 		pt->pt_ev.sigev_value.sival_int = which;
1128 		pt->pt_overruns = 0;
1129 		pt->pt_proc = p;
1130 		pt->pt_type = which;
1131 		pt->pt_entry = which;
1132 		pt->pt_queued = false;
1133 		if (pt->pt_type == CLOCK_REALTIME)
1134 			callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
1135 		else
1136 			pt->pt_active = 0;
1137 
1138 		switch (which) {
1139 		case ITIMER_REAL:
1140 		case ITIMER_MONOTONIC:
1141 			pt->pt_ev.sigev_signo = SIGALRM;
1142 			break;
1143 		case ITIMER_VIRTUAL:
1144 			pt->pt_ev.sigev_signo = SIGVTALRM;
1145 			break;
1146 		case ITIMER_PROF:
1147 			pt->pt_ev.sigev_signo = SIGPROF;
1148 			break;
1149 		}
1150 		pts->pts_timers[which] = pt;
1151 	}
1152 
1153 	TIMEVAL_TO_TIMESPEC(&itvp->it_value, &pt->pt_time.it_value);
1154 	TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &pt->pt_time.it_interval);
1155 
1156 	if (timespecisset(&pt->pt_time.it_value)) {
1157 		/* Convert to absolute time */
1158 		/* XXX need to wrap in splclock for timecounters case? */
1159 		switch (which) {
1160 		case ITIMER_REAL:
1161 			getnanotime(&now);
1162 			timespecadd(&pt->pt_time.it_value, &now,
1163 			    &pt->pt_time.it_value);
1164 			break;
1165 		case ITIMER_MONOTONIC:
1166 			getnanouptime(&now);
1167 			timespecadd(&pt->pt_time.it_value, &now,
1168 			    &pt->pt_time.it_value);
1169 			break;
1170 		default:
1171 			break;
1172 		}
1173 	}
1174 	timer_settime(pt);
1175 	mutex_spin_exit(&timer_lock);
1176 	if (spare != NULL)
1177 		pool_put(&ptimer_pool, spare);
1178 
1179 	return (0);
1180 }
1181 
1182 /* Utility routines to manage the array of pointers to timers. */
1183 struct ptimers *
1184 timers_alloc(struct proc *p)
1185 {
1186 	struct ptimers *pts;
1187 	int i;
1188 
1189 	pts = pool_get(&ptimers_pool, PR_WAITOK);
1190 	LIST_INIT(&pts->pts_virtual);
1191 	LIST_INIT(&pts->pts_prof);
1192 	for (i = 0; i < TIMER_MAX; i++)
1193 		pts->pts_timers[i] = NULL;
1194 	pts->pts_fired = 0;
1195 	mutex_spin_enter(&timer_lock);
1196 	if (p->p_timers == NULL) {
1197 		p->p_timers = pts;
1198 		mutex_spin_exit(&timer_lock);
1199 		return pts;
1200 	}
1201 	mutex_spin_exit(&timer_lock);
1202 	pool_put(&ptimers_pool, pts);
1203 	return p->p_timers;
1204 }
1205 
1206 /*
1207  * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
1208  * then clean up all timers and free all the data structures. If
1209  * "which" is set to TIMERS_POSIX, only clean up the timers allocated
1210  * by timer_create(), not the BSD setitimer() timers, and only free the
1211  * structure if none of those remain.
1212  */
1213 void
1214 timers_free(struct proc *p, int which)
1215 {
1216 	struct ptimers *pts;
1217 	struct ptimer *ptn;
1218 	struct timespec ts;
1219 	int i;
1220 
1221 	if (p->p_timers == NULL)
1222 		return;
1223 
1224 	pts = p->p_timers;
1225 	mutex_spin_enter(&timer_lock);
1226 	if (which == TIMERS_ALL) {
1227 		p->p_timers = NULL;
1228 		i = 0;
1229 	} else {
1230 		timespecclear(&ts);
1231 		for (ptn = LIST_FIRST(&pts->pts_virtual);
1232 		     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
1233 		     ptn = LIST_NEXT(ptn, pt_list)) {
1234 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
1235 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
1236 		}
1237 		LIST_FIRST(&pts->pts_virtual) = NULL;
1238 		if (ptn) {
1239 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
1240 			timespecadd(&ts, &ptn->pt_time.it_value,
1241 			    &ptn->pt_time.it_value);
1242 			LIST_INSERT_HEAD(&pts->pts_virtual, ptn, pt_list);
1243 		}
1244 		timespecclear(&ts);
1245 		for (ptn = LIST_FIRST(&pts->pts_prof);
1246 		     ptn && ptn != pts->pts_timers[ITIMER_PROF];
1247 		     ptn = LIST_NEXT(ptn, pt_list)) {
1248 			KASSERT(ptn->pt_type == CLOCK_PROF);
1249 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
1250 		}
1251 		LIST_FIRST(&pts->pts_prof) = NULL;
1252 		if (ptn) {
1253 			KASSERT(ptn->pt_type == CLOCK_PROF);
1254 			timespecadd(&ts, &ptn->pt_time.it_value,
1255 			    &ptn->pt_time.it_value);
1256 			LIST_INSERT_HEAD(&pts->pts_prof, ptn, pt_list);
1257 		}
1258 		i = 3;
1259 	}
1260 	for ( ; i < TIMER_MAX; i++) {
1261 		if (pts->pts_timers[i] != NULL) {
1262 			itimerfree(pts, i);
1263 			mutex_spin_enter(&timer_lock);
1264 		}
1265 	}
1266 	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
1267 	    pts->pts_timers[2] == NULL) {
1268 		p->p_timers = NULL;
1269 		mutex_spin_exit(&timer_lock);
1270 		pool_put(&ptimers_pool, pts);
1271 	} else
1272 		mutex_spin_exit(&timer_lock);
1273 }
1274 
1275 static void
1276 itimerfree(struct ptimers *pts, int index)
1277 {
1278 	struct ptimer *pt;
1279 
1280 	KASSERT(mutex_owned(&timer_lock));
1281 
1282 	pt = pts->pts_timers[index];
1283 	pts->pts_timers[index] = NULL;
1284 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
1285 		callout_halt(&pt->pt_ch, &timer_lock);
1286 	if (pt->pt_queued)
1287 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1288 	mutex_spin_exit(&timer_lock);
1289 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
1290 		callout_destroy(&pt->pt_ch);
1291 	pool_put(&ptimer_pool, pt);
1292 }
1293 
1294 /*
1295  * Decrement an interval timer by a specified number
1296  * of nanoseconds, which must be less than a second,
1297  * i.e. < 1000000000.  If the timer expires, then reload
1298  * it.  In this case, carry over (nsec - old value) to
1299  * reduce the value reloaded into the timer so that
1300  * the timer does not drift.  This routine assumes
1301  * that it is called in a context where the timers
1302  * on which it is operating cannot change in value.
1303  */
1304 static int
1305 itimerdecr(struct ptimer *pt, int nsec)
1306 {
1307 	struct itimerspec *itp;
1308 
1309 	KASSERT(mutex_owned(&timer_lock));
1310 	KASSERT(CLOCK_VIRTUAL_P(pt->pt_type));
1311 
1312 	itp = &pt->pt_time;
1313 	if (itp->it_value.tv_nsec < nsec) {
1314 		if (itp->it_value.tv_sec == 0) {
1315 			/* expired, and already in next interval */
1316 			nsec -= itp->it_value.tv_nsec;
1317 			goto expire;
1318 		}
1319 		itp->it_value.tv_nsec += 1000000000;
1320 		itp->it_value.tv_sec--;
1321 	}
1322 	itp->it_value.tv_nsec -= nsec;
1323 	nsec = 0;
1324 	if (timespecisset(&itp->it_value))
1325 		return (1);
1326 	/* expired, exactly at end of interval */
1327 expire:
1328 	if (timespecisset(&itp->it_interval)) {
1329 		itp->it_value = itp->it_interval;
1330 		itp->it_value.tv_nsec -= nsec;
1331 		if (itp->it_value.tv_nsec < 0) {
1332 			itp->it_value.tv_nsec += 1000000000;
1333 			itp->it_value.tv_sec--;
1334 		}
1335 		timer_settime(pt);
1336 	} else
1337 		itp->it_value.tv_nsec = 0;		/* sec is already 0 */
1338 	return (0);
1339 }
1340 
1341 static void
1342 itimerfire(struct ptimer *pt)
1343 {
1344 
1345 	KASSERT(mutex_owned(&timer_lock));
1346 
1347 	/*
1348 	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
1349 	 * XXX Relying on the clock interrupt is stupid.
1350 	 */
1351 	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL || pt->pt_queued) {
1352 		return;
1353 	}
1354 	TAILQ_INSERT_TAIL(&timer_queue, pt, pt_chain);
1355 	pt->pt_queued = true;
1356 	softint_schedule(timer_sih);
1357 }
1358 
1359 void
1360 timer_tick(lwp_t *l, bool user)
1361 {
1362 	struct ptimers *pts;
1363 	struct ptimer *pt;
1364 	proc_t *p;
1365 
1366 	p = l->l_proc;
1367 	if (p->p_timers == NULL)
1368 		return;
1369 
1370 	mutex_spin_enter(&timer_lock);
1371 	if ((pts = l->l_proc->p_timers) != NULL) {
1372 		/*
1373 		 * Run current process's virtual and profile time, as needed.
1374 		 */
1375 		if (user && (pt = LIST_FIRST(&pts->pts_virtual)) != NULL)
1376 			if (itimerdecr(pt, tick * 1000) == 0)
1377 				itimerfire(pt);
1378 		if ((pt = LIST_FIRST(&pts->pts_prof)) != NULL)
1379 			if (itimerdecr(pt, tick * 1000) == 0)
1380 				itimerfire(pt);
1381 	}
1382 	mutex_spin_exit(&timer_lock);
1383 }
1384 
1385 static void
1386 timer_intr(void *cookie)
1387 {
1388 	ksiginfo_t ksi;
1389 	struct ptimer *pt;
1390 	proc_t *p;
1391 
1392 	mutex_enter(proc_lock);
1393 	mutex_spin_enter(&timer_lock);
1394 	while ((pt = TAILQ_FIRST(&timer_queue)) != NULL) {
1395 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1396 		KASSERT(pt->pt_queued);
1397 		pt->pt_queued = false;
1398 
1399 		if (pt->pt_proc->p_timers == NULL) {
1400 			/* Process is dying. */
1401 			continue;
1402 		}
1403 		p = pt->pt_proc;
1404 		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
1405 			continue;
1406 		}
1407 		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
1408 			pt->pt_overruns++;
1409 			continue;
1410 		}
1411 
1412 		KSI_INIT(&ksi);
1413 		ksi.ksi_signo = pt->pt_ev.sigev_signo;
1414 		ksi.ksi_code = SI_TIMER;
1415 		ksi.ksi_value = pt->pt_ev.sigev_value;
1416 		pt->pt_poverruns = pt->pt_overruns;
1417 		pt->pt_overruns = 0;
1418 		mutex_spin_exit(&timer_lock);
1419 		kpsignal(p, &ksi, NULL);
1420 		mutex_spin_enter(&timer_lock);
1421 	}
1422 	mutex_spin_exit(&timer_lock);
1423 	mutex_exit(proc_lock);
1424 }
1425 
1426 /*
1427  * Check if the time will wrap if set to ts.
1428  *
1429  * ts - timespec describing the new time
1430  * delta - the delta between the current time and ts
1431  */
1432 bool
1433 time_wraps(struct timespec *ts, struct timespec *delta)
1434 {
1435 
1436 	/*
1437 	 * Don't allow the time to be set forward so far it
1438 	 * will wrap and become negative, thus allowing an
1439 	 * attacker to bypass the next check below.  The
1440 	 * cutoff is 1 year before rollover occurs, so even
1441 	 * if the attacker uses adjtime(2) to move the time
1442 	 * past the cutoff, it will take a very long time
1443 	 * to get to the wrap point.
1444 	 */
1445 	if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
1446 	    (delta->tv_sec < 0 || delta->tv_nsec < 0))
1447 		return true;
1448 
1449 	return false;
1450 }
1451