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