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