Home | History | Annotate | Line # | Download | only in kern
kern_time.c revision 1.54.2.8
      1 /*	$NetBSD: kern_time.c,v 1.54.2.8 2002/02/02 00:04:33 nathanw 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. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by the University of
     54  *	California, Berkeley and its contributors.
     55  * 4. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  *
     71  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
     72  */
     73 
     74 #include <sys/cdefs.h>
     75 __KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.54.2.8 2002/02/02 00:04:33 nathanw Exp $");
     76 
     77 #include "fs_nfs.h"
     78 #include "opt_nfs.h"
     79 #include "opt_nfsserver.h"
     80 
     81 #include <sys/param.h>
     82 #include <sys/resourcevar.h>
     83 #include <sys/kernel.h>
     84 #include <sys/systm.h>
     85 #include <sys/lwp.h>
     86 #include <sys/malloc.h>
     87 #include <sys/proc.h>
     88 #include <sys/sa.h>
     89 #include <sys/savar.h>
     90 #include <sys/vnode.h>
     91 #include <sys/signalvar.h>
     92 #include <sys/syslog.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_var.h>
    103 #endif
    104 
    105 #include <machine/cpu.h>
    106 
    107 static void realtimerupcall(struct lwp *, void *);
    108 
    109 
    110 /* Time of day and interval timer support.
    111  *
    112  * These routines provide the kernel entry points to get and set
    113  * the time-of-day and per-process interval timers.  Subroutines
    114  * here provide support for adding and subtracting timeval structures
    115  * and decrementing interval timers, optionally reloading the interval
    116  * timers when they expire.
    117  */
    118 
    119 /* This function is used by clock_settime and settimeofday */
    120 int
    121 settime(struct timeval *tv)
    122 {
    123 	struct timeval delta;
    124 	struct cpu_info *ci;
    125 	int s;
    126 
    127 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
    128 	s = splclock();
    129 	timersub(tv, &time, &delta);
    130 	if ((delta.tv_sec < 0 || delta.tv_usec < 0) && securelevel > 1) {
    131 		splx(s);
    132 		return (EPERM);
    133 	}
    134 #ifdef notyet
    135 	if ((delta.tv_sec < 86400) && securelevel > 0) {
    136 		splx(s);
    137 		return (EPERM);
    138 	}
    139 #endif
    140 	time = *tv;
    141 	(void) spllowersoftclock();
    142 	timeradd(&boottime, &delta, &boottime);
    143 	/*
    144 	 * XXXSMP
    145 	 * This is wrong.  We should traverse a list of all
    146 	 * CPUs and add the delta to the runtime of those
    147 	 * CPUs which have a process on them.
    148 	 */
    149 	ci = curcpu();
    150 	timeradd(&ci->ci_schedstate.spc_runtime, &delta,
    151 	    &ci->ci_schedstate.spc_runtime);
    152 #	if (defined(NFS) && !defined (NFS_V2_ONLY)) || defined(NFSSERVER)
    153 		nqnfs_lease_updatetime(delta.tv_sec);
    154 #	endif
    155 	splx(s);
    156 	resettodr();
    157 	return (0);
    158 }
    159 
    160 /* ARGSUSED */
    161 int
    162 sys_clock_gettime(struct lwp *l, void *v, register_t *retval)
    163 {
    164 	struct sys_clock_gettime_args /* {
    165 		syscallarg(clockid_t) clock_id;
    166 		syscallarg(struct timespec *) tp;
    167 	} */ *uap = v;
    168 	clockid_t clock_id;
    169 	struct timeval atv;
    170 	struct timespec ats;
    171 
    172 	clock_id = SCARG(uap, clock_id);
    173 	if (clock_id != CLOCK_REALTIME)
    174 		return (EINVAL);
    175 
    176 	microtime(&atv);
    177 	TIMEVAL_TO_TIMESPEC(&atv,&ats);
    178 
    179 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
    180 }
    181 
    182 /* ARGSUSED */
    183 int
    184 sys_clock_settime(l, v, retval)
    185 	struct lwp *l;
    186 	void *v;
    187 	register_t *retval;
    188 {
    189 	struct sys_clock_settime_args /* {
    190 		syscallarg(clockid_t) clock_id;
    191 		syscallarg(const struct timespec *) tp;
    192 	} */ *uap = v;
    193 	struct proc *p = l->l_proc;
    194 	int error;
    195 
    196 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    197 		return (error);
    198 
    199 	return (clock_settime1(SCARG(uap, clock_id), SCARG(uap, tp)));
    200 }
    201 
    202 
    203 int
    204 clock_settime1(clock_id, tp)
    205 	clockid_t clock_id;
    206 	const struct timespec *tp;
    207 {
    208 	struct timespec ats;
    209 	struct timeval atv;
    210 	int error;
    211 
    212 	if ((error = copyin(tp, &ats, sizeof(ats))) != 0)
    213 		return (error);
    214 
    215 	if (clock_id != CLOCK_REALTIME)
    216 		return (EINVAL);
    217 
    218 	TIMESPEC_TO_TIMEVAL(&atv, &ats);
    219 	if ((error = settime(&atv)) != 0)
    220 		return (error);
    221 
    222 	return 0;
    223 }
    224 
    225 int
    226 sys_clock_getres(struct lwp *l, void *v, register_t *retval)
    227 {
    228 	struct sys_clock_getres_args /* {
    229 		syscallarg(clockid_t) clock_id;
    230 		syscallarg(struct timespec *) tp;
    231 	} */ *uap = v;
    232 	clockid_t clock_id;
    233 	struct timespec ts;
    234 	int error = 0;
    235 
    236 	clock_id = SCARG(uap, clock_id);
    237 	if (clock_id != CLOCK_REALTIME)
    238 		return (EINVAL);
    239 
    240 	if (SCARG(uap, tp)) {
    241 		ts.tv_sec = 0;
    242 		ts.tv_nsec = 1000000000 / hz;
    243 
    244 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
    245 	}
    246 
    247 	return error;
    248 }
    249 
    250 /* ARGSUSED */
    251 int
    252 sys_nanosleep(struct lwp *l, void *v, register_t *retval)
    253 {
    254 	static int nanowait;
    255 	struct sys_nanosleep_args/* {
    256 		syscallarg(struct timespec *) rqtp;
    257 		syscallarg(struct timespec *) rmtp;
    258 	} */ *uap = v;
    259 	struct timespec rqt;
    260 	struct timespec rmt;
    261 	struct timeval atv, utv;
    262 	int error, s, timo;
    263 
    264 	error = copyin((caddr_t)SCARG(uap, rqtp), (caddr_t)&rqt,
    265 		       sizeof(struct timespec));
    266 	if (error)
    267 		return (error);
    268 
    269 	TIMESPEC_TO_TIMEVAL(&atv,&rqt)
    270 	if (itimerfix(&atv) || atv.tv_sec > 1000000000)
    271 		return (EINVAL);
    272 
    273 	s = splclock();
    274 	timeradd(&atv,&time,&atv);
    275 	timo = hzto(&atv);
    276 	/*
    277 	 * Avoid inadvertantly sleeping forever
    278 	 */
    279 	if (timo == 0)
    280 		timo = 1;
    281 	splx(s);
    282 
    283 	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
    284 	if (error == ERESTART)
    285 		error = EINTR;
    286 	if (error == EWOULDBLOCK)
    287 		error = 0;
    288 
    289 	if (SCARG(uap, rmtp)) {
    290 		int error;
    291 
    292 		s = splclock();
    293 		utv = time;
    294 		splx(s);
    295 
    296 		timersub(&atv, &utv, &utv);
    297 		if (utv.tv_sec < 0)
    298 			timerclear(&utv);
    299 
    300 		TIMEVAL_TO_TIMESPEC(&utv,&rmt);
    301 		error = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
    302 			sizeof(rmt));
    303 		if (error)
    304 			return (error);
    305 	}
    306 
    307 	return error;
    308 }
    309 
    310 /* ARGSUSED */
    311 int
    312 sys_gettimeofday(struct lwp *l, void *v, register_t *retval)
    313 {
    314 	struct sys_gettimeofday_args /* {
    315 		syscallarg(struct timeval *) tp;
    316 		syscallarg(struct timezone *) tzp;
    317 	} */ *uap = v;
    318 	struct timeval atv;
    319 	int error = 0;
    320 	struct timezone tzfake;
    321 
    322 	if (SCARG(uap, tp)) {
    323 		microtime(&atv);
    324 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
    325 		if (error)
    326 			return (error);
    327 	}
    328 	if (SCARG(uap, tzp)) {
    329 		/*
    330 		 * NetBSD has no kernel notion of time zone, so we just
    331 		 * fake up a timezone struct and return it if demanded.
    332 		 */
    333 		tzfake.tz_minuteswest = 0;
    334 		tzfake.tz_dsttime = 0;
    335 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
    336 	}
    337 	return (error);
    338 }
    339 
    340 /* ARGSUSED */
    341 int
    342 sys_settimeofday(struct lwp *l, void *v, register_t *retval)
    343 {
    344 	struct sys_settimeofday_args /* {
    345 		syscallarg(const struct timeval *) tv;
    346 		syscallarg(const struct timezone *) tzp;
    347 	} */ *uap = v;
    348 	struct proc *p = l->l_proc;
    349 	int error;
    350 
    351 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    352 		return (error);
    353 
    354 	return settimeofday1(SCARG(uap, tv), SCARG(uap, tzp), p);
    355 }
    356 
    357 int
    358 settimeofday1(utv, utzp, p)
    359 	const struct timeval *utv;
    360 	const struct timezone *utzp;
    361 	struct proc *p;
    362 {
    363 	struct timeval atv;
    364 	struct timezone atz;
    365 	struct timeval *tv = NULL;
    366 	struct timezone *tzp = NULL;
    367 	int error;
    368 
    369 	/* Verify all parameters before changing time. */
    370 	if (utv) {
    371 		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
    372 			return (error);
    373 		tv = &atv;
    374 	}
    375 	/* XXX since we don't use tz, probably no point in doing copyin. */
    376 	if (utzp) {
    377 		if ((error = copyin(utzp, &atz, sizeof(atz))) != 0)
    378 			return (error);
    379 		tzp = &atz;
    380 	}
    381 
    382 	if (tv)
    383 		if ((error = settime(tv)) != 0)
    384 			return (error);
    385 	/*
    386 	 * NetBSD has no kernel notion of time zone, and only an
    387 	 * obsolete program would try to set it, so we log a warning.
    388 	 */
    389 	if (tzp)
    390 		log(LOG_WARNING, "pid %d attempted to set the "
    391 		    "(obsolete) kernel time zone\n", p->p_pid);
    392 	return (0);
    393 }
    394 
    395 int	tickdelta;			/* current clock skew, us. per tick */
    396 long	timedelta;			/* unapplied time correction, us. */
    397 long	bigadj = 1000000;		/* use 10x skew above bigadj us. */
    398 
    399 /* ARGSUSED */
    400 int
    401 sys_adjtime(struct lwp *l, void *v, register_t *retval)
    402 {
    403 	struct sys_adjtime_args /* {
    404 		syscallarg(const struct timeval *) delta;
    405 		syscallarg(struct timeval *) olddelta;
    406 	} */ *uap = v;
    407 	struct proc *p = l->l_proc;
    408 	int error;
    409 
    410 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    411 		return (error);
    412 
    413 	return adjtime1(SCARG(uap, delta), SCARG(uap, olddelta), p);
    414 }
    415 
    416 int
    417 adjtime1(delta, olddelta, p)
    418 	const struct timeval *delta;
    419 	struct timeval *olddelta;
    420 	struct proc *p;
    421 {
    422 	struct timeval atv;
    423 	struct timeval *oatv = NULL;
    424 	long ndelta, ntickdelta, odelta;
    425 	int error;
    426 	int s;
    427 
    428 	error = copyin(delta, &atv, sizeof(struct timeval));
    429 	if (error)
    430 		return (error);
    431 
    432 	if (olddelta != NULL) {
    433 		if (uvm_useracc((caddr_t)olddelta,
    434 		    sizeof(struct timeval), B_WRITE) == FALSE)
    435 			return (EFAULT);
    436 		oatv = olddelta;
    437 	}
    438 
    439 	/*
    440 	 * Compute the total correction and the rate at which to apply it.
    441 	 * Round the adjustment down to a whole multiple of the per-tick
    442 	 * delta, so that after some number of incremental changes in
    443 	 * hardclock(), tickdelta will become zero, lest the correction
    444 	 * overshoot and start taking us away from the desired final time.
    445 	 */
    446 	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
    447 	if (ndelta > bigadj || ndelta < -bigadj)
    448 		ntickdelta = 10 * tickadj;
    449 	else
    450 		ntickdelta = tickadj;
    451 	if (ndelta % ntickdelta)
    452 		ndelta = ndelta / ntickdelta * ntickdelta;
    453 
    454 	/*
    455 	 * To make hardclock()'s job easier, make the per-tick delta negative
    456 	 * if we want time to run slower; then hardclock can simply compute
    457 	 * tick + tickdelta, and subtract tickdelta from timedelta.
    458 	 */
    459 	if (ndelta < 0)
    460 		ntickdelta = -ntickdelta;
    461 	s = splclock();
    462 	odelta = timedelta;
    463 	timedelta = ndelta;
    464 	tickdelta = ntickdelta;
    465 	splx(s);
    466 
    467 	if (olddelta) {
    468 		atv.tv_sec = odelta / 1000000;
    469 		atv.tv_usec = odelta % 1000000;
    470 		(void) copyout(&atv, olddelta, sizeof(struct timeval));
    471 	}
    472 	return (0);
    473 }
    474 
    475 /*
    476  * Interval timer support. Both the BSD getitimer() family and the POSIX
    477  * timer_*() family of routines are supported.
    478  *
    479  * All timers are kept in an array pointed to by p_timers, which is
    480  * allocated on demand - many processes don't use timers at all. The
    481  * first three elements in this array are reserved for the BSD timers:
    482  * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, and element
    483  * 2 is ITIMER_PROF. The rest may be allocated by the timer_create()
    484  * syscall.
    485  *
    486  * Realtime timers are kept in the ptimer structure as an absolute
    487  * time; virtual time timers are kept as deltas.  Virtual time timers
    488  * are processed in the hardclock() routine of kern_clock.c.  The real
    489  * time timer is processed by a callout routine, called from the
    490  * softclock() routine.  Since a callout may be delayed in real time
    491  * due to interrupt processing in the system, it is possible for the
    492  * real time timeout routine (realtimeexpire, given below), to be
    493  * delayed in real time past when it is supposed to occur.  It does
    494  * not suffice, therefore, to reload the real timer .it_value from the
    495  * real time timers .it_interval.  Rather, we compute the next time in
    496  * absolute time the timer should go off.
    497  */
    498 
    499 /* Allocate a POSIX realtime timer. */
    500 int
    501 sys_timer_create(struct lwp *l, void *v, register_t *retval)
    502 {
    503 	struct sys_timer_create_args /* {
    504 		syscallarg(clockid_t) clock_id;
    505 		syscallarg(struct sigevent *) evp;
    506 		syscallarg(timer_t *) timerid;
    507 	} */ *uap = v;
    508 	struct proc *p = l->l_proc;
    509 	clockid_t id;
    510 	struct sigevent *evp;
    511 	struct ptimer *pt;
    512 	int timerid, error;
    513 
    514 	id = SCARG(uap, clock_id);
    515 	if (id != CLOCK_REALTIME)
    516 		return (EINVAL);
    517 
    518 	if (p->p_timers == NULL)
    519 		timers_alloc(p);
    520 
    521 	for (timerid = 3; timerid < TIMER_MAX; timerid++)
    522 		if (p->p_timers[timerid] == NULL)
    523 			break;
    524 
    525 	if (timerid == TIMER_MAX)
    526 		return EAGAIN;
    527 
    528 	pt = pool_get(&ptimer_pool, PR_WAITOK);
    529 	evp = SCARG(uap, evp);
    530 	if (evp) {
    531 		if (((error =
    532 		    copyin(evp, &pt->pt_ev, sizeof (pt->pt_ev))) != 0) ||
    533 		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
    534 			(pt->pt_ev.sigev_notify > SIGEV_SA))) {
    535 			pool_put(&ptimer_pool, pt);
    536 			return (error ? error : EINVAL);
    537 		}
    538 	} else {
    539 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
    540 		pt->pt_ev.sigev_signo = SIGALRM;
    541 		pt->pt_ev.sigev_value.sival_int = timerid;
    542 	}
    543 
    544 	callout_init(&pt->pt_ch);
    545 	pt->pt_type = CLOCK_REALTIME;
    546 	pt->pt_proc = p;
    547 	pt->pt_overruns = 0;
    548 
    549 	p->p_timers[timerid] = pt;
    550 
    551 	return copyout(&timerid, SCARG(uap, timerid), sizeof(timerid));
    552 }
    553 
    554 
    555 /* Delete a POSIX realtime timer */
    556 int
    557 sys_timer_delete(struct lwp *l, void *v, register_t *retval)
    558 {
    559 	struct sys_timer_delete_args /*  {
    560 		syscallarg(timer_t) timerid;
    561 	} */ *uap = v;
    562 	struct proc *p = l->l_proc;
    563 	int timerid;
    564 	struct ptimer *pt;
    565 
    566 	timerid = SCARG(uap, timerid);
    567 
    568 	if ((p->p_timers == NULL) ||
    569 	    (timerid < 2) || (timerid >= TIMER_MAX) ||
    570 	    ((pt = p->p_timers[timerid]) == NULL))
    571 		return (EINVAL);
    572 
    573 	callout_stop(&pt->pt_ch);
    574 	p->p_timers[timerid] = NULL;
    575 	pool_put(&ptimer_pool, pt);
    576 
    577 	return (0);
    578 }
    579 
    580 /* Set and arm a POSIX realtime timer */
    581 int
    582 sys_timer_settime(struct lwp *l, void *v, register_t *retval)
    583 {
    584 	struct sys_timer_settime_args /* {
    585 		syscallarg(timer_t) timerid;
    586 		syscallarg(int) flags;
    587 		syscallarg(const struct itimerspec *) value;
    588 		syscallarg(struct itimerspec *) ovalue;
    589 	} */ *uap = v;
    590 	struct proc *p = l->l_proc;
    591 	int error, s, timerid;
    592 	struct itimerval val, oval;
    593 	struct itimerspec value, ovalue;
    594 	struct ptimer *pt;
    595 
    596 	timerid = SCARG(uap, timerid);
    597 
    598 	if ((p->p_timers == NULL) ||
    599 	    (timerid < 2) || (timerid >= TIMER_MAX) ||
    600 	    ((pt = p->p_timers[timerid]) == NULL))
    601 		return (EINVAL);
    602 
    603 	if ((error = copyin(SCARG(uap, value), &value,
    604 	    sizeof(struct itimerspec))) != 0)
    605 		return (error);
    606 
    607 	TIMESPEC_TO_TIMEVAL(&val.it_value, &value.it_value);
    608 	TIMESPEC_TO_TIMEVAL(&val.it_interval, &value.it_interval);
    609 	if (itimerfix(&val.it_value) || itimerfix(&val.it_interval))
    610 		return (EINVAL);
    611 
    612 	oval = pt->pt_time;
    613 	pt->pt_time = val;
    614 
    615 	s = splclock();
    616 	callout_stop(&pt->pt_ch);
    617 	if (timerisset(&pt->pt_time.it_value)) {
    618 		if ((SCARG(uap, flags) & TIMER_ABSTIME) == 0)
    619 			timeradd(&pt->pt_time.it_value, &time,
    620 			    &pt->pt_time.it_value);
    621 		/*
    622 		 * Don't need to check hzto() return value, here.
    623 		 * callout_reset() does it for us.
    624 		 */
    625 		callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
    626 		    realtimerexpire, pt);
    627 	}
    628 	splx(s);
    629 
    630 	if (SCARG(uap, ovalue)) {
    631 		TIMEVAL_TO_TIMESPEC(&oval.it_value, &ovalue.it_value);
    632 		TIMEVAL_TO_TIMESPEC(&oval.it_interval, &ovalue.it_interval);
    633 		return copyout(&ovalue, SCARG(uap, ovalue),
    634 		    sizeof(struct itimerspec));
    635 	}
    636 
    637 	return (0);
    638 }
    639 
    640 /* Return the time remaining until a POSIX timer fires. */
    641 int
    642 sys_timer_gettime(struct lwp *l, void *v, register_t *retval)
    643 {
    644 	struct sys_timer_gettime_args /* {
    645 		syscallarg(timer_t) timerid;
    646 		syscallarg(struct itimerspec *) value;
    647 	} */ *uap = v;
    648 	struct itimerval aitv;
    649 	struct itimerspec its;
    650 	struct proc *p = l->l_proc;
    651 	int timerid;
    652 	struct ptimer *pt;
    653 
    654 	timerid = SCARG(uap, timerid);
    655 
    656 	if ((p->p_timers == NULL) ||
    657 	    (timerid < 2) || (timerid >= TIMER_MAX) ||
    658 	    ((pt = p->p_timers[timerid]) == NULL))
    659 		return (EINVAL);
    660 
    661 	aitv = pt->pt_time;
    662 
    663 	/*
    664 	 * Real-time timers are kept in absolute time, but this interface
    665 	 * is supposed to return a relative time.
    666 	 */
    667 	if (timerisset(&aitv.it_value)) {
    668 		if (timercmp(&aitv.it_value, &time, <))
    669 			timerclear(&aitv.it_value);
    670 		else
    671 			timersub(&aitv.it_value, &time, &aitv.it_value);
    672 	}
    673 
    674 	TIMEVAL_TO_TIMESPEC(&aitv.it_interval, &its.it_interval);
    675 	TIMEVAL_TO_TIMESPEC(&aitv.it_value, &its.it_value);
    676 
    677 	return copyout(&its, SCARG(uap, value), sizeof(its));
    678 }
    679 
    680 /*
    681  * Return the count of the number of times a periodic timer expired
    682  * while a notification was already pending. The counter is reset when
    683  * a timer expires and a notification can be posted.
    684  */
    685 int
    686 sys_timer_getoverrun(struct lwp *l, void *v, register_t *retval)
    687 {
    688 	struct sys_timer_getoverrun_args /* {
    689 		syscallarg(timer_t) timerid;
    690 	} */ *uap = v;
    691 	struct proc *p = l->l_proc;
    692 	int timerid;
    693 	struct ptimer *pt;
    694 
    695 	timerid = SCARG(uap, timerid);
    696 
    697 	if ((p->p_timers == NULL) ||
    698 	    (timerid < 2) || (timerid >= TIMER_MAX) ||
    699 	    ((pt = p->p_timers[timerid]) == NULL))
    700 		return (EINVAL);
    701 
    702 	*retval = pt->pt_overruns;
    703 
    704 	return (0);
    705 }
    706 
    707 /* Glue function that triggers an upcall; called from userret(). */
    708 static void
    709 realtimerupcall(struct lwp *l, void *arg)
    710 {
    711 	struct ptimer *pt;
    712 
    713 	pt = (struct ptimer *)arg;
    714 	sa_upcall(l, SA_UPCALL_SIGEV, NULL, l, sizeof(struct sigevent),
    715 	    &pt->pt_ev);
    716 
    717 	/* The upcall should only be generated once. */
    718 	l->l_proc->p_userret = NULL;
    719 }
    720 
    721 
    722 /*
    723  * Real interval timer expired:
    724  * send process whose timer expired an alarm signal.
    725  * If time is not set up to reload, then just return.
    726  * Else compute next time timer should go off which is > current time.
    727  * This is where delay in processing this timeout causes multiple
    728  * SIGALRM calls to be compressed into one.
    729  */
    730 void
    731 realtimerexpire(void *arg)
    732 {
    733 	struct ptimer *pt;
    734 	struct proc *p;
    735 	int s;
    736 
    737 	pt = (struct ptimer *)arg;
    738 	p = pt->pt_proc;
    739 	if (pt->pt_ev.sigev_notify == SIGEV_SIGNAL) {
    740 		/*
    741 		 * No RT signal infrastructure exists at this time;
    742 		 * just post the signal number and throw away the
    743 		 * value.
    744 		 */
    745 		if (sigismember(&p->p_sigctx.ps_siglist, pt->pt_ev.sigev_signo))
    746 			pt->pt_overruns++;
    747 		else {
    748 			pt->pt_overruns = 0;
    749 			psignal(p, pt->pt_ev.sigev_signo);
    750 		}
    751 	} else if (pt->pt_ev.sigev_notify == SIGEV_SA && (p->p_flag & P_SA)) {
    752 		int notified = 0;
    753 		/* Cause the process to generate an upcall when it returns. */
    754 
    755 		if (p->p_nrlwps == 0) {
    756 			struct sadata_upcall *sd;
    757 			struct lwp *l2;
    758 			int ret;
    759 
    760 			l2 = sa_getcachelwp(p);
    761 			if (l2 != NULL) {
    762 				sd = sadata_upcall_alloc(0);
    763 				cpu_setfunc(l2, sa_switchcall, NULL);
    764 				ret = sa_upcall0(l2, SA_UPCALL_SIGEV,
    765 				    NULL, NULL, sizeof(struct sigevent),
    766 				    &pt->pt_ev, sd);
    767 				if (ret == 0) {
    768 					p->p_nrlwps++;
    769 					l2->l_priority = l2->l_usrpri;
    770 					PRELE(l2);
    771 					setrunnable(l2);
    772 					notified = 1;
    773 				} else
    774 					sa_putcachelwp(p, l2);
    775 			}
    776 		} else if (p->p_userret == NULL) {
    777 			pt->pt_overruns = 0;
    778 			p->p_userret = realtimerupcall;
    779 			p->p_userret_arg = pt;
    780 			notified = 1;
    781 		}
    782 		if (notified == 0)
    783 			pt->pt_overruns++;
    784 	}
    785 	if (!timerisset(&pt->pt_time.it_interval)) {
    786 		timerclear(&pt->pt_time.it_value);
    787 		return;
    788 	}
    789 	for (;;) {
    790 		s = splclock();
    791 		timeradd(&pt->pt_time.it_value,
    792 		    &pt->pt_time.it_interval, &pt->pt_time.it_value);
    793 		if (timercmp(&pt->pt_time.it_value, &time, >)) {
    794 			/*
    795 			 * Don't need to check hzto() return value, here.
    796 			 * callout_reset() does it for us.
    797 			 */
    798 			callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
    799 			    realtimerexpire, pt);
    800 			splx(s);
    801 			return;
    802 		}
    803 		splx(s);
    804 		pt->pt_overruns++;
    805 	}
    806 }
    807 
    808 /* BSD routine to get the value of an interval timer. */
    809 /* ARGSUSED */
    810 int
    811 sys_getitimer(struct lwp *l, void *v, register_t *retval)
    812 {
    813 	struct sys_getitimer_args /* {
    814 		syscallarg(int) which;
    815 		syscallarg(struct itimerval *) itv;
    816 	} */ *uap = v;
    817 	struct proc *p = l->l_proc;
    818 	struct itimerval aitv;
    819 	int s, which;
    820 
    821 	which = SCARG(uap, which);
    822 
    823 	if ((u_int)which > ITIMER_PROF)
    824 		return (EINVAL);
    825 
    826 	if ((p->p_timers == NULL) || (p->p_timers[which] == NULL)) {
    827 		timerclear(&aitv.it_value);
    828 		timerclear(&aitv.it_interval);
    829 	} else {
    830 		s = splclock();
    831 		if (which == ITIMER_REAL) {
    832 			/*
    833 			 * Convert from absolute to relative time in
    834 			 * .it_value part of real time timer.  If time
    835 			 * for real time timer has passed return 0,
    836 			 * else return difference between current time
    837 			 * and time for the timer to go off.
    838 			 */
    839 			aitv = p->p_timers[ITIMER_REAL]->pt_time;
    840 			if (timerisset(&aitv.it_value)) {
    841 				if (timercmp(&aitv.it_value, &time, <))
    842 					timerclear(&aitv.it_value);
    843 				else
    844 					timersub(&aitv.it_value, &time, &aitv.it_value);
    845 			}
    846 		} else
    847 			aitv = p->p_timers[which]->pt_time;
    848 		splx(s);
    849 	}
    850 
    851 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
    852 
    853 }
    854 
    855 /* BSD routine to set/arm an interval timer. */
    856 /* ARGSUSED */
    857 int
    858 sys_setitimer(struct lwp *l, void *v, register_t *retval)
    859 {
    860 	struct sys_setitimer_args /* {
    861 		syscallarg(int) which;
    862 		syscallarg(const struct itimerval *) itv;
    863 		syscallarg(struct itimerval *) oitv;
    864 	} */ *uap = v;
    865 	struct proc *p = l->l_proc;
    866 	int which = SCARG(uap, which);
    867 	struct sys_getitimer_args getargs;
    868 	struct itimerval aitv;
    869 	const struct itimerval *itvp;
    870 	struct ptimer *pt;
    871 	int s, error;
    872 
    873 	if ((u_int)which > ITIMER_PROF)
    874 		return (EINVAL);
    875 	itvp = SCARG(uap, itv);
    876 	if (itvp &&
    877 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval)) != 0))
    878 		return (error);
    879 	if (SCARG(uap, oitv) != NULL) {
    880 		SCARG(&getargs, which) = which;
    881 		SCARG(&getargs, itv) = SCARG(uap, oitv);
    882 		if ((error = sys_getitimer(l, &getargs, retval)) != 0)
    883 			return (error);
    884 	}
    885 	if (itvp == 0)
    886 		return (0);
    887 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
    888 		return (EINVAL);
    889 
    890 	/*
    891 	 * Don't bother allocating data structures if the process just
    892 	 * wants to clear the timer.
    893 	 */
    894 	if (!timerisset(&aitv.it_value) &&
    895 	    ((p->p_timers == NULL) || (p->p_timers[which] == NULL)))
    896 		return (0);
    897 
    898 	if (p->p_timers == NULL)
    899 		timers_alloc(p);
    900 	if (p->p_timers[which] == NULL) {
    901 		pt = pool_get(&ptimer_pool, PR_WAITOK);
    902 		callout_init(&pt->pt_ch);
    903 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
    904 		pt->pt_overruns = 0;
    905 		pt->pt_proc = p;
    906 		pt->pt_type = which;
    907 		switch (which) {
    908 		case ITIMER_REAL:
    909 			pt->pt_ev.sigev_signo = SIGALRM;
    910 			break;
    911 		case ITIMER_VIRTUAL:
    912 			pt->pt_ev.sigev_signo = SIGVTALRM;
    913 			break;
    914 		case ITIMER_PROF:
    915 			pt->pt_ev.sigev_signo = SIGPROF;
    916 			break;
    917 		}
    918 	} else
    919 		pt = p->p_timers[which];
    920 
    921 	pt->pt_time = aitv;
    922 	p->p_timers[which] = pt;
    923 	if (which == ITIMER_REAL) {
    924 		s = splclock();
    925 		callout_stop(&pt->pt_ch);
    926 		if (timerisset(&pt->pt_time.it_value)) {
    927 			timeradd(&pt->pt_time.it_value, &time,
    928 			    &pt->pt_time.it_value);
    929 			/*
    930 			 * Don't need to check hzto() return value, here.
    931 			 * callout_reset() does it for us.
    932 			 */
    933 			callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
    934 			    realtimerexpire, pt);
    935 		}
    936 		splx(s);
    937 	}
    938 
    939 	return (0);
    940 }
    941 
    942 /* Utility routines to manage the array of pointers to timers. */
    943 void
    944 timers_alloc(struct proc *p)
    945 {
    946 	int i;
    947 	struct ptimer **pts;
    948 
    949 	pts = malloc(TIMER_MAX * sizeof(struct timer *), M_SUBPROC, 0);
    950 	for (i = 0; i < TIMER_MAX; i++)
    951 		pts[i] = NULL;
    952 	p->p_timers = pts;
    953 }
    954 
    955 void
    956 timers_free(struct proc *p)
    957 {
    958 	int i;
    959 	struct ptimer *pt, **pts;
    960 
    961 	if (p->p_timers) {
    962 		pts = p->p_timers;
    963 		p->p_timers = NULL;
    964 		for (i = 0; i < TIMER_MAX; i++)
    965 			if ((pt = pts[i]) != NULL) {
    966 				if (pt->pt_type == CLOCK_REALTIME)
    967 					callout_stop(&pt->pt_ch);
    968 				pool_put(&ptimer_pool, pt);
    969 			}
    970 		free(pts, M_SUBPROC);
    971 	}
    972 }
    973 
    974 /*
    975  * Check that a proposed value to load into the .it_value or
    976  * .it_interval part of an interval timer is acceptable, and
    977  * fix it to have at least minimal value (i.e. if it is less
    978  * than the resolution of the clock, round it up.)
    979  */
    980 int
    981 itimerfix(struct timeval *tv)
    982 {
    983 
    984 	if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
    985 		return (EINVAL);
    986 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
    987 		tv->tv_usec = tick;
    988 	return (0);
    989 }
    990 
    991 /*
    992  * Decrement an interval timer by a specified number
    993  * of microseconds, which must be less than a second,
    994  * i.e. < 1000000.  If the timer expires, then reload
    995  * it.  In this case, carry over (usec - old value) to
    996  * reduce the value reloaded into the timer so that
    997  * the timer does not drift.  This routine assumes
    998  * that it is called in a context where the timers
    999  * on which it is operating cannot change in value.
   1000  */
   1001 int
   1002 itimerdecr(struct itimerval *itp, int usec)
   1003 {
   1004 
   1005 	if (itp->it_value.tv_usec < usec) {
   1006 		if (itp->it_value.tv_sec == 0) {
   1007 			/* expired, and already in next interval */
   1008 			usec -= itp->it_value.tv_usec;
   1009 			goto expire;
   1010 		}
   1011 		itp->it_value.tv_usec += 1000000;
   1012 		itp->it_value.tv_sec--;
   1013 	}
   1014 	itp->it_value.tv_usec -= usec;
   1015 	usec = 0;
   1016 	if (timerisset(&itp->it_value))
   1017 		return (1);
   1018 	/* expired, exactly at end of interval */
   1019 expire:
   1020 	if (timerisset(&itp->it_interval)) {
   1021 		itp->it_value = itp->it_interval;
   1022 		itp->it_value.tv_usec -= usec;
   1023 		if (itp->it_value.tv_usec < 0) {
   1024 			itp->it_value.tv_usec += 1000000;
   1025 			itp->it_value.tv_sec--;
   1026 		}
   1027 	} else
   1028 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
   1029 	return (0);
   1030 }
   1031 
   1032 /*
   1033  * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
   1034  * for usage and rationale.
   1035  */
   1036 int
   1037 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
   1038 {
   1039 	struct timeval tv, delta;
   1040 	int s, rv = 0;
   1041 
   1042 	s = splclock();
   1043 	tv = mono_time;
   1044 	splx(s);
   1045 
   1046 	timersub(&tv, lasttime, &delta);
   1047 
   1048 	/*
   1049 	 * check for 0,0 is so that the message will be seen at least once,
   1050 	 * even if interval is huge.
   1051 	 */
   1052 	if (timercmp(&delta, mininterval, >=) ||
   1053 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
   1054 		*lasttime = tv;
   1055 		rv = 1;
   1056 	}
   1057 
   1058 	return (rv);
   1059 }
   1060 
   1061 /*
   1062  * ppsratecheck(): packets (or events) per second limitation.
   1063  */
   1064 int
   1065 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
   1066 {
   1067 	struct timeval tv, delta;
   1068 	int s, rv;
   1069 
   1070 	s = splclock();
   1071 	tv = mono_time;
   1072 	splx(s);
   1073 
   1074 	timersub(&tv, lasttime, &delta);
   1075 
   1076 	/*
   1077 	 * check for 0,0 is so that the message will be seen at least once.
   1078 	 * if more than one second have passed since the last update of
   1079 	 * lasttime, reset the counter.
   1080 	 *
   1081 	 * we do increment *curpps even in *curpps < maxpps case, as some may
   1082 	 * try to use *curpps for stat purposes as well.
   1083 	 */
   1084 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
   1085 	    delta.tv_sec >= 1) {
   1086 		*lasttime = tv;
   1087 		*curpps = 0;
   1088 		rv = 1;
   1089 	} else if (maxpps < 0)
   1090 		rv = 1;
   1091 	else if (*curpps < maxpps)
   1092 		rv = 1;
   1093 	else
   1094 		rv = 0;
   1095 
   1096 #if 1 /*DIAGNOSTIC?*/
   1097 	/* be careful about wrap-around */
   1098 	if (*curpps + 1 > *curpps)
   1099 		*curpps = *curpps + 1;
   1100 #else
   1101 	/*
   1102 	 * assume that there's not too many calls to this function.
   1103 	 * not sure if the assumption holds, as it depends on *caller's*
   1104 	 * behavior, not the behavior of this function.
   1105 	 * IMHO it is wrong to make assumption on the caller's behavior,
   1106 	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
   1107 	 */
   1108 	*curpps = *curpps + 1;
   1109 #endif
   1110 
   1111 	return (rv);
   1112 }
   1113