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