xref: /netbsd-src/sys/kern/kern_time.c (revision 3b01aba77a7a698587faaae455bbfe740923c1f5)
1 /*	$NetBSD: kern_time.c,v 1.55 2001/06/11 07:07:12 tron 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/proc.h>
83 #include <sys/vnode.h>
84 #include <sys/signalvar.h>
85 #include <sys/syslog.h>
86 
87 #include <sys/mount.h>
88 #include <sys/syscallargs.h>
89 
90 #include <uvm/uvm_extern.h>
91 
92 #if defined(NFS) || defined(NFSSERVER)
93 #include <nfs/rpcv2.h>
94 #include <nfs/nfsproto.h>
95 #include <nfs/nfs_var.h>
96 #endif
97 
98 #include <machine/cpu.h>
99 
100 /*
101  * Time of day and interval timer support.
102  *
103  * These routines provide the kernel entry points to get and set
104  * the time-of-day and per-process interval timers.  Subroutines
105  * here provide support for adding and subtracting timeval structures
106  * and decrementing interval timers, optionally reloading the interval
107  * timers when they expire.
108  */
109 
110 /* This function is used by clock_settime and settimeofday */
111 int
112 settime(tv)
113 	struct timeval *tv;
114 {
115 	struct timeval delta;
116 	struct cpu_info *ci;
117 	int s;
118 
119 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
120 	s = splclock();
121 	timersub(tv, &time, &delta);
122 	if ((delta.tv_sec < 0 || delta.tv_usec < 0) && securelevel > 1) {
123 		splx(s);
124 		return (EPERM);
125 	}
126 #ifdef notyet
127 	if ((delta.tv_sec < 86400) && securelevel > 0) {
128 		splx(s);
129 		return (EPERM);
130 	}
131 #endif
132 	time = *tv;
133 	(void) spllowersoftclock();
134 	timeradd(&boottime, &delta, &boottime);
135 	/*
136 	 * XXXSMP
137 	 * This is wrong.  We should traverse a list of all
138 	 * CPUs and add the delta to the runtime of those
139 	 * CPUs which have a process on them.
140 	 */
141 	ci = curcpu();
142 	timeradd(&ci->ci_schedstate.spc_runtime, &delta,
143 	    &ci->ci_schedstate.spc_runtime);
144 #	if (defined(NFS) && !defined (NFS_V2_ONLY)) || defined(NFSSERVER)
145 		nqnfs_lease_updatetime(delta.tv_sec);
146 #	endif
147 	splx(s);
148 	resettodr();
149 	return (0);
150 }
151 
152 /* ARGSUSED */
153 int
154 sys_clock_gettime(p, v, retval)
155 	struct proc *p;
156 	void *v;
157 	register_t *retval;
158 {
159 	struct sys_clock_gettime_args /* {
160 		syscallarg(clockid_t) clock_id;
161 		syscallarg(struct timespec *) tp;
162 	} */ *uap = v;
163 	clockid_t clock_id;
164 	struct timeval atv;
165 	struct timespec ats;
166 
167 	clock_id = SCARG(uap, clock_id);
168 	if (clock_id != CLOCK_REALTIME)
169 		return (EINVAL);
170 
171 	microtime(&atv);
172 	TIMEVAL_TO_TIMESPEC(&atv,&ats);
173 
174 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
175 }
176 
177 /* ARGSUSED */
178 int
179 sys_clock_settime(p, v, retval)
180 	struct proc *p;
181 	void *v;
182 	register_t *retval;
183 {
184 	struct sys_clock_settime_args /* {
185 		syscallarg(clockid_t) clock_id;
186 		syscallarg(const struct timespec *) tp;
187 	} */ *uap = v;
188 	clockid_t clock_id;
189 	struct timeval atv;
190 	struct timespec ats;
191 	int error;
192 
193 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
194 		return (error);
195 
196 	clock_id = SCARG(uap, clock_id);
197 	if (clock_id != CLOCK_REALTIME)
198 		return (EINVAL);
199 
200 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
201 		return (error);
202 
203 	TIMESPEC_TO_TIMEVAL(&atv,&ats);
204 	if ((error = settime(&atv)))
205 		return (error);
206 
207 	return 0;
208 }
209 
210 int
211 sys_clock_getres(p, v, retval)
212 	struct proc *p;
213 	void *v;
214 	register_t *retval;
215 {
216 	struct sys_clock_getres_args /* {
217 		syscallarg(clockid_t) clock_id;
218 		syscallarg(struct timespec *) tp;
219 	} */ *uap = v;
220 	clockid_t clock_id;
221 	struct timespec ts;
222 	int error = 0;
223 
224 	clock_id = SCARG(uap, clock_id);
225 	if (clock_id != CLOCK_REALTIME)
226 		return (EINVAL);
227 
228 	if (SCARG(uap, tp)) {
229 		ts.tv_sec = 0;
230 		ts.tv_nsec = 1000000000 / hz;
231 
232 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
233 	}
234 
235 	return error;
236 }
237 
238 /* ARGSUSED */
239 int
240 sys_nanosleep(p, v, retval)
241 	struct proc *p;
242 	void *v;
243 	register_t *retval;
244 {
245 	static int nanowait;
246 	struct sys_nanosleep_args/* {
247 		syscallarg(struct timespec *) rqtp;
248 		syscallarg(struct timespec *) rmtp;
249 	} */ *uap = v;
250 	struct timespec rqt;
251 	struct timespec rmt;
252 	struct timeval atv, utv;
253 	int error, s, timo;
254 
255 	error = copyin((caddr_t)SCARG(uap, rqtp), (caddr_t)&rqt,
256 		       sizeof(struct timespec));
257 	if (error)
258 		return (error);
259 
260 	TIMESPEC_TO_TIMEVAL(&atv,&rqt)
261 	if (itimerfix(&atv))
262 		return (EINVAL);
263 
264 	s = splclock();
265 	timeradd(&atv,&time,&atv);
266 	timo = hzto(&atv);
267 	/*
268 	 * Avoid inadvertantly sleeping forever
269 	 */
270 	if (timo == 0)
271 		timo = 1;
272 	splx(s);
273 
274 	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
275 	if (error == ERESTART)
276 		error = EINTR;
277 	if (error == EWOULDBLOCK)
278 		error = 0;
279 
280 	if (SCARG(uap, rmtp)) {
281 		int error;
282 
283 		s = splclock();
284 		utv = time;
285 		splx(s);
286 
287 		timersub(&atv, &utv, &utv);
288 		if (utv.tv_sec < 0)
289 			timerclear(&utv);
290 
291 		TIMEVAL_TO_TIMESPEC(&utv,&rmt);
292 		error = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
293 			sizeof(rmt));
294 		if (error)
295 			return (error);
296 	}
297 
298 	return error;
299 }
300 
301 /* ARGSUSED */
302 int
303 sys_gettimeofday(p, v, retval)
304 	struct proc *p;
305 	void *v;
306 	register_t *retval;
307 {
308 	struct sys_gettimeofday_args /* {
309 		syscallarg(struct timeval *) tp;
310 		syscallarg(struct timezone *) tzp;
311 	} */ *uap = v;
312 	struct timeval atv;
313 	int error = 0;
314 	struct timezone tzfake;
315 
316 	if (SCARG(uap, tp)) {
317 		microtime(&atv);
318 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
319 		if (error)
320 			return (error);
321 	}
322 	if (SCARG(uap, tzp)) {
323 		/*
324 		 * NetBSD has no kernel notion of time zone, so we just
325 		 * fake up a timezone struct and return it if demanded.
326 		 */
327 		tzfake.tz_minuteswest = 0;
328 		tzfake.tz_dsttime = 0;
329 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
330 	}
331 	return (error);
332 }
333 
334 /* ARGSUSED */
335 int
336 sys_settimeofday(p, v, retval)
337 	struct proc *p;
338 	void *v;
339 	register_t *retval;
340 {
341 	struct sys_settimeofday_args /* {
342 		syscallarg(const struct timeval *) tv;
343 		syscallarg(const struct timezone *) tzp;
344 	} */ *uap = v;
345 	struct timeval atv;
346 	struct timezone atz;
347 	int error;
348 
349 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
350 		return (error);
351 	/* Verify all parameters before changing time. */
352 	if (SCARG(uap, tv) && (error = copyin(SCARG(uap, tv),
353 	    &atv, sizeof(atv))))
354 		return (error);
355 	/* XXX since we don't use tz, probably no point in doing copyin. */
356 	if (SCARG(uap, tzp) && (error = copyin(SCARG(uap, tzp),
357 	    &atz, sizeof(atz))))
358 		return (error);
359 	if (SCARG(uap, tv))
360 		if ((error = settime(&atv)))
361 			return (error);
362 	/*
363 	 * NetBSD has no kernel notion of time zone, and only an
364 	 * obsolete program would try to set it, so we log a warning.
365 	 */
366 	if (SCARG(uap, tzp))
367 		log(LOG_WARNING, "pid %d attempted to set the "
368 		    "(obsolete) kernel time zone\n", p->p_pid);
369 	return (0);
370 }
371 
372 int	tickdelta;			/* current clock skew, us. per tick */
373 long	timedelta;			/* unapplied time correction, us. */
374 long	bigadj = 1000000;		/* use 10x skew above bigadj us. */
375 
376 /* ARGSUSED */
377 int
378 sys_adjtime(p, v, retval)
379 	struct proc *p;
380 	void *v;
381 	register_t *retval;
382 {
383 	struct sys_adjtime_args /* {
384 		syscallarg(const struct timeval *) delta;
385 		syscallarg(struct timeval *) olddelta;
386 	} */ *uap = v;
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(p, v, retval)
463 	struct proc *p;
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 	int which = SCARG(uap, which);
472 	struct itimerval aitv;
473 	int s;
474 
475 	if ((u_int)which > ITIMER_PROF)
476 		return (EINVAL);
477 	s = splclock();
478 	if (which == ITIMER_REAL) {
479 		/*
480 		 * Convert from absolute to relative time in .it_value
481 		 * part of real time timer.  If time for real time timer
482 		 * has passed return 0, else return difference between
483 		 * current time and time for the timer to go off.
484 		 */
485 		aitv = p->p_realtimer;
486 		if (timerisset(&aitv.it_value)) {
487 			if (timercmp(&aitv.it_value, &time, <))
488 				timerclear(&aitv.it_value);
489 			else
490 				timersub(&aitv.it_value, &time, &aitv.it_value);
491 		}
492 	} else
493 		aitv = p->p_stats->p_timer[which];
494 	splx(s);
495 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
496 }
497 
498 /* ARGSUSED */
499 int
500 sys_setitimer(p, v, retval)
501 	struct proc *p;
502 	void *v;
503 	register_t *retval;
504 {
505 	struct sys_setitimer_args /* {
506 		syscallarg(int) which;
507 		syscallarg(const struct itimerval *) itv;
508 		syscallarg(struct itimerval *) oitv;
509 	} */ *uap = v;
510 	int which = SCARG(uap, which);
511 	struct sys_getitimer_args getargs;
512 	struct itimerval aitv;
513 	const struct itimerval *itvp;
514 	int s, error;
515 
516 	if ((u_int)which > ITIMER_PROF)
517 		return (EINVAL);
518 	itvp = SCARG(uap, itv);
519 	if (itvp && (error = copyin(itvp, &aitv, sizeof(struct itimerval))))
520 		return (error);
521 	if (SCARG(uap, oitv) != NULL) {
522 		SCARG(&getargs, which) = which;
523 		SCARG(&getargs, itv) = SCARG(uap, oitv);
524 		if ((error = sys_getitimer(p, &getargs, retval)) != 0)
525 			return (error);
526 	}
527 	if (itvp == 0)
528 		return (0);
529 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
530 		return (EINVAL);
531 	s = splclock();
532 	if (which == ITIMER_REAL) {
533 		callout_stop(&p->p_realit_ch);
534 		if (timerisset(&aitv.it_value)) {
535 			/*
536 			 * Don't need to check hzto() return value, here.
537 			 * callout_reset() does it for us.
538 			 */
539 			timeradd(&aitv.it_value, &time, &aitv.it_value);
540 			callout_reset(&p->p_realit_ch, hzto(&aitv.it_value),
541 			    realitexpire, p);
542 		}
543 		p->p_realtimer = aitv;
544 	} else
545 		p->p_stats->p_timer[which] = aitv;
546 	splx(s);
547 	return (0);
548 }
549 
550 /*
551  * Real interval timer expired:
552  * send process whose timer expired an alarm signal.
553  * If time is not set up to reload, then just return.
554  * Else compute next time timer should go off which is > current time.
555  * This is where delay in processing this timeout causes multiple
556  * SIGALRM calls to be compressed into one.
557  */
558 void
559 realitexpire(arg)
560 	void *arg;
561 {
562 	struct proc *p;
563 	int s;
564 
565 	p = (struct proc *)arg;
566 	psignal(p, SIGALRM);
567 	if (!timerisset(&p->p_realtimer.it_interval)) {
568 		timerclear(&p->p_realtimer.it_value);
569 		return;
570 	}
571 	for (;;) {
572 		s = splclock();
573 		timeradd(&p->p_realtimer.it_value,
574 		    &p->p_realtimer.it_interval, &p->p_realtimer.it_value);
575 		if (timercmp(&p->p_realtimer.it_value, &time, >)) {
576 			/*
577 			 * Don't need to check hzto() return value, here.
578 			 * callout_reset() does it for us.
579 			 */
580 			callout_reset(&p->p_realit_ch,
581 			    hzto(&p->p_realtimer.it_value), realitexpire, p);
582 			splx(s);
583 			return;
584 		}
585 		splx(s);
586 	}
587 }
588 
589 /*
590  * Check that a proposed value to load into the .it_value or
591  * .it_interval part of an interval timer is acceptable, and
592  * fix it to have at least minimal value (i.e. if it is less
593  * than the resolution of the clock, round it up.)
594  */
595 int
596 itimerfix(tv)
597 	struct timeval *tv;
598 {
599 
600 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
601 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
602 		return (EINVAL);
603 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
604 		tv->tv_usec = tick;
605 	return (0);
606 }
607 
608 /*
609  * Decrement an interval timer by a specified number
610  * of microseconds, which must be less than a second,
611  * i.e. < 1000000.  If the timer expires, then reload
612  * it.  In this case, carry over (usec - old value) to
613  * reduce the value reloaded into the timer so that
614  * the timer does not drift.  This routine assumes
615  * that it is called in a context where the timers
616  * on which it is operating cannot change in value.
617  */
618 int
619 itimerdecr(itp, usec)
620 	struct itimerval *itp;
621 	int usec;
622 {
623 
624 	if (itp->it_value.tv_usec < usec) {
625 		if (itp->it_value.tv_sec == 0) {
626 			/* expired, and already in next interval */
627 			usec -= itp->it_value.tv_usec;
628 			goto expire;
629 		}
630 		itp->it_value.tv_usec += 1000000;
631 		itp->it_value.tv_sec--;
632 	}
633 	itp->it_value.tv_usec -= usec;
634 	usec = 0;
635 	if (timerisset(&itp->it_value))
636 		return (1);
637 	/* expired, exactly at end of interval */
638 expire:
639 	if (timerisset(&itp->it_interval)) {
640 		itp->it_value = itp->it_interval;
641 		itp->it_value.tv_usec -= usec;
642 		if (itp->it_value.tv_usec < 0) {
643 			itp->it_value.tv_usec += 1000000;
644 			itp->it_value.tv_sec--;
645 		}
646 	} else
647 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
648 	return (0);
649 }
650 
651 /*
652  * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
653  * for usage and rationale.
654  */
655 int
656 ratecheck(lasttime, mininterval)
657 	struct timeval *lasttime;
658 	const struct timeval *mininterval;
659 {
660 	struct timeval tv, delta;
661 	int s, rv = 0;
662 
663 	s = splclock();
664 	tv = mono_time;
665 	splx(s);
666 
667 	timersub(&tv, lasttime, &delta);
668 
669 	/*
670 	 * check for 0,0 is so that the message will be seen at least once,
671 	 * even if interval is huge.
672 	 */
673 	if (timercmp(&delta, mininterval, >=) ||
674 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
675 		*lasttime = tv;
676 		rv = 1;
677 	}
678 
679 	return (rv);
680 }
681 
682 /*
683  * ppsratecheck(): packets (or events) per second limitation.
684  */
685 int
686 ppsratecheck(lasttime, curpps, maxpps)
687 	struct timeval *lasttime;
688 	int *curpps;
689 	int maxpps;	/* maximum pps allowed */
690 {
691 	struct timeval tv, delta;
692 	int s, rv;
693 
694 	s = splclock();
695 	tv = mono_time;
696 	splx(s);
697 
698 	timersub(&tv, lasttime, &delta);
699 
700 	/*
701 	 * check for 0,0 is so that the message will be seen at least once.
702 	 * if more than one second have passed since the last update of
703 	 * lasttime, reset the counter.
704 	 *
705 	 * we do increment *curpps even in *curpps < maxpps case, as some may
706 	 * try to use *curpps for stat purposes as well.
707 	 */
708 	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
709 	    delta.tv_sec >= 1) {
710 		*lasttime = tv;
711 		*curpps = 0;
712 		rv = 1;
713 	} else if (maxpps < 0)
714 		rv = 1;
715 	else if (*curpps < maxpps)
716 		rv = 1;
717 	else
718 		rv = 0;
719 
720 #if 1 /*DIAGNOSTIC?*/
721 	/* be careful about wrap-around */
722 	if (*curpps + 1 > *curpps)
723 		*curpps = *curpps + 1;
724 #else
725 	/*
726 	 * assume that there's not too many calls to this function.
727 	 * not sure if the assumption holds, as it depends on *caller's*
728 	 * behavior, not the behavior of this function.
729 	 * IMHO it is wrong to make assumption on the caller's behavior,
730 	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
731 	 */
732 	*curpps = *curpps + 1;
733 #endif
734 
735 	return (rv);
736 }
737