Home | History | Annotate | Line # | Download | only in kern
kern_time.c revision 1.54.2.2
      1 /*	$NetBSD: kern_time.c,v 1.54.2.2 2001/06/21 20:06:57 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 		splx(s);
    125 		return (EPERM);
    126 	}
    127 #ifdef notyet
    128 	if ((delta.tv_sec < 86400) && securelevel > 0) {
    129 		splx(s);
    130 		return (EPERM);
    131 	}
    132 #endif
    133 	time = *tv;
    134 	(void) spllowersoftclock();
    135 	timeradd(&boottime, &delta, &boottime);
    136 	/*
    137 	 * XXXSMP
    138 	 * This is wrong.  We should traverse a list of all
    139 	 * CPUs and add the delta to the runtime of those
    140 	 * CPUs which have a process on them.
    141 	 */
    142 	ci = curcpu();
    143 	timeradd(&ci->ci_schedstate.spc_runtime, &delta,
    144 	    &ci->ci_schedstate.spc_runtime);
    145 #	if (defined(NFS) && !defined (NFS_V2_ONLY)) || defined(NFSSERVER)
    146 		nqnfs_lease_updatetime(delta.tv_sec);
    147 #	endif
    148 	splx(s);
    149 	resettodr();
    150 	return (0);
    151 }
    152 
    153 /* ARGSUSED */
    154 int
    155 sys_clock_gettime(l, v, retval)
    156 	struct lwp *l;
    157 	void *v;
    158 	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 
    168 	clock_id = SCARG(uap, clock_id);
    169 	if (clock_id != CLOCK_REALTIME)
    170 		return (EINVAL);
    171 
    172 	microtime(&atv);
    173 	TIMEVAL_TO_TIMESPEC(&atv,&ats);
    174 
    175 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
    176 }
    177 
    178 /* ARGSUSED */
    179 int
    180 sys_clock_settime(l, v, retval)
    181 	struct lwp *l;
    182 	void *v;
    183 	register_t *retval;
    184 {
    185 	struct sys_clock_settime_args /* {
    186 		syscallarg(clockid_t) clock_id;
    187 		syscallarg(const struct timespec *) tp;
    188 	} */ *uap = v;
    189 	struct proc *p = l->l_proc;
    190 	clockid_t clock_id;
    191 	struct timeval atv;
    192 	struct timespec ats;
    193 	int error;
    194 
    195 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    196 		return (error);
    197 
    198 	clock_id = SCARG(uap, clock_id);
    199 	if (clock_id != CLOCK_REALTIME)
    200 		return (EINVAL);
    201 
    202 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
    203 		return (error);
    204 
    205 	TIMESPEC_TO_TIMEVAL(&atv,&ats);
    206 	if ((error = settime(&atv)))
    207 		return (error);
    208 
    209 	return 0;
    210 }
    211 
    212 int
    213 sys_clock_getres(l, v, retval)
    214 	struct lwp *l;
    215 	void *v;
    216 	register_t *retval;
    217 {
    218 	struct sys_clock_getres_args /* {
    219 		syscallarg(clockid_t) clock_id;
    220 		syscallarg(struct timespec *) tp;
    221 	} */ *uap = v;
    222 	clockid_t clock_id;
    223 	struct timespec ts;
    224 	int error = 0;
    225 
    226 	clock_id = SCARG(uap, clock_id);
    227 	if (clock_id != CLOCK_REALTIME)
    228 		return (EINVAL);
    229 
    230 	if (SCARG(uap, tp)) {
    231 		ts.tv_sec = 0;
    232 		ts.tv_nsec = 1000000000 / hz;
    233 
    234 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
    235 	}
    236 
    237 	return error;
    238 }
    239 
    240 /* ARGSUSED */
    241 int
    242 sys_nanosleep(l, v, retval)
    243 	struct lwp *l;
    244 	void *v;
    245 	register_t *retval;
    246 {
    247 	static int nanowait;
    248 	struct sys_nanosleep_args/* {
    249 		syscallarg(struct timespec *) rqtp;
    250 		syscallarg(struct timespec *) rmtp;
    251 	} */ *uap = v;
    252 	struct timespec rqt;
    253 	struct timespec rmt;
    254 	struct timeval atv, utv;
    255 	int error, s, timo;
    256 
    257 	error = copyin((caddr_t)SCARG(uap, rqtp), (caddr_t)&rqt,
    258 		       sizeof(struct timespec));
    259 	if (error)
    260 		return (error);
    261 
    262 	TIMESPEC_TO_TIMEVAL(&atv,&rqt)
    263 	if (itimerfix(&atv))
    264 		return (EINVAL);
    265 
    266 	s = splclock();
    267 	timeradd(&atv,&time,&atv);
    268 	timo = hzto(&atv);
    269 	/*
    270 	 * Avoid inadvertantly sleeping forever
    271 	 */
    272 	if (timo == 0)
    273 		timo = 1;
    274 	splx(s);
    275 
    276 	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
    277 	if (error == ERESTART)
    278 		error = EINTR;
    279 	if (error == EWOULDBLOCK)
    280 		error = 0;
    281 
    282 	if (SCARG(uap, rmtp)) {
    283 		int error;
    284 
    285 		s = splclock();
    286 		utv = time;
    287 		splx(s);
    288 
    289 		timersub(&atv, &utv, &utv);
    290 		if (utv.tv_sec < 0)
    291 			timerclear(&utv);
    292 
    293 		TIMEVAL_TO_TIMESPEC(&utv,&rmt);
    294 		error = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
    295 			sizeof(rmt));
    296 		if (error)
    297 			return (error);
    298 	}
    299 
    300 	return error;
    301 }
    302 
    303 /* ARGSUSED */
    304 int
    305 sys_gettimeofday(l, v, retval)
    306 	struct lwp *l;
    307 	void *v;
    308 	register_t *retval;
    309 {
    310 	struct sys_gettimeofday_args /* {
    311 		syscallarg(struct timeval *) tp;
    312 		syscallarg(struct timezone *) tzp;
    313 	} */ *uap = v;
    314 	struct timeval atv;
    315 	int error = 0;
    316 	struct timezone tzfake;
    317 
    318 	if (SCARG(uap, tp)) {
    319 		microtime(&atv);
    320 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
    321 		if (error)
    322 			return (error);
    323 	}
    324 	if (SCARG(uap, tzp)) {
    325 		/*
    326 		 * NetBSD has no kernel notion of time zone, so we just
    327 		 * fake up a timezone struct and return it if demanded.
    328 		 */
    329 		tzfake.tz_minuteswest = 0;
    330 		tzfake.tz_dsttime = 0;
    331 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
    332 	}
    333 	return (error);
    334 }
    335 
    336 /* ARGSUSED */
    337 int
    338 sys_settimeofday(l, v, retval)
    339 	struct lwp *l;
    340 	void *v;
    341 	register_t *retval;
    342 {
    343 	struct sys_settimeofday_args /* {
    344 		syscallarg(const struct timeval *) tv;
    345 		syscallarg(const struct timezone *) tzp;
    346 	} */ *uap = v;
    347 	struct proc *p = l->l_proc;
    348 	struct timeval atv;
    349 	struct timezone atz;
    350 	int error;
    351 
    352 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    353 		return (error);
    354 	/* Verify all parameters before changing time. */
    355 	if (SCARG(uap, tv) && (error = copyin(SCARG(uap, tv),
    356 	    &atv, sizeof(atv))))
    357 		return (error);
    358 	/* XXX since we don't use tz, probably no point in doing copyin. */
    359 	if (SCARG(uap, tzp) && (error = copyin(SCARG(uap, tzp),
    360 	    &atz, sizeof(atz))))
    361 		return (error);
    362 	if (SCARG(uap, tv))
    363 		if ((error = settime(&atv)))
    364 			return (error);
    365 	/*
    366 	 * NetBSD has no kernel notion of time zone, and only an
    367 	 * obsolete program would try to set it, so we log a warning.
    368 	 */
    369 	if (SCARG(uap, tzp))
    370 		log(LOG_WARNING, "pid %d attempted to set the "
    371 		    "(obsolete) kernel time zone\n", p->p_pid);
    372 	return (0);
    373 }
    374 
    375 int	tickdelta;			/* current clock skew, us. per tick */
    376 long	timedelta;			/* unapplied time correction, us. */
    377 long	bigadj = 1000000;		/* use 10x skew above bigadj us. */
    378 
    379 /* ARGSUSED */
    380 int
    381 sys_adjtime(l, v, retval)
    382 	struct lwp *l;
    383 	void *v;
    384 	register_t *retval;
    385 {
    386 	struct sys_adjtime_args /* {
    387 		syscallarg(const struct timeval *) delta;
    388 		syscallarg(struct timeval *) olddelta;
    389 	} */ *uap = v;
    390 	struct proc *p = l->l_proc;
    391 	struct timeval atv;
    392 	long ndelta, ntickdelta, odelta;
    393 	int s, error;
    394 
    395 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    396 		return (error);
    397 
    398 	error = copyin(SCARG(uap, delta), &atv, sizeof(struct timeval));
    399 	if (error)
    400 		return (error);
    401 	if (SCARG(uap, olddelta) != NULL &&
    402 	    uvm_useracc((caddr_t)SCARG(uap, olddelta), sizeof(struct timeval),
    403 	     B_WRITE) == FALSE)
    404 		return (EFAULT);
    405 
    406 	/*
    407 	 * Compute the total correction and the rate at which to apply it.
    408 	 * Round the adjustment down to a whole multiple of the per-tick
    409 	 * delta, so that after some number of incremental changes in
    410 	 * hardclock(), tickdelta will become zero, lest the correction
    411 	 * overshoot and start taking us away from the desired final time.
    412 	 */
    413 	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
    414 	if (ndelta > bigadj || ndelta < -bigadj)
    415 		ntickdelta = 10 * tickadj;
    416 	else
    417 		ntickdelta = tickadj;
    418 	if (ndelta % ntickdelta)
    419 		ndelta = ndelta / ntickdelta * ntickdelta;
    420 
    421 	/*
    422 	 * To make hardclock()'s job easier, make the per-tick delta negative
    423 	 * if we want time to run slower; then hardclock can simply compute
    424 	 * tick + tickdelta, and subtract tickdelta from timedelta.
    425 	 */
    426 	if (ndelta < 0)
    427 		ntickdelta = -ntickdelta;
    428 	s = splclock();
    429 	odelta = timedelta;
    430 	timedelta = ndelta;
    431 	tickdelta = ntickdelta;
    432 	splx(s);
    433 
    434 	if (SCARG(uap, olddelta)) {
    435 		atv.tv_sec = odelta / 1000000;
    436 		atv.tv_usec = odelta % 1000000;
    437 		(void) copyout(&atv, SCARG(uap, olddelta),
    438 		    sizeof(struct timeval));
    439 	}
    440 	return (0);
    441 }
    442 
    443 /*
    444  * Get value of an interval timer.  The process virtual and
    445  * profiling virtual time timers are kept in the p_stats area, since
    446  * they can be swapped out.  These are kept internally in the
    447  * way they are specified externally: in time until they expire.
    448  *
    449  * The real time interval timer is kept in the process table slot
    450  * for the process, and its value (it_value) is kept as an
    451  * absolute time rather than as a delta, so that it is easy to keep
    452  * periodic real-time signals from drifting.
    453  *
    454  * Virtual time timers are processed in the hardclock() routine of
    455  * kern_clock.c.  The real time timer is processed by a timeout
    456  * routine, called from the softclock() routine.  Since a callout
    457  * may be delayed in real time due to interrupt processing in the system,
    458  * it is possible for the real time timeout routine (realitexpire, given below),
    459  * to be delayed in real time past when it is supposed to occur.  It
    460  * does not suffice, therefore, to reload the real timer .it_value from the
    461  * real time timers .it_interval.  Rather, we compute the next time in
    462  * absolute time the timer should go off.
    463  */
    464 /* ARGSUSED */
    465 int
    466 sys_getitimer(l, v, retval)
    467 	struct lwp *l;
    468 	void *v;
    469 	register_t *retval;
    470 {
    471 	struct sys_getitimer_args /* {
    472 		syscallarg(int) which;
    473 		syscallarg(struct itimerval *) itv;
    474 	} */ *uap = v;
    475 	struct proc *p = l->l_proc;
    476 	int which = SCARG(uap, which);
    477 	struct itimerval aitv;
    478 	int s;
    479 
    480 	if ((u_int)which > ITIMER_PROF)
    481 		return (EINVAL);
    482 	s = splclock();
    483 	if (which == ITIMER_REAL) {
    484 		/*
    485 		 * Convert from absolute to relative time in .it_value
    486 		 * part of real time timer.  If time for real time timer
    487 		 * has passed return 0, else return difference between
    488 		 * current time and time for the timer to go off.
    489 		 */
    490 		aitv = p->p_realtimer;
    491 		if (timerisset(&aitv.it_value)) {
    492 			if (timercmp(&aitv.it_value, &time, <))
    493 				timerclear(&aitv.it_value);
    494 			else
    495 				timersub(&aitv.it_value, &time, &aitv.it_value);
    496 		}
    497 	} else
    498 		aitv = p->p_stats->p_timer[which];
    499 	splx(s);
    500 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
    501 }
    502 
    503 /* ARGSUSED */
    504 int
    505 sys_setitimer(l, v, retval)
    506 	struct lwp *l;
    507 	void *v;
    508 	register_t *retval;
    509 {
    510 	struct sys_setitimer_args /* {
    511 		syscallarg(int) which;
    512 		syscallarg(const struct itimerval *) itv;
    513 		syscallarg(struct itimerval *) oitv;
    514 	} */ *uap = v;
    515 	struct proc *p = l->l_proc;
    516 	int which = SCARG(uap, which);
    517 	struct sys_getitimer_args getargs;
    518 	struct itimerval aitv;
    519 	const struct itimerval *itvp;
    520 	int s, error;
    521 
    522 	if ((u_int)which > ITIMER_PROF)
    523 		return (EINVAL);
    524 	itvp = SCARG(uap, itv);
    525 	if (itvp && (error = copyin(itvp, &aitv, sizeof(struct itimerval))))
    526 		return (error);
    527 	if (SCARG(uap, oitv) != NULL) {
    528 		SCARG(&getargs, which) = which;
    529 		SCARG(&getargs, itv) = SCARG(uap, oitv);
    530 		if ((error = sys_getitimer(l, &getargs, retval)) != 0)
    531 			return (error);
    532 	}
    533 	if (itvp == 0)
    534 		return (0);
    535 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
    536 		return (EINVAL);
    537 	s = splclock();
    538 	if (which == ITIMER_REAL) {
    539 		callout_stop(&p->p_realit_ch);
    540 		if (timerisset(&aitv.it_value)) {
    541 			/*
    542 			 * Don't need to check hzto() return value, here.
    543 			 * callout_reset() does it for us.
    544 			 */
    545 			timeradd(&aitv.it_value, &time, &aitv.it_value);
    546 			callout_reset(&p->p_realit_ch, hzto(&aitv.it_value),
    547 			    realitexpire, p);
    548 		}
    549 		p->p_realtimer = aitv;
    550 	} else
    551 		p->p_stats->p_timer[which] = aitv;
    552 	splx(s);
    553 	return (0);
    554 }
    555 
    556 /*
    557  * Real interval timer expired:
    558  * send process whose timer expired an alarm signal.
    559  * If time is not set up to reload, then just return.
    560  * Else compute next time timer should go off which is > current time.
    561  * This is where delay in processing this timeout causes multiple
    562  * SIGALRM calls to be compressed into one.
    563  */
    564 void
    565 realitexpire(arg)
    566 	void *arg;
    567 {
    568 	struct proc *p;
    569 	int s;
    570 
    571 	p = (struct proc *)arg;
    572 	psignal(p, SIGALRM);
    573 	if (!timerisset(&p->p_realtimer.it_interval)) {
    574 		timerclear(&p->p_realtimer.it_value);
    575 		return;
    576 	}
    577 	for (;;) {
    578 		s = splclock();
    579 		timeradd(&p->p_realtimer.it_value,
    580 		    &p->p_realtimer.it_interval, &p->p_realtimer.it_value);
    581 		if (timercmp(&p->p_realtimer.it_value, &time, >)) {
    582 			/*
    583 			 * Don't need to check hzto() return value, here.
    584 			 * callout_reset() does it for us.
    585 			 */
    586 			callout_reset(&p->p_realit_ch,
    587 			    hzto(&p->p_realtimer.it_value), realitexpire, p);
    588 			splx(s);
    589 			return;
    590 		}
    591 		splx(s);
    592 	}
    593 }
    594 
    595 /*
    596  * Check that a proposed value to load into the .it_value or
    597  * .it_interval part of an interval timer is acceptable, and
    598  * fix it to have at least minimal value (i.e. if it is less
    599  * than the resolution of the clock, round it up.)
    600  */
    601 int
    602 itimerfix(tv)
    603 	struct timeval *tv;
    604 {
    605 
    606 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
    607 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
    608 		return (EINVAL);
    609 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
    610 		tv->tv_usec = tick;
    611 	return (0);
    612 }
    613 
    614 /*
    615  * Decrement an interval timer by a specified number
    616  * of microseconds, which must be less than a second,
    617  * i.e. < 1000000.  If the timer expires, then reload
    618  * it.  In this case, carry over (usec - old value) to
    619  * reduce the value reloaded into the timer so that
    620  * the timer does not drift.  This routine assumes
    621  * that it is called in a context where the timers
    622  * on which it is operating cannot change in value.
    623  */
    624 int
    625 itimerdecr(itp, usec)
    626 	struct itimerval *itp;
    627 	int usec;
    628 {
    629 
    630 	if (itp->it_value.tv_usec < usec) {
    631 		if (itp->it_value.tv_sec == 0) {
    632 			/* expired, and already in next interval */
    633 			usec -= itp->it_value.tv_usec;
    634 			goto expire;
    635 		}
    636 		itp->it_value.tv_usec += 1000000;
    637 		itp->it_value.tv_sec--;
    638 	}
    639 	itp->it_value.tv_usec -= usec;
    640 	usec = 0;
    641 	if (timerisset(&itp->it_value))
    642 		return (1);
    643 	/* expired, exactly at end of interval */
    644 expire:
    645 	if (timerisset(&itp->it_interval)) {
    646 		itp->it_value = itp->it_interval;
    647 		itp->it_value.tv_usec -= usec;
    648 		if (itp->it_value.tv_usec < 0) {
    649 			itp->it_value.tv_usec += 1000000;
    650 			itp->it_value.tv_sec--;
    651 		}
    652 	} else
    653 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
    654 	return (0);
    655 }
    656 
    657 /*
    658  * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
    659  * for usage and rationale.
    660  */
    661 int
    662 ratecheck(lasttime, mininterval)
    663 	struct timeval *lasttime;
    664 	const struct timeval *mininterval;
    665 {
    666 	struct timeval tv, delta;
    667 	int s, rv = 0;
    668 
    669 	s = splclock();
    670 	tv = mono_time;
    671 	splx(s);
    672 
    673 	timersub(&tv, lasttime, &delta);
    674 
    675 	/*
    676 	 * check for 0,0 is so that the message will be seen at least once,
    677 	 * even if interval is huge.
    678 	 */
    679 	if (timercmp(&delta, mininterval, >=) ||
    680 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
    681 		*lasttime = tv;
    682 		rv = 1;
    683 	}
    684 
    685 	return (rv);
    686 }
    687 
    688 /*
    689  * ppsratecheck(): packets (or events) per second limitation.
    690  */
    691 int
    692 ppsratecheck(lasttime, curpps, maxpps)
    693 	struct timeval *lasttime;
    694 	int *curpps;
    695 	int maxpps;	/* maximum pps allowed */
    696 {
    697 	struct timeval tv, delta;
    698 	int s, rv;
    699 
    700 	s = splclock();
    701 	tv = mono_time;
    702 	splx(s);
    703 
    704 	timersub(&tv, lasttime, &delta);
    705 
    706 	/*
    707 	 * check for 0,0 is so that the message will be seen at least once.
    708 	 * if more than one second have passed since the last update of
    709 	 * lasttime, reset the counter.
    710 	 *
    711 	 * we do increment *curpps even in *curpps < maxpps case, as some may
    712 	 * try to use *curpps for stat purposes as well.
    713 	 */
    714 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
    715 	    delta.tv_sec >= 1) {
    716 		*lasttime = tv;
    717 		*curpps = 0;
    718 		rv = 1;
    719 	} else if (maxpps < 0)
    720 		rv = 1;
    721 	else if (*curpps < maxpps)
    722 		rv = 1;
    723 	else
    724 		rv = 0;
    725 
    726 #if 1 /*DIAGNOSTIC?*/
    727 	/* be careful about wrap-around */
    728 	if (*curpps + 1 > *curpps)
    729 		*curpps = *curpps + 1;
    730 #else
    731 	/*
    732 	 * assume that there's not too many calls to this function.
    733 	 * not sure if the assumption holds, as it depends on *caller's*
    734 	 * behavior, not the behavior of this function.
    735 	 * IMHO it is wrong to make assumption on the caller's behavior,
    736 	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
    737 	 */
    738 	*curpps = *curpps + 1;
    739 #endif
    740 
    741 	return (rv);
    742 }
    743