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