xref: /netbsd-src/sys/kern/kern_time.c (revision cac8e449158efc7261bebc8657cbb0125a2cfdde)
1 /*	$NetBSD: kern_time.c,v 1.150 2008/07/15 16:18:08 christos 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.150 2008/07/15 16:18:08 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 #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 	timespecclear(&pt->pt_time.it_value);
594 	if (id == CLOCK_REALTIME)
595 		callout_init(&pt->pt_ch, 0);
596 	else
597 		pt->pt_active = 0;
598 
599 	pts->pts_timers[timerid] = pt;
600 	mutex_spin_exit(&timer_lock);
601 
602 	return copyout(&timerid, tid, sizeof(timerid));
603 }
604 
605 /* Delete a POSIX realtime timer */
606 int
607 sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
608     register_t *retval)
609 {
610 	/* {
611 		syscallarg(timer_t) timerid;
612 	} */
613 	struct proc *p = l->l_proc;
614 	timer_t timerid;
615 	struct ptimers *pts;
616 	struct ptimer *pt, *ptn;
617 
618 	timerid = SCARG(uap, timerid);
619 	pts = p->p_timers;
620 
621 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
622 		return (EINVAL);
623 
624 	mutex_spin_enter(&timer_lock);
625 	if ((pt = pts->pts_timers[timerid]) == NULL) {
626 		mutex_spin_exit(&timer_lock);
627 		return (EINVAL);
628 	}
629 	if (pt->pt_type != CLOCK_REALTIME) {
630 		if (pt->pt_active) {
631 			ptn = LIST_NEXT(pt, pt_list);
632 			LIST_REMOVE(pt, pt_list);
633 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
634 				timespecadd(&pt->pt_time.it_value,
635 				    &ptn->pt_time.it_value,
636 				    &ptn->pt_time.it_value);
637 			pt->pt_active = 0;
638 		}
639 	}
640 	itimerfree(pts, timerid);
641 
642 	return (0);
643 }
644 
645 /*
646  * Set up the given timer. The value in pt->pt_time.it_value is taken
647  * to be an absolute time for CLOCK_REALTIME timers and a relative
648  * time for virtual timers.
649  * Must be called at splclock().
650  */
651 void
652 timer_settime(struct ptimer *pt)
653 {
654 	struct ptimer *ptn, *pptn;
655 	struct ptlist *ptl;
656 
657 	KASSERT(mutex_owned(&timer_lock));
658 
659 	if (pt->pt_type == CLOCK_REALTIME) {
660 		callout_stop(&pt->pt_ch);
661 		if (timespecisset(&pt->pt_time.it_value)) {
662 			/*
663 			 * Don't need to check tshzto() return value, here.
664 			 * callout_reset() does it for us.
665 			 */
666 			callout_reset(&pt->pt_ch, tshzto(&pt->pt_time.it_value),
667 			    realtimerexpire, pt);
668 		}
669 	} else {
670 		if (pt->pt_active) {
671 			ptn = LIST_NEXT(pt, pt_list);
672 			LIST_REMOVE(pt, pt_list);
673 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
674 				timespecadd(&pt->pt_time.it_value,
675 				    &ptn->pt_time.it_value,
676 				    &ptn->pt_time.it_value);
677 		}
678 		if (timespecisset(&pt->pt_time.it_value)) {
679 			if (pt->pt_type == CLOCK_VIRTUAL)
680 				ptl = &pt->pt_proc->p_timers->pts_virtual;
681 			else
682 				ptl = &pt->pt_proc->p_timers->pts_prof;
683 
684 			for (ptn = LIST_FIRST(ptl), pptn = NULL;
685 			     ptn && timespeccmp(&pt->pt_time.it_value,
686 				 &ptn->pt_time.it_value, >);
687 			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
688 				timespecsub(&pt->pt_time.it_value,
689 				    &ptn->pt_time.it_value,
690 				    &pt->pt_time.it_value);
691 
692 			if (pptn)
693 				LIST_INSERT_AFTER(pptn, pt, pt_list);
694 			else
695 				LIST_INSERT_HEAD(ptl, pt, pt_list);
696 
697 			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
698 				timespecsub(&ptn->pt_time.it_value,
699 				    &pt->pt_time.it_value,
700 				    &ptn->pt_time.it_value);
701 
702 			pt->pt_active = 1;
703 		} else
704 			pt->pt_active = 0;
705 	}
706 }
707 
708 void
709 timer_gettime(struct ptimer *pt, struct itimerspec *aits)
710 {
711 	struct timespec now;
712 	struct ptimer *ptn;
713 
714 	KASSERT(mutex_owned(&timer_lock));
715 
716 	*aits = pt->pt_time;
717 	if (pt->pt_type == CLOCK_REALTIME) {
718 		/*
719 		 * Convert from absolute to relative time in .it_value
720 		 * part of real time timer.  If time for real time
721 		 * timer has passed return 0, else return difference
722 		 * between current time and time for the timer to go
723 		 * off.
724 		 */
725 		if (timespecisset(&aits->it_value)) {
726 			getnanotime(&now);
727 			if (timespeccmp(&aits->it_value, &now, <))
728 				timespecclear(&aits->it_value);
729 			else
730 				timespecsub(&aits->it_value, &now,
731 				    &aits->it_value);
732 		}
733 	} else if (pt->pt_active) {
734 		if (pt->pt_type == CLOCK_VIRTUAL)
735 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
736 		else
737 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
738 		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
739 			timespecadd(&aits->it_value,
740 			    &ptn->pt_time.it_value, &aits->it_value);
741 		KASSERT(ptn != NULL); /* pt should be findable on the list */
742 	} else
743 		timespecclear(&aits->it_value);
744 }
745 
746 
747 
748 /* Set and arm a POSIX realtime timer */
749 int
750 sys_timer_settime(struct lwp *l, const struct sys_timer_settime_args *uap,
751     register_t *retval)
752 {
753 	/* {
754 		syscallarg(timer_t) timerid;
755 		syscallarg(int) flags;
756 		syscallarg(const struct itimerspec *) value;
757 		syscallarg(struct itimerspec *) ovalue;
758 	} */
759 	int error;
760 	struct itimerspec value, ovalue, *ovp = NULL;
761 
762 	if ((error = copyin(SCARG(uap, value), &value,
763 	    sizeof(struct itimerspec))) != 0)
764 		return (error);
765 
766 	if (SCARG(uap, ovalue))
767 		ovp = &ovalue;
768 
769 	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
770 	    SCARG(uap, flags), l->l_proc)) != 0)
771 		return error;
772 
773 	if (ovp)
774 		return copyout(&ovalue, SCARG(uap, ovalue),
775 		    sizeof(struct itimerspec));
776 	return 0;
777 }
778 
779 int
780 dotimer_settime(int timerid, struct itimerspec *value,
781     struct itimerspec *ovalue, int flags, struct proc *p)
782 {
783 	struct timespec now;
784 	struct itimerspec val, oval;
785 	struct ptimers *pts;
786 	struct ptimer *pt;
787 
788 	pts = p->p_timers;
789 
790 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
791 		return EINVAL;
792 	val = *value;
793 	if (itimespecfix(&val.it_value) || itimespecfix(&val.it_interval))
794 		return EINVAL;
795 
796 	mutex_spin_enter(&timer_lock);
797 	if ((pt = pts->pts_timers[timerid]) == NULL) {
798 		mutex_spin_exit(&timer_lock);
799 		return EINVAL;
800 	}
801 
802 	oval = pt->pt_time;
803 	pt->pt_time = val;
804 
805 	/*
806 	 * If we've been passed a relative time for a realtime timer,
807 	 * convert it to absolute; if an absolute time for a virtual
808 	 * timer, convert it to relative and make sure we don't set it
809 	 * to zero, which would cancel the timer, or let it go
810 	 * negative, which would confuse the comparison tests.
811 	 */
812 	if (timespecisset(&pt->pt_time.it_value)) {
813 		if (pt->pt_type == CLOCK_REALTIME) {
814 			if ((flags & TIMER_ABSTIME) == 0) {
815 				getnanotime(&now);
816 				timespecadd(&pt->pt_time.it_value, &now,
817 				    &pt->pt_time.it_value);
818 			}
819 		} else {
820 			if ((flags & TIMER_ABSTIME) != 0) {
821 				getnanotime(&now);
822 				timespecsub(&pt->pt_time.it_value, &now,
823 				    &pt->pt_time.it_value);
824 				if (!timespecisset(&pt->pt_time.it_value) ||
825 				    pt->pt_time.it_value.tv_sec < 0) {
826 					pt->pt_time.it_value.tv_sec = 0;
827 					pt->pt_time.it_value.tv_nsec = 1;
828 				}
829 			}
830 		}
831 	}
832 
833 	timer_settime(pt);
834 	mutex_spin_exit(&timer_lock);
835 
836 	if (ovalue)
837 		*ovalue = oval;
838 
839 	return (0);
840 }
841 
842 /* Return the time remaining until a POSIX timer fires. */
843 int
844 sys_timer_gettime(struct lwp *l, const struct sys_timer_gettime_args *uap,
845     register_t *retval)
846 {
847 	/* {
848 		syscallarg(timer_t) timerid;
849 		syscallarg(struct itimerspec *) value;
850 	} */
851 	struct itimerspec its;
852 	int error;
853 
854 	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
855 	    &its)) != 0)
856 		return error;
857 
858 	return copyout(&its, SCARG(uap, value), sizeof(its));
859 }
860 
861 int
862 dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
863 {
864 	struct ptimer *pt;
865 	struct ptimers *pts;
866 
867 	pts = p->p_timers;
868 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
869 		return (EINVAL);
870 	mutex_spin_enter(&timer_lock);
871 	if ((pt = pts->pts_timers[timerid]) == NULL) {
872 		mutex_spin_exit(&timer_lock);
873 		return (EINVAL);
874 	}
875 	timer_gettime(pt, its);
876 	mutex_spin_exit(&timer_lock);
877 
878 	return 0;
879 }
880 
881 /*
882  * Return the count of the number of times a periodic timer expired
883  * while a notification was already pending. The counter is reset when
884  * a timer expires and a notification can be posted.
885  */
886 int
887 sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
888     register_t *retval)
889 {
890 	/* {
891 		syscallarg(timer_t) timerid;
892 	} */
893 	struct proc *p = l->l_proc;
894 	struct ptimers *pts;
895 	int timerid;
896 	struct ptimer *pt;
897 
898 	timerid = SCARG(uap, timerid);
899 
900 	pts = p->p_timers;
901 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
902 		return (EINVAL);
903 	mutex_spin_enter(&timer_lock);
904 	if ((pt = pts->pts_timers[timerid]) == NULL) {
905 		mutex_spin_exit(&timer_lock);
906 		return (EINVAL);
907 	}
908 	*retval = pt->pt_poverruns;
909 	mutex_spin_exit(&timer_lock);
910 
911 	return (0);
912 }
913 
914 /*
915  * Real interval timer expired:
916  * send process whose timer expired an alarm signal.
917  * If time is not set up to reload, then just return.
918  * Else compute next time timer should go off which is > current time.
919  * This is where delay in processing this timeout causes multiple
920  * SIGALRM calls to be compressed into one.
921  */
922 void
923 realtimerexpire(void *arg)
924 {
925 	uint64_t last_val, next_val, interval, now_ms;
926 	struct timespec now, next;
927 	struct ptimer *pt;
928 	int backwards;
929 
930 	pt = arg;
931 
932 	mutex_spin_enter(&timer_lock);
933 	itimerfire(pt);
934 
935 	if (!timespecisset(&pt->pt_time.it_interval)) {
936 		timespecclear(&pt->pt_time.it_value);
937 		mutex_spin_exit(&timer_lock);
938 		return;
939 	}
940 
941 	getnanotime(&now);
942 	backwards = (timespeccmp(&pt->pt_time.it_value, &now, >));
943 	timespecadd(&pt->pt_time.it_value, &pt->pt_time.it_interval, &next);
944 	/* Handle the easy case of non-overflown timers first. */
945 	if (!backwards && timespeccmp(&next, &now, >)) {
946 		pt->pt_time.it_value = next;
947 	} else {
948 		now_ms = timespec2ns(&now);
949 		last_val = timespec2ns(&pt->pt_time.it_value);
950 		interval = timespec2ns(&pt->pt_time.it_interval);
951 
952 		next_val = now_ms +
953 		    (now_ms - last_val + interval - 1) % interval;
954 
955 		if (backwards)
956 			next_val += interval;
957 		else
958 			pt->pt_overruns += (now_ms - last_val) / interval;
959 
960 		pt->pt_time.it_value.tv_sec = next_val / 1000000000;
961 		pt->pt_time.it_value.tv_nsec = next_val % 1000000000;
962 	}
963 
964 	/*
965 	 * Don't need to check tshzto() return value, here.
966 	 * callout_reset() does it for us.
967 	 */
968 	callout_reset(&pt->pt_ch, tshzto(&pt->pt_time.it_value),
969 	    realtimerexpire, pt);
970 	mutex_spin_exit(&timer_lock);
971 }
972 
973 /* BSD routine to get the value of an interval timer. */
974 /* ARGSUSED */
975 int
976 sys_getitimer(struct lwp *l, const struct sys_getitimer_args *uap,
977     register_t *retval)
978 {
979 	/* {
980 		syscallarg(int) which;
981 		syscallarg(struct itimerval *) itv;
982 	} */
983 	struct proc *p = l->l_proc;
984 	struct itimerval aitv;
985 	int error;
986 
987 	error = dogetitimer(p, SCARG(uap, which), &aitv);
988 	if (error)
989 		return error;
990 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
991 }
992 
993 int
994 dogetitimer(struct proc *p, int which, struct itimerval *itvp)
995 {
996 	struct ptimers *pts;
997 	struct ptimer *pt;
998 	struct itimerspec its;
999 
1000 	if ((u_int)which > ITIMER_PROF)
1001 		return (EINVAL);
1002 
1003 	mutex_spin_enter(&timer_lock);
1004 	pts = p->p_timers;
1005 	if (pts == NULL || (pt = pts->pts_timers[which]) == NULL) {
1006 		timerclear(&itvp->it_value);
1007 		timerclear(&itvp->it_interval);
1008 	} else {
1009 		TIMEVAL_TO_TIMESPEC(&itvp->it_value, &its.it_value);
1010 		TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &its.it_interval);
1011 		timer_gettime(pt, &its);
1012 	}
1013 	mutex_spin_exit(&timer_lock);
1014 
1015 	return 0;
1016 }
1017 
1018 /* BSD routine to set/arm an interval timer. */
1019 /* ARGSUSED */
1020 int
1021 sys_setitimer(struct lwp *l, const struct sys_setitimer_args *uap,
1022     register_t *retval)
1023 {
1024 	/* {
1025 		syscallarg(int) which;
1026 		syscallarg(const struct itimerval *) itv;
1027 		syscallarg(struct itimerval *) oitv;
1028 	} */
1029 	struct proc *p = l->l_proc;
1030 	int which = SCARG(uap, which);
1031 	struct sys_getitimer_args getargs;
1032 	const struct itimerval *itvp;
1033 	struct itimerval aitv;
1034 	int error;
1035 
1036 	if ((u_int)which > ITIMER_PROF)
1037 		return (EINVAL);
1038 	itvp = SCARG(uap, itv);
1039 	if (itvp &&
1040 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval)) != 0))
1041 		return (error);
1042 	if (SCARG(uap, oitv) != NULL) {
1043 		SCARG(&getargs, which) = which;
1044 		SCARG(&getargs, itv) = SCARG(uap, oitv);
1045 		if ((error = sys_getitimer(l, &getargs, retval)) != 0)
1046 			return (error);
1047 	}
1048 	if (itvp == 0)
1049 		return (0);
1050 
1051 	return dosetitimer(p, which, &aitv);
1052 }
1053 
1054 int
1055 dosetitimer(struct proc *p, int which, struct itimerval *itvp)
1056 {
1057 	struct timespec now;
1058 	struct ptimers *pts;
1059 	struct ptimer *pt, *spare;
1060 
1061 	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
1062 		return (EINVAL);
1063 
1064 	/*
1065 	 * Don't bother allocating data structures if the process just
1066 	 * wants to clear the timer.
1067 	 */
1068 	spare = NULL;
1069 	pts = p->p_timers;
1070  retry:
1071 	if (!timerisset(&itvp->it_value) && (pts == NULL ||
1072 	    pts->pts_timers[which] == NULL))
1073 		return (0);
1074 	if (pts == NULL)
1075 		pts = timers_alloc(p);
1076 	mutex_spin_enter(&timer_lock);
1077 	pt = pts->pts_timers[which];
1078 	if (pt == NULL) {
1079 		if (spare == NULL) {
1080 			mutex_spin_exit(&timer_lock);
1081 			spare = pool_get(&ptimer_pool, PR_WAITOK);
1082 			goto retry;
1083 		}
1084 		pt = spare;
1085 		spare = NULL;
1086 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
1087 		pt->pt_ev.sigev_value.sival_int = which;
1088 		pt->pt_overruns = 0;
1089 		pt->pt_proc = p;
1090 		pt->pt_type = which;
1091 		pt->pt_entry = which;
1092 		pt->pt_queued = false;
1093 		if (pt->pt_type == CLOCK_REALTIME)
1094 			callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
1095 		else
1096 			pt->pt_active = 0;
1097 
1098 		switch (which) {
1099 		case ITIMER_REAL:
1100 			pt->pt_ev.sigev_signo = SIGALRM;
1101 			break;
1102 		case ITIMER_VIRTUAL:
1103 			pt->pt_ev.sigev_signo = SIGVTALRM;
1104 			break;
1105 		case ITIMER_PROF:
1106 			pt->pt_ev.sigev_signo = SIGPROF;
1107 			break;
1108 		}
1109 		pts->pts_timers[which] = pt;
1110 	}
1111 
1112 	TIMEVAL_TO_TIMESPEC(&itvp->it_value, &pt->pt_time.it_value);
1113 	TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &pt->pt_time.it_interval);
1114 
1115 	if ((which == ITIMER_REAL) && timespecisset(&pt->pt_time.it_value)) {
1116 		/* Convert to absolute time */
1117 		/* XXX need to wrap in splclock for timecounters case? */
1118 		getnanotime(&now);
1119 		timespecadd(&pt->pt_time.it_value, &now, &pt->pt_time.it_value);
1120 	}
1121 	timer_settime(pt);
1122 	mutex_spin_exit(&timer_lock);
1123 	if (spare != NULL)
1124 		pool_put(&ptimer_pool, spare);
1125 
1126 	return (0);
1127 }
1128 
1129 /* Utility routines to manage the array of pointers to timers. */
1130 struct ptimers *
1131 timers_alloc(struct proc *p)
1132 {
1133 	struct ptimers *pts;
1134 	int i;
1135 
1136 	pts = pool_get(&ptimers_pool, PR_WAITOK);
1137 	LIST_INIT(&pts->pts_virtual);
1138 	LIST_INIT(&pts->pts_prof);
1139 	for (i = 0; i < TIMER_MAX; i++)
1140 		pts->pts_timers[i] = NULL;
1141 	pts->pts_fired = 0;
1142 	mutex_spin_enter(&timer_lock);
1143 	if (p->p_timers == NULL) {
1144 		p->p_timers = pts;
1145 		mutex_spin_exit(&timer_lock);
1146 		return pts;
1147 	}
1148 	mutex_spin_exit(&timer_lock);
1149 	pool_put(&ptimers_pool, pts);
1150 	return p->p_timers;
1151 }
1152 
1153 /*
1154  * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
1155  * then clean up all timers and free all the data structures. If
1156  * "which" is set to TIMERS_POSIX, only clean up the timers allocated
1157  * by timer_create(), not the BSD setitimer() timers, and only free the
1158  * structure if none of those remain.
1159  */
1160 void
1161 timers_free(struct proc *p, int which)
1162 {
1163 	struct ptimers *pts;
1164 	struct ptimer *ptn;
1165 	struct timespec ts;
1166 	int i;
1167 
1168 	if (p->p_timers == NULL)
1169 		return;
1170 
1171 	pts = p->p_timers;
1172 	mutex_spin_enter(&timer_lock);
1173 	if (which == TIMERS_ALL) {
1174 		p->p_timers = NULL;
1175 		i = 0;
1176 	} else {
1177 		timespecclear(&ts);
1178 		for (ptn = LIST_FIRST(&pts->pts_virtual);
1179 		     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
1180 		     ptn = LIST_NEXT(ptn, pt_list)) {
1181 			KASSERT(ptn->pt_type != CLOCK_REALTIME);
1182 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
1183 		}
1184 		LIST_FIRST(&pts->pts_virtual) = NULL;
1185 		if (ptn) {
1186 			KASSERT(ptn->pt_type != CLOCK_REALTIME);
1187 			timespecadd(&ts, &ptn->pt_time.it_value,
1188 			    &ptn->pt_time.it_value);
1189 			LIST_INSERT_HEAD(&pts->pts_virtual, ptn, pt_list);
1190 		}
1191 		timespecclear(&ts);
1192 		for (ptn = LIST_FIRST(&pts->pts_prof);
1193 		     ptn && ptn != pts->pts_timers[ITIMER_PROF];
1194 		     ptn = LIST_NEXT(ptn, pt_list)) {
1195 			KASSERT(ptn->pt_type != CLOCK_REALTIME);
1196 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
1197 		}
1198 		LIST_FIRST(&pts->pts_prof) = NULL;
1199 		if (ptn) {
1200 			KASSERT(ptn->pt_type != CLOCK_REALTIME);
1201 			timespecadd(&ts, &ptn->pt_time.it_value,
1202 			    &ptn->pt_time.it_value);
1203 			LIST_INSERT_HEAD(&pts->pts_prof, ptn, pt_list);
1204 		}
1205 		i = 3;
1206 	}
1207 	for ( ; i < TIMER_MAX; i++) {
1208 		if (pts->pts_timers[i] != NULL) {
1209 			itimerfree(pts, i);
1210 			mutex_spin_enter(&timer_lock);
1211 		}
1212 	}
1213 	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
1214 	    pts->pts_timers[2] == NULL) {
1215 		p->p_timers = NULL;
1216 		mutex_spin_exit(&timer_lock);
1217 		pool_put(&ptimers_pool, pts);
1218 	} else
1219 		mutex_spin_exit(&timer_lock);
1220 }
1221 
1222 static void
1223 itimerfree(struct ptimers *pts, int index)
1224 {
1225 	struct ptimer *pt;
1226 
1227 	KASSERT(mutex_owned(&timer_lock));
1228 
1229 	pt = pts->pts_timers[index];
1230 	pts->pts_timers[index] = NULL;
1231 	if (pt->pt_type == CLOCK_REALTIME)
1232 		callout_halt(&pt->pt_ch, &timer_lock);
1233 	else if (pt->pt_queued)
1234 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1235 	mutex_spin_exit(&timer_lock);
1236 	if (pt->pt_type == CLOCK_REALTIME)
1237 		callout_destroy(&pt->pt_ch);
1238 	pool_put(&ptimer_pool, pt);
1239 }
1240 
1241 /*
1242  * Decrement an interval timer by a specified number
1243  * of microseconds, which must be less than a second,
1244  * i.e. < 1000000.  If the timer expires, then reload
1245  * it.  In this case, carry over (usec - old value) to
1246  * reduce the value reloaded into the timer so that
1247  * the timer does not drift.  This routine assumes
1248  * that it is called in a context where the timers
1249  * on which it is operating cannot change in value.
1250  */
1251 static int
1252 itimerdecr(struct ptimer *pt, int usec)
1253 {
1254 	struct itimerspec *itp;
1255 	int nsec = usec * 1000;
1256 
1257 	KASSERT(mutex_owned(&timer_lock));
1258 
1259 	itp = &pt->pt_time;
1260 	if (itp->it_value.tv_nsec < nsec) {
1261 		if (itp->it_value.tv_sec == 0) {
1262 			/* expired, and already in next interval */
1263 			nsec -= itp->it_value.tv_nsec;
1264 			goto expire;
1265 		}
1266 		itp->it_value.tv_nsec += 1000000000;
1267 		itp->it_value.tv_sec--;
1268 	}
1269 	itp->it_value.tv_nsec -= usec;
1270 	usec = 0;
1271 	if (timespecisset(&itp->it_value))
1272 		return (1);
1273 	/* expired, exactly at end of interval */
1274 expire:
1275 	if (timespecisset(&itp->it_interval)) {
1276 		itp->it_value = itp->it_interval;
1277 		itp->it_value.tv_nsec -= nsec;
1278 		if (itp->it_value.tv_nsec < 0) {
1279 			itp->it_value.tv_nsec += 1000000000;
1280 			itp->it_value.tv_sec--;
1281 		}
1282 		timer_settime(pt);
1283 	} else
1284 		itp->it_value.tv_nsec = 0;		/* sec is already 0 */
1285 	return (0);
1286 }
1287 
1288 static void
1289 itimerfire(struct ptimer *pt)
1290 {
1291 
1292 	KASSERT(mutex_owned(&timer_lock));
1293 
1294 	/*
1295 	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
1296 	 * XXX Relying on the clock interrupt is stupid.
1297 	 */
1298 	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL || pt->pt_queued)
1299 		return;
1300 	TAILQ_INSERT_TAIL(&timer_queue, pt, pt_chain);
1301 	pt->pt_queued = true;
1302 	softint_schedule(timer_sih);
1303 }
1304 
1305 void
1306 timer_tick(lwp_t *l, bool user)
1307 {
1308 	struct ptimers *pts;
1309 	struct ptimer *pt;
1310 	proc_t *p;
1311 
1312 	p = l->l_proc;
1313 	if (p->p_timers == NULL)
1314 		return;
1315 
1316 	mutex_spin_enter(&timer_lock);
1317 	if ((pts = l->l_proc->p_timers) != NULL) {
1318 		/*
1319 		 * Run current process's virtual and profile time, as needed.
1320 		 */
1321 		if (user && (pt = LIST_FIRST(&pts->pts_virtual)) != NULL)
1322 			if (itimerdecr(pt, tick) == 0)
1323 				itimerfire(pt);
1324 		if ((pt = LIST_FIRST(&pts->pts_prof)) != NULL)
1325 			if (itimerdecr(pt, tick) == 0)
1326 				itimerfire(pt);
1327 	}
1328 	mutex_spin_exit(&timer_lock);
1329 }
1330 
1331 static void
1332 timer_intr(void *cookie)
1333 {
1334 	ksiginfo_t ksi;
1335 	struct ptimer *pt;
1336 	proc_t *p;
1337 
1338 	mutex_spin_enter(&timer_lock);
1339 	while ((pt = TAILQ_FIRST(&timer_queue)) != NULL) {
1340 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1341 		KASSERT(pt->pt_queued);
1342 		pt->pt_queued = false;
1343 
1344 		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL)
1345 			continue;
1346 		p = pt->pt_proc;
1347 		if (pt->pt_proc->p_timers == NULL) {
1348 			/* Process is dying. */
1349 			continue;
1350 		}
1351 		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
1352 			pt->pt_overruns++;
1353 			continue;
1354 		}
1355 
1356 		KSI_INIT(&ksi);
1357 		ksi.ksi_signo = pt->pt_ev.sigev_signo;
1358 		ksi.ksi_code = SI_TIMER;
1359 		ksi.ksi_value = pt->pt_ev.sigev_value;
1360 		pt->pt_poverruns = pt->pt_overruns;
1361 		pt->pt_overruns = 0;
1362 		mutex_spin_exit(&timer_lock);
1363 
1364 		mutex_enter(proc_lock);
1365 		kpsignal(p, &ksi, NULL);
1366 		mutex_exit(proc_lock);
1367 
1368 		mutex_spin_enter(&timer_lock);
1369 	}
1370 	mutex_spin_exit(&timer_lock);
1371 }
1372 
1373 /*
1374  * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
1375  * for usage and rationale.
1376  */
1377 int
1378 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1379 {
1380 	struct timeval tv, delta;
1381 	int rv = 0;
1382 
1383 	getmicrouptime(&tv);
1384 	timersub(&tv, lasttime, &delta);
1385 
1386 	/*
1387 	 * check for 0,0 is so that the message will be seen at least once,
1388 	 * even if interval is huge.
1389 	 */
1390 	if (timercmp(&delta, mininterval, >=) ||
1391 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1392 		*lasttime = tv;
1393 		rv = 1;
1394 	}
1395 
1396 	return (rv);
1397 }
1398 
1399 /*
1400  * ppsratecheck(): packets (or events) per second limitation.
1401  */
1402 int
1403 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1404 {
1405 	struct timeval tv, delta;
1406 	int rv;
1407 
1408 	getmicrouptime(&tv);
1409 	timersub(&tv, lasttime, &delta);
1410 
1411 	/*
1412 	 * check for 0,0 is so that the message will be seen at least once.
1413 	 * if more than one second have passed since the last update of
1414 	 * lasttime, reset the counter.
1415 	 *
1416 	 * we do increment *curpps even in *curpps < maxpps case, as some may
1417 	 * try to use *curpps for stat purposes as well.
1418 	 */
1419 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
1420 	    delta.tv_sec >= 1) {
1421 		*lasttime = tv;
1422 		*curpps = 0;
1423 	}
1424 	if (maxpps < 0)
1425 		rv = 1;
1426 	else if (*curpps < maxpps)
1427 		rv = 1;
1428 	else
1429 		rv = 0;
1430 
1431 #if 1 /*DIAGNOSTIC?*/
1432 	/* be careful about wrap-around */
1433 	if (*curpps + 1 > *curpps)
1434 		*curpps = *curpps + 1;
1435 #else
1436 	/*
1437 	 * assume that there's not too many calls to this function.
1438 	 * not sure if the assumption holds, as it depends on *caller's*
1439 	 * behavior, not the behavior of this function.
1440 	 * IMHO it is wrong to make assumption on the caller's behavior,
1441 	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
1442 	 */
1443 	*curpps = *curpps + 1;
1444 #endif
1445 
1446 	return (rv);
1447 }
1448