kern_time.c revision 1.103
1/*	$NetBSD: kern_time.c,v 1.103 2006/07/14 22:45:20 kardel Exp $	*/
2
3/*-
4 * Copyright (c) 2000, 2004, 2005 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 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the NetBSD
21 *	Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 *    contributors may be used to endorse or promote products derived
24 *    from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39/*
40 * Copyright (c) 1982, 1986, 1989, 1993
41 *	The Regents of the University of California.  All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 *    notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 *    notice, this list of conditions and the following disclaimer in the
50 *    documentation and/or other materials provided with the distribution.
51 * 3. Neither the name of the University nor the names of its contributors
52 *    may be used to endorse or promote products derived from this software
53 *    without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 * SUCH DAMAGE.
66 *
67 *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
68 */
69
70#include <sys/cdefs.h>
71__KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.103 2006/07/14 22:45:20 kardel Exp $");
72
73#include "fs_nfs.h"
74#include "opt_nfs.h"
75#include "opt_nfsserver.h"
76
77#include <sys/param.h>
78#include <sys/resourcevar.h>
79#include <sys/kernel.h>
80#include <sys/systm.h>
81#include <sys/proc.h>
82#include <sys/sa.h>
83#include <sys/savar.h>
84#include <sys/vnode.h>
85#include <sys/signalvar.h>
86#include <sys/syslog.h>
87#ifdef __HAVE_TIMECOUNTER
88#include <sys/timetc.h>
89#else /* !__HAVE_TIMECOUNTER */
90#include <sys/timevar.h>
91#endif /* !__HAVE_TIMECOUNTER */
92#include <sys/kauth.h>
93
94#include <sys/mount.h>
95#include <sys/syscallargs.h>
96
97#include <uvm/uvm_extern.h>
98
99#if defined(NFS) || defined(NFSSERVER)
100#include <nfs/rpcv2.h>
101#include <nfs/nfsproto.h>
102#include <nfs/nfs.h>
103#include <nfs/nfs_var.h>
104#endif
105
106#include <machine/cpu.h>
107
108POOL_INIT(ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
109    &pool_allocator_nointr);
110POOL_INIT(ptimers_pool, sizeof(struct ptimers), 0, 0, 0, "ptimerspl",
111    &pool_allocator_nointr);
112
113static void timerupcall(struct lwp *, void *);
114#ifdef __HAVE_TIMECOUNTER
115static int itimespecfix(struct timespec *);		/* XXX move itimerfix to timespecs */
116#endif /* __HAVE_TIMECOUNTER */
117
118/* Time of day and interval timer support.
119 *
120 * These routines provide the kernel entry points to get and set
121 * the time-of-day and per-process interval timers.  Subroutines
122 * here provide support for adding and subtracting timeval structures
123 * and decrementing interval timers, optionally reloading the interval
124 * timers when they expire.
125 */
126
127/* This function is used by clock_settime and settimeofday */
128int
129settime(struct proc *p, struct timespec *ts)
130{
131	struct timeval delta, tv;
132#ifdef __HAVE_TIMECOUNTER
133	struct timeval now;
134	struct timespec ts1;
135#endif /* !__HAVE_TIMECOUNTER */
136	struct cpu_info *ci;
137	int s;
138
139	/*
140	 * Don't allow the time to be set forward so far it will wrap
141	 * and become negative, thus allowing an attacker to bypass
142	 * the next check below.  The cutoff is 1 year before rollover
143	 * occurs, so even if the attacker uses adjtime(2) to move
144	 * the time past the cutoff, it will take a very long time
145	 * to get to the wrap point.
146	 *
147	 * XXX: we check against INT_MAX since on 64-bit
148	 *	platforms, sizeof(int) != sizeof(long) and
149	 *	time_t is 32 bits even when atv.tv_sec is 64 bits.
150	 */
151	if (ts->tv_sec > INT_MAX - 365*24*60*60) {
152		struct proc *pp = p->p_pptr;
153		log(LOG_WARNING, "pid %d (%s) "
154		    "invoked by uid %d ppid %d (%s) "
155		    "tried to set clock forward to %ld\n",
156		    p->p_pid, p->p_comm, kauth_cred_geteuid(pp->p_cred),
157		    pp->p_pid, pp->p_comm, (long)ts->tv_sec);
158		return (EPERM);
159	}
160	TIMESPEC_TO_TIMEVAL(&tv, ts);
161
162	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
163	s = splclock();
164#ifdef __HAVE_TIMECOUNTER
165	microtime(&now);
166	timersub(&tv, &now, &delta);
167#else /* !__HAVE_TIMECOUNTER */
168	timersub(&tv, &time, &delta);
169#endif /* !__HAVE_TIMECOUNTER */
170	if ((delta.tv_sec < 0 || delta.tv_usec < 0) && securelevel > 1) {
171		splx(s);
172		return (EPERM);
173	}
174#ifdef notyet
175	if ((delta.tv_sec < 86400) && securelevel > 0) {
176		splx(s);
177		return (EPERM);
178	}
179#endif
180
181#ifdef __HAVE_TIMECOUNTER
182	TIMEVAL_TO_TIMESPEC(&tv, &ts1);
183	tc_setclock(&ts1);
184#else /* !__HAVE_TIMECOUNTER */
185	time = tv;
186#endif /* !__HAVE_TIMECOUNTER */
187
188	(void) spllowersoftclock();
189
190	timeradd(&boottime, &delta, &boottime);
191
192	/*
193	 * XXXSMP
194	 * This is wrong.  We should traverse a list of all
195	 * CPUs and add the delta to the runtime of those
196	 * CPUs which have a process on them.
197	 */
198	ci = curcpu();
199	timeradd(&ci->ci_schedstate.spc_runtime, &delta,
200	    &ci->ci_schedstate.spc_runtime);
201#if (defined(NFS) && !defined (NFS_V2_ONLY)) || defined(NFSSERVER)
202	nqnfs_lease_updatetime(delta.tv_sec);
203#endif
204	splx(s);
205	resettodr();
206	return (0);
207}
208
209/* ARGSUSED */
210int
211sys_clock_gettime(struct lwp *l, void *v, register_t *retval)
212{
213	struct sys_clock_gettime_args /* {
214		syscallarg(clockid_t) clock_id;
215		syscallarg(struct timespec *) tp;
216	} */ *uap = v;
217	clockid_t clock_id;
218	struct timespec ats;
219
220	clock_id = SCARG(uap, clock_id);
221	switch (clock_id) {
222	case CLOCK_REALTIME:
223		nanotime(&ats);
224		break;
225	case CLOCK_MONOTONIC:
226#ifdef __HAVE_TIMECOUNTER
227		nanouptime(&ats);
228#else /* !__HAVE_TIMECOUNTER */
229		{
230		int s;
231
232		/* XXX "hz" granularity */
233		s = splclock();
234		TIMEVAL_TO_TIMESPEC(&mono_time,&ats);
235		splx(s);
236		}
237#endif /* !__HAVE_TIMECOUNTER */
238		break;
239	default:
240		return (EINVAL);
241	}
242
243	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
244}
245
246/* ARGSUSED */
247int
248sys_clock_settime(struct lwp *l, void *v, register_t *retval)
249{
250	struct sys_clock_settime_args /* {
251		syscallarg(clockid_t) clock_id;
252		syscallarg(const struct timespec *) tp;
253	} */ *uap = v;
254	struct proc *p = l->l_proc;
255	int error;
256
257	if ((error = kauth_authorize_generic(p->p_cred, KAUTH_GENERIC_ISSUSER,
258				       &p->p_acflag)) != 0)
259		return (error);
260
261	return (clock_settime1(p, SCARG(uap, clock_id), SCARG(uap, tp)));
262}
263
264
265int
266clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp)
267{
268	struct timespec ats;
269	int error;
270
271	if ((error = copyin(tp, &ats, sizeof(ats))) != 0)
272		return (error);
273
274	switch (clock_id) {
275	case CLOCK_REALTIME:
276		if ((error = settime(p, &ats)) != 0)
277			return (error);
278		break;
279	case CLOCK_MONOTONIC:
280		return (EINVAL);	/* read-only clock */
281	default:
282		return (EINVAL);
283	}
284
285	return 0;
286}
287
288int
289sys_clock_getres(struct lwp *l, void *v, register_t *retval)
290{
291	struct sys_clock_getres_args /* {
292		syscallarg(clockid_t) clock_id;
293		syscallarg(struct timespec *) tp;
294	} */ *uap = v;
295	clockid_t clock_id;
296	struct timespec ts;
297	int error = 0;
298
299	clock_id = SCARG(uap, clock_id);
300	switch (clock_id) {
301	case CLOCK_REALTIME:
302	case CLOCK_MONOTONIC:
303		ts.tv_sec = 0;
304#ifdef __HAVE_TIMECOUNTER
305		if (tc_getfrequency() > 1000000000)
306			ts.tv_nsec = 1;
307		else
308			ts.tv_nsec = 1000000000 / tc_getfrequency();
309#else /* !__HAVE_TIMECOUNTER */
310		ts.tv_nsec = 1000000000 / hz;
311#endif /* !__HAVE_TIMECOUNTER */
312		break;
313	default:
314		return (EINVAL);
315	}
316
317	if (SCARG(uap, tp))
318		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
319
320	return error;
321}
322
323/* ARGSUSED */
324int
325sys_nanosleep(struct lwp *l, void *v, register_t *retval)
326{
327#ifdef __HAVE_TIMECOUNTER
328	static int nanowait;
329	struct sys_nanosleep_args/* {
330		syscallarg(struct timespec *) rqtp;
331		syscallarg(struct timespec *) rmtp;
332	} */ *uap = v;
333	struct timespec rmt, rqt;
334	int error, timo;
335
336	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
337	if (error)
338		return (error);
339
340	if (itimespecfix(&rqt))
341		return (EINVAL);
342
343	timo = tstohz(&rqt);
344	/*
345	 * Avoid inadvertantly sleeping forever
346	 */
347	if (timo == 0)
348		timo = 1;
349
350	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
351	if (error == ERESTART)
352		error = EINTR;
353	if (error == EWOULDBLOCK)
354		error = 0;
355
356	if (SCARG(uap, rmtp)) {
357		int error1;
358
359		getnanotime(&rmt);
360
361		timespecsub(&rqt, &rmt, &rmt);
362		if (rmt.tv_sec < 0)
363			timespecclear(&rmt);
364
365		error1 = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
366			sizeof(rmt));
367		if (error1)
368			return (error1);
369	}
370
371	return error;
372#else /* !__HAVE_TIMECOUNTER */
373	static int nanowait;
374	struct sys_nanosleep_args/* {
375		syscallarg(struct timespec *) rqtp;
376		syscallarg(struct timespec *) rmtp;
377	} */ *uap = v;
378	struct timespec rqt;
379	struct timespec rmt;
380	struct timeval atv, utv;
381	int error, s, timo;
382
383	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
384	if (error)
385		return (error);
386
387	TIMESPEC_TO_TIMEVAL(&atv,&rqt);
388	if (itimerfix(&atv))
389		return (EINVAL);
390
391	s = splclock();
392	timeradd(&atv,&time,&atv);
393	timo = hzto(&atv);
394	/*
395	 * Avoid inadvertantly sleeping forever
396	 */
397	if (timo == 0)
398		timo = 1;
399	splx(s);
400
401	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
402	if (error == ERESTART)
403		error = EINTR;
404	if (error == EWOULDBLOCK)
405		error = 0;
406
407	if (SCARG(uap, rmtp)) {
408		int error1;
409
410		s = splclock();
411		utv = time;
412		splx(s);
413
414		timersub(&atv, &utv, &utv);
415		if (utv.tv_sec < 0)
416			timerclear(&utv);
417
418		TIMEVAL_TO_TIMESPEC(&utv,&rmt);
419		error1 = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
420			sizeof(rmt));
421		if (error1)
422			return (error1);
423	}
424
425	return error;
426#endif /* !__HAVE_TIMECOUNTER */
427}
428
429/* ARGSUSED */
430int
431sys_gettimeofday(struct lwp *l, void *v, register_t *retval)
432{
433	struct sys_gettimeofday_args /* {
434		syscallarg(struct timeval *) tp;
435		syscallarg(void *) tzp;		really "struct timezone *"
436	} */ *uap = v;
437	struct timeval atv;
438	int error = 0;
439	struct timezone tzfake;
440
441	if (SCARG(uap, tp)) {
442		microtime(&atv);
443		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
444		if (error)
445			return (error);
446	}
447	if (SCARG(uap, tzp)) {
448		/*
449		 * NetBSD has no kernel notion of time zone, so we just
450		 * fake up a timezone struct and return it if demanded.
451		 */
452		tzfake.tz_minuteswest = 0;
453		tzfake.tz_dsttime = 0;
454		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
455	}
456	return (error);
457}
458
459/* ARGSUSED */
460int
461sys_settimeofday(struct lwp *l, void *v, register_t *retval)
462{
463	struct sys_settimeofday_args /* {
464		syscallarg(const struct timeval *) tv;
465		syscallarg(const void *) tzp;	really "const struct timezone *"
466	} */ *uap = v;
467	struct proc *p = l->l_proc;
468	int error;
469
470	if ((error = kauth_authorize_generic(p->p_cred, KAUTH_GENERIC_ISSUSER,
471				       &p->p_acflag)) != 0)
472		return (error);
473
474	return settimeofday1(SCARG(uap, tv), SCARG(uap, tzp), p);
475}
476
477int
478settimeofday1(const struct timeval *utv, const struct timezone *utzp,
479    struct proc *p)
480{
481	struct timeval atv;
482	struct timespec ts;
483	int error;
484
485	/* Verify all parameters before changing time. */
486	/*
487	 * NetBSD has no kernel notion of time zone, and only an
488	 * obsolete program would try to set it, so we log a warning.
489	 */
490	if (utzp)
491		log(LOG_WARNING, "pid %d attempted to set the "
492		    "(obsolete) kernel time zone\n", p->p_pid);
493
494	if (utv == NULL)
495		return 0;
496
497	if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
498		return error;
499	TIMEVAL_TO_TIMESPEC(&atv, &ts);
500	return settime(p, &ts);
501}
502
503#ifndef __HAVE_TIMECOUNTER
504int	tickdelta;			/* current clock skew, us. per tick */
505long	timedelta;			/* unapplied time correction, us. */
506long	bigadj = 1000000;		/* use 10x skew above bigadj us. */
507#endif
508
509int	time_adjusted;			/* set if an adjustment is made */
510
511/* ARGSUSED */
512int
513sys_adjtime(struct lwp *l, void *v, register_t *retval)
514{
515	struct sys_adjtime_args /* {
516		syscallarg(const struct timeval *) delta;
517		syscallarg(struct timeval *) olddelta;
518	} */ *uap = v;
519	struct proc *p = l->l_proc;
520	int error;
521
522	if ((error = kauth_authorize_generic(p->p_cred, KAUTH_GENERIC_ISSUSER,
523				       &p->p_acflag)) != 0)
524		return (error);
525
526	return adjtime1(SCARG(uap, delta), SCARG(uap, olddelta), p);
527}
528
529int
530adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
531{
532	struct timeval atv;
533	int error = 0;
534
535#ifdef __HAVE_TIMECOUNTER
536	extern int64_t time_adjtime;  /* in kern_ntptime.c */
537#else /* !__HAVE_TIMECOUNTER */
538	long ndelta, ntickdelta, odelta;
539	int s;
540#endif /* !__HAVE_TIMECOUNTER */
541
542#ifdef __HAVE_TIMECOUNTER
543	if (olddelta) {
544		atv.tv_sec = time_adjtime / 1000000;
545		atv.tv_usec = time_adjtime % 1000000;
546		if (atv.tv_usec < 0) {
547			atv.tv_usec += 1000000;
548			atv.tv_sec--;
549		}
550		error = copyout(&atv, olddelta, sizeof(struct timeval));
551		if (error)
552			return (error);
553	}
554
555	if (delta) {
556		error = copyin(delta, &atv, sizeof(struct timeval));
557		if (error)
558			return (error);
559
560		time_adjtime = (int64_t)atv.tv_sec * 1000000 +
561			atv.tv_usec;
562
563		if (time_adjtime)
564			/* We need to save the system time during shutdown */
565			time_adjusted |= 1;
566	}
567#else /* !__HAVE_TIMECOUNTER */
568	error = copyin(delta, &atv, sizeof(struct timeval));
569	if (error)
570		return (error);
571
572	/*
573	 * Compute the total correction and the rate at which to apply it.
574	 * Round the adjustment down to a whole multiple of the per-tick
575	 * delta, so that after some number of incremental changes in
576	 * hardclock(), tickdelta will become zero, lest the correction
577	 * overshoot and start taking us away from the desired final time.
578	 */
579	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
580	if (ndelta > bigadj || ndelta < -bigadj)
581		ntickdelta = 10 * tickadj;
582	else
583		ntickdelta = tickadj;
584	if (ndelta % ntickdelta)
585		ndelta = ndelta / ntickdelta * ntickdelta;
586
587	/*
588	 * To make hardclock()'s job easier, make the per-tick delta negative
589	 * if we want time to run slower; then hardclock can simply compute
590	 * tick + tickdelta, and subtract tickdelta from timedelta.
591	 */
592	if (ndelta < 0)
593		ntickdelta = -ntickdelta;
594	if (ndelta != 0)
595		/* We need to save the system clock time during shutdown */
596		time_adjusted |= 1;
597	s = splclock();
598	odelta = timedelta;
599	timedelta = ndelta;
600	tickdelta = ntickdelta;
601	splx(s);
602
603	if (olddelta) {
604		atv.tv_sec = odelta / 1000000;
605		atv.tv_usec = odelta % 1000000;
606		error = copyout(&atv, olddelta, sizeof(struct timeval));
607	}
608#endif /* __HAVE_TIMECOUNTER */
609
610	return error;
611}
612
613/*
614 * Interval timer support. Both the BSD getitimer() family and the POSIX
615 * timer_*() family of routines are supported.
616 *
617 * All timers are kept in an array pointed to by p_timers, which is
618 * allocated on demand - many processes don't use timers at all. The
619 * first three elements in this array are reserved for the BSD timers:
620 * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, and element
621 * 2 is ITIMER_PROF. The rest may be allocated by the timer_create()
622 * syscall.
623 *
624 * Realtime timers are kept in the ptimer structure as an absolute
625 * time; virtual time timers are kept as a linked list of deltas.
626 * Virtual time timers are processed in the hardclock() routine of
627 * kern_clock.c.  The real time timer is processed by a callout
628 * routine, called from the softclock() routine.  Since a callout may
629 * be delayed in real time due to interrupt processing in the system,
630 * it is possible for the real time timeout routine (realtimeexpire,
631 * given below), to be delayed in real time past when it is supposed
632 * to occur.  It does not suffice, therefore, to reload the real timer
633 * .it_value from the real time timers .it_interval.  Rather, we
634 * compute the next time in absolute time the timer should go off.  */
635
636/* Allocate a POSIX realtime timer. */
637int
638sys_timer_create(struct lwp *l, void *v, register_t *retval)
639{
640	struct sys_timer_create_args /* {
641		syscallarg(clockid_t) clock_id;
642		syscallarg(struct sigevent *) evp;
643		syscallarg(timer_t *) timerid;
644	} */ *uap = v;
645
646	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
647	    SCARG(uap, evp), copyin, l->l_proc);
648}
649
650int
651timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
652    copyin_t fetch_event, struct proc *p)
653{
654	int error;
655	timer_t timerid;
656	struct ptimer *pt;
657
658	if (id < CLOCK_REALTIME ||
659	    id > CLOCK_PROF)
660		return (EINVAL);
661
662	if (p->p_timers == NULL)
663		timers_alloc(p);
664
665	/* Find a free timer slot, skipping those reserved for setitimer(). */
666	for (timerid = 3; timerid < TIMER_MAX; timerid++)
667		if (p->p_timers->pts_timers[timerid] == NULL)
668			break;
669
670	if (timerid == TIMER_MAX)
671		return EAGAIN;
672
673	pt = pool_get(&ptimer_pool, PR_WAITOK);
674	if (evp) {
675		if (((error =
676		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
677		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
678			(pt->pt_ev.sigev_notify > SIGEV_SA))) {
679			pool_put(&ptimer_pool, pt);
680			return (error ? error : EINVAL);
681		}
682	} else {
683		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
684		switch (id) {
685		case CLOCK_REALTIME:
686			pt->pt_ev.sigev_signo = SIGALRM;
687			break;
688		case CLOCK_VIRTUAL:
689			pt->pt_ev.sigev_signo = SIGVTALRM;
690			break;
691		case CLOCK_PROF:
692			pt->pt_ev.sigev_signo = SIGPROF;
693			break;
694		}
695		pt->pt_ev.sigev_value.sival_int = timerid;
696	}
697	pt->pt_info.ksi_signo = pt->pt_ev.sigev_signo;
698	pt->pt_info.ksi_errno = 0;
699	pt->pt_info.ksi_code = 0;
700	pt->pt_info.ksi_pid = p->p_pid;
701	pt->pt_info.ksi_uid = kauth_cred_getuid(p->p_cred);
702	pt->pt_info.ksi_sigval = pt->pt_ev.sigev_value;
703
704	pt->pt_type = id;
705	pt->pt_proc = p;
706	pt->pt_overruns = 0;
707	pt->pt_poverruns = 0;
708	pt->pt_entry = timerid;
709	timerclear(&pt->pt_time.it_value);
710	if (id == CLOCK_REALTIME)
711		callout_init(&pt->pt_ch);
712	else
713		pt->pt_active = 0;
714
715	p->p_timers->pts_timers[timerid] = pt;
716
717	return copyout(&timerid, tid, sizeof(timerid));
718}
719
720/* Delete a POSIX realtime timer */
721int
722sys_timer_delete(struct lwp *l, void *v, register_t *retval)
723{
724	struct sys_timer_delete_args /*  {
725		syscallarg(timer_t) timerid;
726	} */ *uap = v;
727	struct proc *p = l->l_proc;
728	timer_t timerid;
729	struct ptimer *pt, *ptn;
730	int s;
731
732	timerid = SCARG(uap, timerid);
733
734	if ((p->p_timers == NULL) ||
735	    (timerid < 2) || (timerid >= TIMER_MAX) ||
736	    ((pt = p->p_timers->pts_timers[timerid]) == NULL))
737		return (EINVAL);
738
739	if (pt->pt_type == CLOCK_REALTIME)
740		callout_stop(&pt->pt_ch);
741	else if (pt->pt_active) {
742		s = splclock();
743		ptn = LIST_NEXT(pt, pt_list);
744		LIST_REMOVE(pt, pt_list);
745		for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
746			timeradd(&pt->pt_time.it_value, &ptn->pt_time.it_value,
747			    &ptn->pt_time.it_value);
748		splx(s);
749	}
750
751	p->p_timers->pts_timers[timerid] = NULL;
752	pool_put(&ptimer_pool, pt);
753
754	return (0);
755}
756
757/*
758 * Set up the given timer. The value in pt->pt_time.it_value is taken
759 * to be an absolute time for CLOCK_REALTIME timers and a relative
760 * time for virtual timers.
761 * Must be called at splclock().
762 */
763void
764timer_settime(struct ptimer *pt)
765{
766	struct ptimer *ptn, *pptn;
767	struct ptlist *ptl;
768
769	if (pt->pt_type == CLOCK_REALTIME) {
770		callout_stop(&pt->pt_ch);
771		if (timerisset(&pt->pt_time.it_value)) {
772			/*
773			 * Don't need to check hzto() return value, here.
774			 * callout_reset() does it for us.
775			 */
776			callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
777			    realtimerexpire, pt);
778		}
779	} else {
780		if (pt->pt_active) {
781			ptn = LIST_NEXT(pt, pt_list);
782			LIST_REMOVE(pt, pt_list);
783			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
784				timeradd(&pt->pt_time.it_value,
785				    &ptn->pt_time.it_value,
786				    &ptn->pt_time.it_value);
787		}
788		if (timerisset(&pt->pt_time.it_value)) {
789			if (pt->pt_type == CLOCK_VIRTUAL)
790				ptl = &pt->pt_proc->p_timers->pts_virtual;
791			else
792				ptl = &pt->pt_proc->p_timers->pts_prof;
793
794			for (ptn = LIST_FIRST(ptl), pptn = NULL;
795			     ptn && timercmp(&pt->pt_time.it_value,
796				 &ptn->pt_time.it_value, >);
797			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
798				timersub(&pt->pt_time.it_value,
799				    &ptn->pt_time.it_value,
800				    &pt->pt_time.it_value);
801
802			if (pptn)
803				LIST_INSERT_AFTER(pptn, pt, pt_list);
804			else
805				LIST_INSERT_HEAD(ptl, pt, pt_list);
806
807			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
808				timersub(&ptn->pt_time.it_value,
809				    &pt->pt_time.it_value,
810				    &ptn->pt_time.it_value);
811
812			pt->pt_active = 1;
813		} else
814			pt->pt_active = 0;
815	}
816}
817
818void
819timer_gettime(struct ptimer *pt, struct itimerval *aitv)
820{
821#ifdef __HAVE_TIMECOUNTER
822	struct timeval now;
823#endif
824	struct ptimer *ptn;
825
826	*aitv = pt->pt_time;
827	if (pt->pt_type == CLOCK_REALTIME) {
828		/*
829		 * Convert from absolute to relative time in .it_value
830		 * part of real time timer.  If time for real time
831		 * timer has passed return 0, else return difference
832		 * between current time and time for the timer to go
833		 * off.
834		 */
835		if (timerisset(&aitv->it_value)) {
836#ifdef __HAVE_TIMECOUNTER
837			getmicrotime(&now);
838			if (timercmp(&aitv->it_value, &now, <))
839				timerclear(&aitv->it_value);
840			else
841				timersub(&aitv->it_value, &now,
842				    &aitv->it_value);
843#else /* !__HAVE_TIMECOUNTER */
844			if (timercmp(&aitv->it_value, &time, <))
845				timerclear(&aitv->it_value);
846			else
847				timersub(&aitv->it_value, &time,
848				    &aitv->it_value);
849#endif /* !__HAVE_TIMECOUNTER */
850		}
851	} else if (pt->pt_active) {
852		if (pt->pt_type == CLOCK_VIRTUAL)
853			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
854		else
855			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
856		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
857			timeradd(&aitv->it_value,
858			    &ptn->pt_time.it_value, &aitv->it_value);
859		KASSERT(ptn != NULL); /* pt should be findable on the list */
860	} else
861		timerclear(&aitv->it_value);
862}
863
864
865
866/* Set and arm a POSIX realtime timer */
867int
868sys_timer_settime(struct lwp *l, void *v, register_t *retval)
869{
870	struct sys_timer_settime_args /* {
871		syscallarg(timer_t) timerid;
872		syscallarg(int) flags;
873		syscallarg(const struct itimerspec *) value;
874		syscallarg(struct itimerspec *) ovalue;
875	} */ *uap = v;
876	int error;
877	struct itimerspec value, ovalue, *ovp = NULL;
878
879	if ((error = copyin(SCARG(uap, value), &value,
880	    sizeof(struct itimerspec))) != 0)
881		return (error);
882
883	if (SCARG(uap, ovalue))
884		ovp = &ovalue;
885
886	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
887	    SCARG(uap, flags), l->l_proc)) != 0)
888		return error;
889
890	if (ovp)
891		return copyout(&ovalue, SCARG(uap, ovalue),
892		    sizeof(struct itimerspec));
893	return 0;
894}
895
896int
897dotimer_settime(int timerid, struct itimerspec *value,
898    struct itimerspec *ovalue, int flags, struct proc *p)
899{
900#ifdef __HAVE_TIMECOUNTER
901	struct timeval now;
902#endif
903	struct itimerval val, oval;
904	struct ptimer *pt;
905	int s;
906
907	if ((p->p_timers == NULL) ||
908	    (timerid < 2) || (timerid >= TIMER_MAX) ||
909	    ((pt = p->p_timers->pts_timers[timerid]) == NULL))
910		return (EINVAL);
911
912	TIMESPEC_TO_TIMEVAL(&val.it_value, &value->it_value);
913	TIMESPEC_TO_TIMEVAL(&val.it_interval, &value->it_interval);
914	if (itimerfix(&val.it_value) || itimerfix(&val.it_interval))
915		return (EINVAL);
916
917	oval = pt->pt_time;
918	pt->pt_time = val;
919
920	s = splclock();
921	/*
922	 * If we've been passed a relative time for a realtime timer,
923	 * convert it to absolute; if an absolute time for a virtual
924	 * timer, convert it to relative and make sure we don't set it
925	 * to zero, which would cancel the timer, or let it go
926	 * negative, which would confuse the comparison tests.
927	 */
928	if (timerisset(&pt->pt_time.it_value)) {
929		if (pt->pt_type == CLOCK_REALTIME) {
930#ifdef __HAVE_TIMECOUNTER
931			if ((flags & TIMER_ABSTIME) == 0) {
932				getmicrotime(&now);
933				timeradd(&pt->pt_time.it_value, &now,
934				    &pt->pt_time.it_value);
935			}
936#else /* !__HAVE_TIMECOUNTER */
937			if ((flags & TIMER_ABSTIME) == 0)
938				timeradd(&pt->pt_time.it_value, &time,
939				    &pt->pt_time.it_value);
940#endif /* !__HAVE_TIMECOUNTER */
941		} else {
942			if ((flags & TIMER_ABSTIME) != 0) {
943#ifdef __HAVE_TIMECOUNTER
944				getmicrotime(&now);
945				timersub(&pt->pt_time.it_value, &now,
946				    &pt->pt_time.it_value);
947#else /* !__HAVE_TIMECOUNTER */
948				timersub(&pt->pt_time.it_value, &time,
949				    &pt->pt_time.it_value);
950#endif /* !__HAVE_TIMECOUNTER */
951				if (!timerisset(&pt->pt_time.it_value) ||
952				    pt->pt_time.it_value.tv_sec < 0) {
953					pt->pt_time.it_value.tv_sec = 0;
954					pt->pt_time.it_value.tv_usec = 1;
955				}
956			}
957		}
958	}
959
960	timer_settime(pt);
961	splx(s);
962
963	if (ovalue) {
964		TIMEVAL_TO_TIMESPEC(&oval.it_value, &ovalue->it_value);
965		TIMEVAL_TO_TIMESPEC(&oval.it_interval, &ovalue->it_interval);
966	}
967
968	return (0);
969}
970
971/* Return the time remaining until a POSIX timer fires. */
972int
973sys_timer_gettime(struct lwp *l, void *v, register_t *retval)
974{
975	struct sys_timer_gettime_args /* {
976		syscallarg(timer_t) timerid;
977		syscallarg(struct itimerspec *) value;
978	} */ *uap = v;
979	struct itimerspec its;
980	int error;
981
982	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
983	    &its)) != 0)
984		return error;
985
986	return copyout(&its, SCARG(uap, value), sizeof(its));
987}
988
989int
990dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
991{
992	int s;
993	struct ptimer *pt;
994	struct itimerval aitv;
995
996	if ((p->p_timers == NULL) ||
997	    (timerid < 2) || (timerid >= TIMER_MAX) ||
998	    ((pt = p->p_timers->pts_timers[timerid]) == NULL))
999		return (EINVAL);
1000
1001	s = splclock();
1002	timer_gettime(pt, &aitv);
1003	splx(s);
1004
1005	TIMEVAL_TO_TIMESPEC(&aitv.it_interval, &its->it_interval);
1006	TIMEVAL_TO_TIMESPEC(&aitv.it_value, &its->it_value);
1007
1008	return 0;
1009}
1010
1011/*
1012 * Return the count of the number of times a periodic timer expired
1013 * while a notification was already pending. The counter is reset when
1014 * a timer expires and a notification can be posted.
1015 */
1016int
1017sys_timer_getoverrun(struct lwp *l, void *v, register_t *retval)
1018{
1019	struct sys_timer_getoverrun_args /* {
1020		syscallarg(timer_t) timerid;
1021	} */ *uap = v;
1022	struct proc *p = l->l_proc;
1023	int timerid;
1024	struct ptimer *pt;
1025
1026	timerid = SCARG(uap, timerid);
1027
1028	if ((p->p_timers == NULL) ||
1029	    (timerid < 2) || (timerid >= TIMER_MAX) ||
1030	    ((pt = p->p_timers->pts_timers[timerid]) == NULL))
1031		return (EINVAL);
1032
1033	*retval = pt->pt_poverruns;
1034
1035	return (0);
1036}
1037
1038/* Glue function that triggers an upcall; called from userret(). */
1039static void
1040timerupcall(struct lwp *l, void *arg)
1041{
1042	struct ptimers *pt = (struct ptimers *)arg;
1043	unsigned int i, fired, done;
1044
1045	KDASSERT(l->l_proc->p_sa);
1046	/* Bail out if we do not own the virtual processor */
1047	if (l->l_savp->savp_lwp != l)
1048		return ;
1049
1050	KERNEL_PROC_LOCK(l);
1051
1052	fired = pt->pts_fired;
1053	done = 0;
1054	while ((i = ffs(fired)) != 0) {
1055		siginfo_t *si;
1056		int mask = 1 << --i;
1057		int f;
1058
1059		f = l->l_flag & L_SA;
1060		l->l_flag &= ~L_SA;
1061		si = siginfo_alloc(PR_WAITOK);
1062		si->_info = pt->pts_timers[i]->pt_info.ksi_info;
1063		if (sa_upcall(l, SA_UPCALL_SIGEV | SA_UPCALL_DEFER, NULL, l,
1064		    sizeof(*si), si, siginfo_free) != 0) {
1065			siginfo_free(si);
1066			/* XXX What do we do here?? */
1067		} else
1068			done |= mask;
1069		fired &= ~mask;
1070		l->l_flag |= f;
1071	}
1072	pt->pts_fired &= ~done;
1073	if (pt->pts_fired == 0)
1074		l->l_proc->p_userret = NULL;
1075
1076	KERNEL_PROC_UNLOCK(l);
1077}
1078
1079/*
1080 * Real interval timer expired:
1081 * send process whose timer expired an alarm signal.
1082 * If time is not set up to reload, then just return.
1083 * Else compute next time timer should go off which is > current time.
1084 * This is where delay in processing this timeout causes multiple
1085 * SIGALRM calls to be compressed into one.
1086 */
1087void
1088realtimerexpire(void *arg)
1089{
1090#ifdef __HAVE_TIMECOUNTER
1091	struct timeval now;
1092#endif
1093	struct ptimer *pt;
1094	int s;
1095
1096	pt = (struct ptimer *)arg;
1097
1098	itimerfire(pt);
1099
1100	if (!timerisset(&pt->pt_time.it_interval)) {
1101		timerclear(&pt->pt_time.it_value);
1102		return;
1103	}
1104#ifdef __HAVE_TIMECOUNTER
1105	for (;;) {
1106		s = splclock();	/* XXX need spl now? */
1107		timeradd(&pt->pt_time.it_value,
1108		    &pt->pt_time.it_interval, &pt->pt_time.it_value);
1109		getmicrotime(&now);
1110		if (timercmp(&pt->pt_time.it_value, &now, >)) {
1111			/*
1112			 * Don't need to check hzto() return value, here.
1113			 * callout_reset() does it for us.
1114			 */
1115			callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
1116			    realtimerexpire, pt);
1117			splx(s);
1118			return;
1119		}
1120		splx(s);
1121		pt->pt_overruns++;
1122	}
1123#else /* !__HAVE_TIMECOUNTER */
1124	for (;;) {
1125		s = splclock();
1126		timeradd(&pt->pt_time.it_value,
1127		    &pt->pt_time.it_interval, &pt->pt_time.it_value);
1128		if (timercmp(&pt->pt_time.it_value, &time, >)) {
1129			/*
1130			 * Don't need to check hzto() return value, here.
1131			 * callout_reset() does it for us.
1132			 */
1133			callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
1134			    realtimerexpire, pt);
1135			splx(s);
1136			return;
1137		}
1138		splx(s);
1139		pt->pt_overruns++;
1140	}
1141#endif /* !__HAVE_TIMECOUNTER */
1142}
1143
1144/* BSD routine to get the value of an interval timer. */
1145/* ARGSUSED */
1146int
1147sys_getitimer(struct lwp *l, void *v, register_t *retval)
1148{
1149	struct sys_getitimer_args /* {
1150		syscallarg(int) which;
1151		syscallarg(struct itimerval *) itv;
1152	} */ *uap = v;
1153	struct proc *p = l->l_proc;
1154	struct itimerval aitv;
1155	int error;
1156
1157	error = dogetitimer(p, SCARG(uap, which), &aitv);
1158	if (error)
1159		return error;
1160	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
1161}
1162
1163int
1164dogetitimer(struct proc *p, int which, struct itimerval *itvp)
1165{
1166	int s;
1167
1168	if ((u_int)which > ITIMER_PROF)
1169		return (EINVAL);
1170
1171	if ((p->p_timers == NULL) || (p->p_timers->pts_timers[which] == NULL)){
1172		timerclear(&itvp->it_value);
1173		timerclear(&itvp->it_interval);
1174	} else {
1175		s = splclock();
1176		timer_gettime(p->p_timers->pts_timers[which], itvp);
1177		splx(s);
1178	}
1179
1180	return 0;
1181}
1182
1183/* BSD routine to set/arm an interval timer. */
1184/* ARGSUSED */
1185int
1186sys_setitimer(struct lwp *l, void *v, register_t *retval)
1187{
1188	struct sys_setitimer_args /* {
1189		syscallarg(int) which;
1190		syscallarg(const struct itimerval *) itv;
1191		syscallarg(struct itimerval *) oitv;
1192	} */ *uap = v;
1193	struct proc *p = l->l_proc;
1194	int which = SCARG(uap, which);
1195	struct sys_getitimer_args getargs;
1196	const struct itimerval *itvp;
1197	struct itimerval aitv;
1198	int error;
1199
1200	if ((u_int)which > ITIMER_PROF)
1201		return (EINVAL);
1202	itvp = SCARG(uap, itv);
1203	if (itvp &&
1204	    (error = copyin(itvp, &aitv, sizeof(struct itimerval)) != 0))
1205		return (error);
1206	if (SCARG(uap, oitv) != NULL) {
1207		SCARG(&getargs, which) = which;
1208		SCARG(&getargs, itv) = SCARG(uap, oitv);
1209		if ((error = sys_getitimer(l, &getargs, retval)) != 0)
1210			return (error);
1211	}
1212	if (itvp == 0)
1213		return (0);
1214
1215	return dosetitimer(p, which, &aitv);
1216}
1217
1218int
1219dosetitimer(struct proc *p, int which, struct itimerval *itvp)
1220{
1221#ifdef __HAVE_TIMECOUNTER
1222	struct timeval now;
1223#endif
1224	struct ptimer *pt;
1225	int s;
1226
1227	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
1228		return (EINVAL);
1229
1230	/*
1231	 * Don't bother allocating data structures if the process just
1232	 * wants to clear the timer.
1233	 */
1234	if (!timerisset(&itvp->it_value) &&
1235	    ((p->p_timers == NULL) ||(p->p_timers->pts_timers[which] == NULL)))
1236		return (0);
1237
1238	if (p->p_timers == NULL)
1239		timers_alloc(p);
1240	if (p->p_timers->pts_timers[which] == NULL) {
1241		pt = pool_get(&ptimer_pool, PR_WAITOK);
1242		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
1243		pt->pt_ev.sigev_value.sival_int = which;
1244		pt->pt_overruns = 0;
1245		pt->pt_proc = p;
1246		pt->pt_type = which;
1247		pt->pt_entry = which;
1248		switch (which) {
1249		case ITIMER_REAL:
1250			callout_init(&pt->pt_ch);
1251			pt->pt_ev.sigev_signo = SIGALRM;
1252			break;
1253		case ITIMER_VIRTUAL:
1254			pt->pt_active = 0;
1255			pt->pt_ev.sigev_signo = SIGVTALRM;
1256			break;
1257		case ITIMER_PROF:
1258			pt->pt_active = 0;
1259			pt->pt_ev.sigev_signo = SIGPROF;
1260			break;
1261		}
1262	} else
1263		pt = p->p_timers->pts_timers[which];
1264
1265	pt->pt_time = *itvp;
1266	p->p_timers->pts_timers[which] = pt;
1267
1268	s = splclock();
1269	if ((which == ITIMER_REAL) && timerisset(&pt->pt_time.it_value)) {
1270		/* Convert to absolute time */
1271#ifdef __HAVE_TIMECOUNTER
1272		/* XXX need to wrap in splclock for timecounters case? */
1273		getmicrotime(&now);
1274		timeradd(&pt->pt_time.it_value, &now, &pt->pt_time.it_value);
1275#else /* !__HAVE_TIMECOUNTER */
1276		timeradd(&pt->pt_time.it_value, &time, &pt->pt_time.it_value);
1277#endif /* !__HAVE_TIMECOUNTER */
1278	}
1279	timer_settime(pt);
1280	splx(s);
1281
1282	return (0);
1283}
1284
1285/* Utility routines to manage the array of pointers to timers. */
1286void
1287timers_alloc(struct proc *p)
1288{
1289	int i;
1290	struct ptimers *pts;
1291
1292	pts = pool_get(&ptimers_pool, PR_WAITOK);
1293	LIST_INIT(&pts->pts_virtual);
1294	LIST_INIT(&pts->pts_prof);
1295	for (i = 0; i < TIMER_MAX; i++)
1296		pts->pts_timers[i] = NULL;
1297	pts->pts_fired = 0;
1298	p->p_timers = pts;
1299}
1300
1301/*
1302 * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
1303 * then clean up all timers and free all the data structures. If
1304 * "which" is set to TIMERS_POSIX, only clean up the timers allocated
1305 * by timer_create(), not the BSD setitimer() timers, and only free the
1306 * structure if none of those remain.
1307 */
1308void
1309timers_free(struct proc *p, int which)
1310{
1311	int i, s;
1312	struct ptimers *pts;
1313	struct ptimer *pt, *ptn;
1314	struct timeval tv;
1315
1316	if (p->p_timers) {
1317		pts = p->p_timers;
1318		if (which == TIMERS_ALL)
1319			i = 0;
1320		else {
1321			s = splclock();
1322			timerclear(&tv);
1323			for (ptn = LIST_FIRST(&p->p_timers->pts_virtual);
1324			     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
1325			     ptn = LIST_NEXT(ptn, pt_list))
1326				timeradd(&tv, &ptn->pt_time.it_value, &tv);
1327			LIST_FIRST(&p->p_timers->pts_virtual) = NULL;
1328			if (ptn) {
1329				timeradd(&tv, &ptn->pt_time.it_value,
1330				    &ptn->pt_time.it_value);
1331				LIST_INSERT_HEAD(&p->p_timers->pts_virtual,
1332				    ptn, pt_list);
1333			}
1334
1335			timerclear(&tv);
1336			for (ptn = LIST_FIRST(&p->p_timers->pts_prof);
1337			     ptn && ptn != pts->pts_timers[ITIMER_PROF];
1338			     ptn = LIST_NEXT(ptn, pt_list))
1339				timeradd(&tv, &ptn->pt_time.it_value, &tv);
1340			LIST_FIRST(&p->p_timers->pts_prof) = NULL;
1341			if (ptn) {
1342				timeradd(&tv, &ptn->pt_time.it_value,
1343				    &ptn->pt_time.it_value);
1344				LIST_INSERT_HEAD(&p->p_timers->pts_prof, ptn,
1345				    pt_list);
1346			}
1347			splx(s);
1348			i = 3;
1349		}
1350		for ( ; i < TIMER_MAX; i++)
1351			if ((pt = pts->pts_timers[i]) != NULL) {
1352				if (pt->pt_type == CLOCK_REALTIME)
1353					callout_stop(&pt->pt_ch);
1354				pts->pts_timers[i] = NULL;
1355				pool_put(&ptimer_pool, pt);
1356			}
1357		if ((pts->pts_timers[0] == NULL) &&
1358		    (pts->pts_timers[1] == NULL) &&
1359		    (pts->pts_timers[2] == NULL)) {
1360			p->p_timers = NULL;
1361			pool_put(&ptimers_pool, pts);
1362		}
1363	}
1364}
1365
1366/*
1367 * Check that a proposed value to load into the .it_value or
1368 * .it_interval part of an interval timer is acceptable, and
1369 * fix it to have at least minimal value (i.e. if it is less
1370 * than the resolution of the clock, round it up.)
1371 */
1372int
1373itimerfix(struct timeval *tv)
1374{
1375
1376	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
1377		return (EINVAL);
1378	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
1379		tv->tv_usec = tick;
1380	return (0);
1381}
1382
1383#ifdef __HAVE_TIMECOUNTER
1384int
1385itimespecfix(struct timespec *ts)
1386{
1387
1388	if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1389		return (EINVAL);
1390	if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1391		ts->tv_nsec = tick * 1000;
1392	return (0);
1393}
1394#endif /* __HAVE_TIMECOUNTER */
1395
1396/*
1397 * Decrement an interval timer by a specified number
1398 * of microseconds, which must be less than a second,
1399 * i.e. < 1000000.  If the timer expires, then reload
1400 * it.  In this case, carry over (usec - old value) to
1401 * reduce the value reloaded into the timer so that
1402 * the timer does not drift.  This routine assumes
1403 * that it is called in a context where the timers
1404 * on which it is operating cannot change in value.
1405 */
1406int
1407itimerdecr(struct ptimer *pt, int usec)
1408{
1409	struct itimerval *itp;
1410
1411	itp = &pt->pt_time;
1412	if (itp->it_value.tv_usec < usec) {
1413		if (itp->it_value.tv_sec == 0) {
1414			/* expired, and already in next interval */
1415			usec -= itp->it_value.tv_usec;
1416			goto expire;
1417		}
1418		itp->it_value.tv_usec += 1000000;
1419		itp->it_value.tv_sec--;
1420	}
1421	itp->it_value.tv_usec -= usec;
1422	usec = 0;
1423	if (timerisset(&itp->it_value))
1424		return (1);
1425	/* expired, exactly at end of interval */
1426expire:
1427	if (timerisset(&itp->it_interval)) {
1428		itp->it_value = itp->it_interval;
1429		itp->it_value.tv_usec -= usec;
1430		if (itp->it_value.tv_usec < 0) {
1431			itp->it_value.tv_usec += 1000000;
1432			itp->it_value.tv_sec--;
1433		}
1434		timer_settime(pt);
1435	} else
1436		itp->it_value.tv_usec = 0;		/* sec is already 0 */
1437	return (0);
1438}
1439
1440void
1441itimerfire(struct ptimer *pt)
1442{
1443	struct proc *p = pt->pt_proc;
1444	struct sadata_vp *vp;
1445	int s;
1446	unsigned int i;
1447
1448	if (pt->pt_ev.sigev_notify == SIGEV_SIGNAL) {
1449		/*
1450		 * No RT signal infrastructure exists at this time;
1451		 * just post the signal number and throw away the
1452		 * value.
1453		 */
1454		if (sigismember(&p->p_sigctx.ps_siglist, pt->pt_ev.sigev_signo))
1455			pt->pt_overruns++;
1456		else {
1457			ksiginfo_t ksi;
1458			(void)memset(&ksi, 0, sizeof(ksi));
1459			ksi.ksi_signo = pt->pt_ev.sigev_signo;
1460			ksi.ksi_code = SI_TIMER;
1461			ksi.ksi_sigval = pt->pt_ev.sigev_value;
1462			pt->pt_poverruns = pt->pt_overruns;
1463			pt->pt_overruns = 0;
1464			kpsignal(p, &ksi, NULL);
1465		}
1466	} else if (pt->pt_ev.sigev_notify == SIGEV_SA && (p->p_flag & P_SA)) {
1467		/* Cause the process to generate an upcall when it returns. */
1468
1469		if (p->p_userret == NULL) {
1470			/*
1471			 * XXX stop signals can be processed inside tsleep,
1472			 * which can be inside sa_yield's inner loop, which
1473			 * makes testing for sa_idle alone insuffucent to
1474			 * determine if we really should call setrunnable.
1475			 */
1476			pt->pt_poverruns = pt->pt_overruns;
1477			pt->pt_overruns = 0;
1478			i = 1 << pt->pt_entry;
1479			p->p_timers->pts_fired = i;
1480			p->p_userret = timerupcall;
1481			p->p_userret_arg = p->p_timers;
1482
1483			SCHED_LOCK(s);
1484			SLIST_FOREACH(vp, &p->p_sa->sa_vps, savp_next) {
1485				if (vp->savp_lwp->l_flag & L_SA_IDLE) {
1486					vp->savp_lwp->l_flag &= ~L_SA_IDLE;
1487					sched_wakeup(vp->savp_lwp);
1488					break;
1489				}
1490			}
1491			SCHED_UNLOCK(s);
1492		} else if (p->p_userret == timerupcall) {
1493			i = 1 << pt->pt_entry;
1494			if ((p->p_timers->pts_fired & i) == 0) {
1495				pt->pt_poverruns = pt->pt_overruns;
1496				pt->pt_overruns = 0;
1497				p->p_timers->pts_fired |= i;
1498			} else
1499				pt->pt_overruns++;
1500		} else {
1501			pt->pt_overruns++;
1502			if ((p->p_flag & P_WEXIT) == 0)
1503				printf("itimerfire(%d): overrun %d on timer %x (userret is %p)\n",
1504				    p->p_pid, pt->pt_overruns,
1505				    pt->pt_ev.sigev_value.sival_int,
1506				    p->p_userret);
1507		}
1508	}
1509
1510}
1511
1512/*
1513 * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
1514 * for usage and rationale.
1515 */
1516int
1517ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1518{
1519	struct timeval tv, delta;
1520	int rv = 0;
1521#ifndef __HAVE_TIMECOUNTER
1522	int s;
1523#endif
1524
1525#ifdef __HAVE_TIMECOUNTER
1526	getmicrouptime(&tv);
1527#else /* !__HAVE_TIMECOUNTER */
1528	s = splclock();
1529	tv = mono_time;
1530	splx(s);
1531#endif /* !__HAVE_TIMECOUNTER */
1532	timersub(&tv, lasttime, &delta);
1533
1534	/*
1535	 * check for 0,0 is so that the message will be seen at least once,
1536	 * even if interval is huge.
1537	 */
1538	if (timercmp(&delta, mininterval, >=) ||
1539	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1540		*lasttime = tv;
1541		rv = 1;
1542	}
1543
1544	return (rv);
1545}
1546
1547/*
1548 * ppsratecheck(): packets (or events) per second limitation.
1549 */
1550int
1551ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1552{
1553	struct timeval tv, delta;
1554	int rv;
1555#ifndef __HAVE_TIMECOUNTER
1556	int s;
1557#endif
1558
1559#ifdef __HAVE_TIMECOUNTER
1560	getmicrouptime(&tv);
1561#else /* !__HAVE_TIMECOUNTER */
1562	s = splclock();
1563	tv = mono_time;
1564	splx(s);
1565#endif /* !__HAVE_TIMECOUNTER */
1566	timersub(&tv, lasttime, &delta);
1567
1568	/*
1569	 * check for 0,0 is so that the message will be seen at least once.
1570	 * if more than one second have passed since the last update of
1571	 * lasttime, reset the counter.
1572	 *
1573	 * we do increment *curpps even in *curpps < maxpps case, as some may
1574	 * try to use *curpps for stat purposes as well.
1575	 */
1576	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
1577	    delta.tv_sec >= 1) {
1578		*lasttime = tv;
1579		*curpps = 0;
1580	}
1581	if (maxpps < 0)
1582		rv = 1;
1583	else if (*curpps < maxpps)
1584		rv = 1;
1585	else
1586		rv = 0;
1587
1588#if 1 /*DIAGNOSTIC?*/
1589	/* be careful about wrap-around */
1590	if (*curpps + 1 > *curpps)
1591		*curpps = *curpps + 1;
1592#else
1593	/*
1594	 * assume that there's not too many calls to this function.
1595	 * not sure if the assumption holds, as it depends on *caller's*
1596	 * behavior, not the behavior of this function.
1597	 * IMHO it is wrong to make assumption on the caller's behavior,
1598	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
1599	 */
1600	*curpps = *curpps + 1;
1601#endif
1602
1603	return (rv);
1604}
1605