Home | History | Annotate | Line # | Download | only in kern
kern_time.c revision 1.54.2.1
      1 /*	$NetBSD: kern_time.c,v 1.54.2.1 2001/03/05 22:49:43 nathanw Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Christopher G. Demetriou.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 1982, 1986, 1989, 1993
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by the University of
     54  *	California, Berkeley and its contributors.
     55  * 4. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  *
     71  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
     72  */
     73 
     74 #include "fs_nfs.h"
     75 #include "opt_nfs.h"
     76 #include "opt_nfsserver.h"
     77 
     78 #include <sys/param.h>
     79 #include <sys/resourcevar.h>
     80 #include <sys/kernel.h>
     81 #include <sys/systm.h>
     82 #include <sys/lwp.h>
     83 #include <sys/proc.h>
     84 #include <sys/vnode.h>
     85 #include <sys/signalvar.h>
     86 #include <sys/syslog.h>
     87 
     88 #include <sys/mount.h>
     89 #include <sys/syscallargs.h>
     90 
     91 #include <uvm/uvm_extern.h>
     92 
     93 #if defined(NFS) || defined(NFSSERVER)
     94 #include <nfs/rpcv2.h>
     95 #include <nfs/nfsproto.h>
     96 #include <nfs/nfs_var.h>
     97 #endif
     98 
     99 #include <machine/cpu.h>
    100 
    101 /*
    102  * Time of day and interval timer support.
    103  *
    104  * These routines provide the kernel entry points to get and set
    105  * the time-of-day and per-process interval timers.  Subroutines
    106  * here provide support for adding and subtracting timeval structures
    107  * and decrementing interval timers, optionally reloading the interval
    108  * timers when they expire.
    109  */
    110 
    111 /* This function is used by clock_settime and settimeofday */
    112 int
    113 settime(tv)
    114 	struct timeval *tv;
    115 {
    116 	struct timeval delta;
    117 	struct cpu_info *ci;
    118 	int s;
    119 
    120 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
    121 	s = splclock();
    122 	timersub(tv, &time, &delta);
    123 	if ((delta.tv_sec < 0 || delta.tv_usec < 0) && securelevel > 1)
    124 		return (EPERM);
    125 #ifdef notyet
    126 	if ((delta.tv_sec < 86400) && securelevel > 0)
    127 		return (EPERM);
    128 #endif
    129 	time = *tv;
    130 	(void) spllowersoftclock();
    131 	timeradd(&boottime, &delta, &boottime);
    132 	/*
    133 	 * XXXSMP
    134 	 * This is wrong.  We should traverse a list of all
    135 	 * CPUs and add the delta to the runtime of those
    136 	 * CPUs which have a process on them.
    137 	 */
    138 	ci = curcpu();
    139 	timeradd(&ci->ci_schedstate.spc_runtime, &delta,
    140 	    &ci->ci_schedstate.spc_runtime);
    141 #	if (defined(NFS) && !defined (NFS_V2_ONLY)) || defined(NFSSERVER)
    142 		nqnfs_lease_updatetime(delta.tv_sec);
    143 #	endif
    144 	splx(s);
    145 	resettodr();
    146 	return (0);
    147 }
    148 
    149 /* ARGSUSED */
    150 int
    151 sys_clock_gettime(l, v, retval)
    152 	struct lwp *l;
    153 	void *v;
    154 	register_t *retval;
    155 {
    156 	struct sys_clock_gettime_args /* {
    157 		syscallarg(clockid_t) clock_id;
    158 		syscallarg(struct timespec *) tp;
    159 	} */ *uap = v;
    160 	clockid_t clock_id;
    161 	struct timeval atv;
    162 	struct timespec ats;
    163 
    164 	clock_id = SCARG(uap, clock_id);
    165 	if (clock_id != CLOCK_REALTIME)
    166 		return (EINVAL);
    167 
    168 	microtime(&atv);
    169 	TIMEVAL_TO_TIMESPEC(&atv,&ats);
    170 
    171 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
    172 }
    173 
    174 /* ARGSUSED */
    175 int
    176 sys_clock_settime(l, v, retval)
    177 	struct lwp *l;
    178 	void *v;
    179 	register_t *retval;
    180 {
    181 	struct sys_clock_settime_args /* {
    182 		syscallarg(clockid_t) clock_id;
    183 		syscallarg(const struct timespec *) tp;
    184 	} */ *uap = v;
    185 	struct proc *p = l->l_proc;
    186 	clockid_t clock_id;
    187 	struct timeval atv;
    188 	struct timespec ats;
    189 	int error;
    190 
    191 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    192 		return (error);
    193 
    194 	clock_id = SCARG(uap, clock_id);
    195 	if (clock_id != CLOCK_REALTIME)
    196 		return (EINVAL);
    197 
    198 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
    199 		return (error);
    200 
    201 	TIMESPEC_TO_TIMEVAL(&atv,&ats);
    202 	if ((error = settime(&atv)))
    203 		return (error);
    204 
    205 	return 0;
    206 }
    207 
    208 int
    209 sys_clock_getres(l, v, retval)
    210 	struct lwp *l;
    211 	void *v;
    212 	register_t *retval;
    213 {
    214 	struct sys_clock_getres_args /* {
    215 		syscallarg(clockid_t) clock_id;
    216 		syscallarg(struct timespec *) tp;
    217 	} */ *uap = v;
    218 	clockid_t clock_id;
    219 	struct timespec ts;
    220 	int error = 0;
    221 
    222 	clock_id = SCARG(uap, clock_id);
    223 	if (clock_id != CLOCK_REALTIME)
    224 		return (EINVAL);
    225 
    226 	if (SCARG(uap, tp)) {
    227 		ts.tv_sec = 0;
    228 		ts.tv_nsec = 1000000000 / hz;
    229 
    230 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
    231 	}
    232 
    233 	return error;
    234 }
    235 
    236 /* ARGSUSED */
    237 int
    238 sys_nanosleep(l, v, retval)
    239 	struct lwp *l;
    240 	void *v;
    241 	register_t *retval;
    242 {
    243 	static int nanowait;
    244 	struct sys_nanosleep_args/* {
    245 		syscallarg(struct timespec *) rqtp;
    246 		syscallarg(struct timespec *) rmtp;
    247 	} */ *uap = v;
    248 	struct timespec rqt;
    249 	struct timespec rmt;
    250 	struct timeval atv, utv;
    251 	int error, s, timo;
    252 
    253 	error = copyin((caddr_t)SCARG(uap, rqtp), (caddr_t)&rqt,
    254 		       sizeof(struct timespec));
    255 	if (error)
    256 		return (error);
    257 
    258 	TIMESPEC_TO_TIMEVAL(&atv,&rqt)
    259 	if (itimerfix(&atv))
    260 		return (EINVAL);
    261 
    262 	s = splclock();
    263 	timeradd(&atv,&time,&atv);
    264 	timo = hzto(&atv);
    265 	/*
    266 	 * Avoid inadvertantly sleeping forever
    267 	 */
    268 	if (timo == 0)
    269 		timo = 1;
    270 	splx(s);
    271 
    272 	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
    273 	if (error == ERESTART)
    274 		error = EINTR;
    275 	if (error == EWOULDBLOCK)
    276 		error = 0;
    277 
    278 	if (SCARG(uap, rmtp)) {
    279 		int error;
    280 
    281 		s = splclock();
    282 		utv = time;
    283 		splx(s);
    284 
    285 		timersub(&atv, &utv, &utv);
    286 		if (utv.tv_sec < 0)
    287 			timerclear(&utv);
    288 
    289 		TIMEVAL_TO_TIMESPEC(&utv,&rmt);
    290 		error = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
    291 			sizeof(rmt));
    292 		if (error)
    293 			return (error);
    294 	}
    295 
    296 	return error;
    297 }
    298 
    299 /* ARGSUSED */
    300 int
    301 sys_gettimeofday(l, v, retval)
    302 	struct lwp *l;
    303 	void *v;
    304 	register_t *retval;
    305 {
    306 	struct sys_gettimeofday_args /* {
    307 		syscallarg(struct timeval *) tp;
    308 		syscallarg(struct timezone *) tzp;
    309 	} */ *uap = v;
    310 	struct timeval atv;
    311 	int error = 0;
    312 	struct timezone tzfake;
    313 
    314 	if (SCARG(uap, tp)) {
    315 		microtime(&atv);
    316 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
    317 		if (error)
    318 			return (error);
    319 	}
    320 	if (SCARG(uap, tzp)) {
    321 		/*
    322 		 * NetBSD has no kernel notion of time zone, so we just
    323 		 * fake up a timezone struct and return it if demanded.
    324 		 */
    325 		tzfake.tz_minuteswest = 0;
    326 		tzfake.tz_dsttime = 0;
    327 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
    328 	}
    329 	return (error);
    330 }
    331 
    332 /* ARGSUSED */
    333 int
    334 sys_settimeofday(l, v, retval)
    335 	struct lwp *l;
    336 	void *v;
    337 	register_t *retval;
    338 {
    339 	struct sys_settimeofday_args /* {
    340 		syscallarg(const struct timeval *) tv;
    341 		syscallarg(const struct timezone *) tzp;
    342 	} */ *uap = v;
    343 	struct proc *p = l->l_proc;
    344 	struct timeval atv;
    345 	struct timezone atz;
    346 	int error;
    347 
    348 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    349 		return (error);
    350 	/* Verify all parameters before changing time. */
    351 	if (SCARG(uap, tv) && (error = copyin(SCARG(uap, tv),
    352 	    &atv, sizeof(atv))))
    353 		return (error);
    354 	/* XXX since we don't use tz, probably no point in doing copyin. */
    355 	if (SCARG(uap, tzp) && (error = copyin(SCARG(uap, tzp),
    356 	    &atz, sizeof(atz))))
    357 		return (error);
    358 	if (SCARG(uap, tv))
    359 		if ((error = settime(&atv)))
    360 			return (error);
    361 	/*
    362 	 * NetBSD has no kernel notion of time zone, and only an
    363 	 * obsolete program would try to set it, so we log a warning.
    364 	 */
    365 	if (SCARG(uap, tzp))
    366 		log(LOG_WARNING, "pid %d attempted to set the "
    367 		    "(obsolete) kernel time zone\n", p->p_pid);
    368 	return (0);
    369 }
    370 
    371 int	tickdelta;			/* current clock skew, us. per tick */
    372 long	timedelta;			/* unapplied time correction, us. */
    373 long	bigadj = 1000000;		/* use 10x skew above bigadj us. */
    374 
    375 /* ARGSUSED */
    376 int
    377 sys_adjtime(l, v, retval)
    378 	struct lwp *l;
    379 	void *v;
    380 	register_t *retval;
    381 {
    382 	struct sys_adjtime_args /* {
    383 		syscallarg(const struct timeval *) delta;
    384 		syscallarg(struct timeval *) olddelta;
    385 	} */ *uap = v;
    386 	struct proc *p = l->l_proc;
    387 	struct timeval atv;
    388 	long ndelta, ntickdelta, odelta;
    389 	int s, error;
    390 
    391 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    392 		return (error);
    393 
    394 	error = copyin(SCARG(uap, delta), &atv, sizeof(struct timeval));
    395 	if (error)
    396 		return (error);
    397 	if (SCARG(uap, olddelta) != NULL &&
    398 	    uvm_useracc((caddr_t)SCARG(uap, olddelta), sizeof(struct timeval),
    399 	     B_WRITE) == FALSE)
    400 		return (EFAULT);
    401 
    402 	/*
    403 	 * Compute the total correction and the rate at which to apply it.
    404 	 * Round the adjustment down to a whole multiple of the per-tick
    405 	 * delta, so that after some number of incremental changes in
    406 	 * hardclock(), tickdelta will become zero, lest the correction
    407 	 * overshoot and start taking us away from the desired final time.
    408 	 */
    409 	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
    410 	if (ndelta > bigadj || ndelta < -bigadj)
    411 		ntickdelta = 10 * tickadj;
    412 	else
    413 		ntickdelta = tickadj;
    414 	if (ndelta % ntickdelta)
    415 		ndelta = ndelta / ntickdelta * ntickdelta;
    416 
    417 	/*
    418 	 * To make hardclock()'s job easier, make the per-tick delta negative
    419 	 * if we want time to run slower; then hardclock can simply compute
    420 	 * tick + tickdelta, and subtract tickdelta from timedelta.
    421 	 */
    422 	if (ndelta < 0)
    423 		ntickdelta = -ntickdelta;
    424 	s = splclock();
    425 	odelta = timedelta;
    426 	timedelta = ndelta;
    427 	tickdelta = ntickdelta;
    428 	splx(s);
    429 
    430 	if (SCARG(uap, olddelta)) {
    431 		atv.tv_sec = odelta / 1000000;
    432 		atv.tv_usec = odelta % 1000000;
    433 		(void) copyout(&atv, SCARG(uap, olddelta),
    434 		    sizeof(struct timeval));
    435 	}
    436 	return (0);
    437 }
    438 
    439 /*
    440  * Get value of an interval timer.  The process virtual and
    441  * profiling virtual time timers are kept in the p_stats area, since
    442  * they can be swapped out.  These are kept internally in the
    443  * way they are specified externally: in time until they expire.
    444  *
    445  * The real time interval timer is kept in the process table slot
    446  * for the process, and its value (it_value) is kept as an
    447  * absolute time rather than as a delta, so that it is easy to keep
    448  * periodic real-time signals from drifting.
    449  *
    450  * Virtual time timers are processed in the hardclock() routine of
    451  * kern_clock.c.  The real time timer is processed by a timeout
    452  * routine, called from the softclock() routine.  Since a callout
    453  * may be delayed in real time due to interrupt processing in the system,
    454  * it is possible for the real time timeout routine (realitexpire, given below),
    455  * to be delayed in real time past when it is supposed to occur.  It
    456  * does not suffice, therefore, to reload the real timer .it_value from the
    457  * real time timers .it_interval.  Rather, we compute the next time in
    458  * absolute time the timer should go off.
    459  */
    460 /* ARGSUSED */
    461 int
    462 sys_getitimer(l, v, retval)
    463 	struct lwp *l;
    464 	void *v;
    465 	register_t *retval;
    466 {
    467 	struct sys_getitimer_args /* {
    468 		syscallarg(int) which;
    469 		syscallarg(struct itimerval *) itv;
    470 	} */ *uap = v;
    471 	struct proc *p = l->l_proc;
    472 	int which = SCARG(uap, which);
    473 	struct itimerval aitv;
    474 	int s;
    475 
    476 	if ((u_int)which > ITIMER_PROF)
    477 		return (EINVAL);
    478 	s = splclock();
    479 	if (which == ITIMER_REAL) {
    480 		/*
    481 		 * Convert from absolute to relative time in .it_value
    482 		 * part of real time timer.  If time for real time timer
    483 		 * has passed return 0, else return difference between
    484 		 * current time and time for the timer to go off.
    485 		 */
    486 		aitv = p->p_realtimer;
    487 		if (timerisset(&aitv.it_value)) {
    488 			if (timercmp(&aitv.it_value, &time, <))
    489 				timerclear(&aitv.it_value);
    490 			else
    491 				timersub(&aitv.it_value, &time, &aitv.it_value);
    492 		}
    493 	} else
    494 		aitv = p->p_stats->p_timer[which];
    495 	splx(s);
    496 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
    497 }
    498 
    499 /* ARGSUSED */
    500 int
    501 sys_setitimer(l, v, retval)
    502 	struct lwp *l;
    503 	void *v;
    504 	register_t *retval;
    505 {
    506 	struct sys_setitimer_args /* {
    507 		syscallarg(int) which;
    508 		syscallarg(const struct itimerval *) itv;
    509 		syscallarg(struct itimerval *) oitv;
    510 	} */ *uap = v;
    511 	struct proc *p = l->l_proc;
    512 	int which = SCARG(uap, which);
    513 	struct sys_getitimer_args getargs;
    514 	struct itimerval aitv;
    515 	const struct itimerval *itvp;
    516 	int s, error;
    517 
    518 	if ((u_int)which > ITIMER_PROF)
    519 		return (EINVAL);
    520 	itvp = SCARG(uap, itv);
    521 	if (itvp && (error = copyin(itvp, &aitv, sizeof(struct itimerval))))
    522 		return (error);
    523 	if (SCARG(uap, oitv) != NULL) {
    524 		SCARG(&getargs, which) = which;
    525 		SCARG(&getargs, itv) = SCARG(uap, oitv);
    526 		if ((error = sys_getitimer(l, &getargs, retval)) != 0)
    527 			return (error);
    528 	}
    529 	if (itvp == 0)
    530 		return (0);
    531 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
    532 		return (EINVAL);
    533 	s = splclock();
    534 	if (which == ITIMER_REAL) {
    535 		callout_stop(&p->p_realit_ch);
    536 		if (timerisset(&aitv.it_value)) {
    537 			/*
    538 			 * Don't need to check hzto() return value, here.
    539 			 * callout_reset() does it for us.
    540 			 */
    541 			timeradd(&aitv.it_value, &time, &aitv.it_value);
    542 			callout_reset(&p->p_realit_ch, hzto(&aitv.it_value),
    543 			    realitexpire, p);
    544 		}
    545 		p->p_realtimer = aitv;
    546 	} else
    547 		p->p_stats->p_timer[which] = aitv;
    548 	splx(s);
    549 	return (0);
    550 }
    551 
    552 /*
    553  * Real interval timer expired:
    554  * send process whose timer expired an alarm signal.
    555  * If time is not set up to reload, then just return.
    556  * Else compute next time timer should go off which is > current time.
    557  * This is where delay in processing this timeout causes multiple
    558  * SIGALRM calls to be compressed into one.
    559  */
    560 void
    561 realitexpire(arg)
    562 	void *arg;
    563 {
    564 	struct proc *p;
    565 	int s;
    566 
    567 	p = (struct proc *)arg;
    568 	psignal(p, SIGALRM);
    569 	if (!timerisset(&p->p_realtimer.it_interval)) {
    570 		timerclear(&p->p_realtimer.it_value);
    571 		return;
    572 	}
    573 	for (;;) {
    574 		s = splclock();
    575 		timeradd(&p->p_realtimer.it_value,
    576 		    &p->p_realtimer.it_interval, &p->p_realtimer.it_value);
    577 		if (timercmp(&p->p_realtimer.it_value, &time, >)) {
    578 			/*
    579 			 * Don't need to check hzto() return value, here.
    580 			 * callout_reset() does it for us.
    581 			 */
    582 			callout_reset(&p->p_realit_ch,
    583 			    hzto(&p->p_realtimer.it_value), realitexpire, p);
    584 			splx(s);
    585 			return;
    586 		}
    587 		splx(s);
    588 	}
    589 }
    590 
    591 /*
    592  * Check that a proposed value to load into the .it_value or
    593  * .it_interval part of an interval timer is acceptable, and
    594  * fix it to have at least minimal value (i.e. if it is less
    595  * than the resolution of the clock, round it up.)
    596  */
    597 int
    598 itimerfix(tv)
    599 	struct timeval *tv;
    600 {
    601 
    602 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
    603 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
    604 		return (EINVAL);
    605 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
    606 		tv->tv_usec = tick;
    607 	return (0);
    608 }
    609 
    610 /*
    611  * Decrement an interval timer by a specified number
    612  * of microseconds, which must be less than a second,
    613  * i.e. < 1000000.  If the timer expires, then reload
    614  * it.  In this case, carry over (usec - old value) to
    615  * reduce the value reloaded into the timer so that
    616  * the timer does not drift.  This routine assumes
    617  * that it is called in a context where the timers
    618  * on which it is operating cannot change in value.
    619  */
    620 int
    621 itimerdecr(itp, usec)
    622 	struct itimerval *itp;
    623 	int usec;
    624 {
    625 
    626 	if (itp->it_value.tv_usec < usec) {
    627 		if (itp->it_value.tv_sec == 0) {
    628 			/* expired, and already in next interval */
    629 			usec -= itp->it_value.tv_usec;
    630 			goto expire;
    631 		}
    632 		itp->it_value.tv_usec += 1000000;
    633 		itp->it_value.tv_sec--;
    634 	}
    635 	itp->it_value.tv_usec -= usec;
    636 	usec = 0;
    637 	if (timerisset(&itp->it_value))
    638 		return (1);
    639 	/* expired, exactly at end of interval */
    640 expire:
    641 	if (timerisset(&itp->it_interval)) {
    642 		itp->it_value = itp->it_interval;
    643 		itp->it_value.tv_usec -= usec;
    644 		if (itp->it_value.tv_usec < 0) {
    645 			itp->it_value.tv_usec += 1000000;
    646 			itp->it_value.tv_sec--;
    647 		}
    648 	} else
    649 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
    650 	return (0);
    651 }
    652 
    653 /*
    654  * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
    655  * for usage and rationale.
    656  */
    657 int
    658 ratecheck(lasttime, mininterval)
    659 	struct timeval *lasttime;
    660 	const struct timeval *mininterval;
    661 {
    662 	struct timeval tv, delta;
    663 	int s, rv = 0;
    664 
    665 	s = splclock();
    666 	tv = mono_time;
    667 	splx(s);
    668 
    669 	timersub(&tv, lasttime, &delta);
    670 
    671 	/*
    672 	 * check for 0,0 is so that the message will be seen at least once,
    673 	 * even if interval is huge.
    674 	 */
    675 	if (timercmp(&delta, mininterval, >=) ||
    676 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
    677 		*lasttime = tv;
    678 		rv = 1;
    679 	}
    680 
    681 	return (rv);
    682 }
    683 
    684 /*
    685  * ppsratecheck(): packets (or events) per second limitation.
    686  */
    687 int
    688 ppsratecheck(lasttime, curpps, maxpps)
    689 	struct timeval *lasttime;
    690 	int *curpps;
    691 	int maxpps;	/* maximum pps allowed */
    692 {
    693 	struct timeval tv, delta;
    694 	int s, rv;
    695 
    696 	s = splclock();
    697 	tv = mono_time;
    698 	splx(s);
    699 
    700 	timersub(&tv, lasttime, &delta);
    701 
    702 	/*
    703 	 * check for 0,0 is so that the message will be seen at least once.
    704 	 * if more than one second have passed since the last update of
    705 	 * lasttime, reset the counter.
    706 	 *
    707 	 * we do increment *curpps even in *curpps < maxpps case, as some may
    708 	 * try to use *curpps for stat purposes as well.
    709 	 */
    710 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
    711 	    delta.tv_sec >= 1) {
    712 		*lasttime = tv;
    713 		*curpps = 0;
    714 		rv = 1;
    715 	} else if (maxpps < 0)
    716 		rv = 1;
    717 	else if (*curpps < maxpps)
    718 		rv = 1;
    719 	else
    720 		rv = 0;
    721 
    722 #if 1 /*DIAGNOSTIC?*/
    723 	/* be careful about wrap-around */
    724 	if (*curpps + 1 > *curpps)
    725 		*curpps = *curpps + 1;
    726 #else
    727 	/*
    728 	 * assume that there's not too many calls to this function.
    729 	 * not sure if the assumption holds, as it depends on *caller's*
    730 	 * behavior, not the behavior of this function.
    731 	 * IMHO it is wrong to make assumption on the caller's behavior,
    732 	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
    733 	 */
    734 	*curpps = *curpps + 1;
    735 #endif
    736 
    737 	return (rv);
    738 }
    739