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