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