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