xref: /dflybsd-src/sys/kern/kern_time.c (revision ac2e3f5effc58aa364c7e5c199f35ebbae7cda81)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)kern_time.c	8.1 (Berkeley) 6/10/93
34  * $FreeBSD: src/sys/kern/kern_time.c,v 1.68.2.1 2002/10/01 08:00:41 bde Exp $
35  * $DragonFly: src/sys/kern/kern_time.c,v 1.9 2003/08/12 02:36:15 dillon Exp $
36  */
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/buf.h>
41 #include <sys/sysproto.h>
42 #include <sys/resourcevar.h>
43 #include <sys/signalvar.h>
44 #include <sys/kernel.h>
45 #include <sys/systm.h>
46 #include <sys/sysent.h>
47 #include <sys/proc.h>
48 #include <sys/time.h>
49 #include <sys/vnode.h>
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52 #include <sys/msgport2.h>
53 
54 struct timezone tz;
55 
56 /*
57  * Time of day and interval timer support.
58  *
59  * These routines provide the kernel entry points to get and set
60  * the time-of-day and per-process interval timers.  Subroutines
61  * here provide support for adding and subtracting timeval structures
62  * and decrementing interval timers, optionally reloading the interval
63  * timers when they expire.
64  */
65 
66 static int	nanosleep1 __P((struct timespec *rqt,
67 		    struct timespec *rmt));
68 static int	settime __P((struct timeval *));
69 static void	timevalfix __P((struct timeval *));
70 static void	no_lease_updatetime __P((int));
71 
72 static void
73 no_lease_updatetime(deltat)
74 	int deltat;
75 {
76 }
77 
78 void (*lease_updatetime) __P((int))  = no_lease_updatetime;
79 
80 static int
81 settime(tv)
82 	struct timeval *tv;
83 {
84 	struct timeval delta, tv1, tv2;
85 	static struct timeval maxtime, laststep;
86 	struct timespec ts;
87 	int s;
88 
89 	s = splclock();
90 	microtime(&tv1);
91 	delta = *tv;
92 	timevalsub(&delta, &tv1);
93 
94 	/*
95 	 * If the system is secure, we do not allow the time to be
96 	 * set to a value earlier than 1 second less than the highest
97 	 * time we have yet seen. The worst a miscreant can do in
98 	 * this circumstance is "freeze" time. He couldn't go
99 	 * back to the past.
100 	 *
101 	 * We similarly do not allow the clock to be stepped more
102 	 * than one second, nor more than once per second. This allows
103 	 * a miscreant to make the clock march double-time, but no worse.
104 	 */
105 	if (securelevel > 1) {
106 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
107 			/*
108 			 * Update maxtime to latest time we've seen.
109 			 */
110 			if (tv1.tv_sec > maxtime.tv_sec)
111 				maxtime = tv1;
112 			tv2 = *tv;
113 			timevalsub(&tv2, &maxtime);
114 			if (tv2.tv_sec < -1) {
115 				tv->tv_sec = maxtime.tv_sec - 1;
116 				printf("Time adjustment clamped to -1 second\n");
117 			}
118 		} else {
119 			if (tv1.tv_sec == laststep.tv_sec) {
120 				splx(s);
121 				return (EPERM);
122 			}
123 			if (delta.tv_sec > 1) {
124 				tv->tv_sec = tv1.tv_sec + 1;
125 				printf("Time adjustment clamped to +1 second\n");
126 			}
127 			laststep = *tv;
128 		}
129 	}
130 
131 	ts.tv_sec = tv->tv_sec;
132 	ts.tv_nsec = tv->tv_usec * 1000;
133 	set_timecounter(&ts);
134 	(void) splsoftclock();
135 	lease_updatetime(delta.tv_sec);
136 	splx(s);
137 	resettodr();
138 	return (0);
139 }
140 
141 /* ARGSUSED */
142 int
143 clock_gettime(struct clock_gettime_args *uap)
144 {
145 	struct timespec ats;
146 
147 	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
148 		return (EINVAL);
149 	nanotime(&ats);
150 	return (copyout(&ats, SCARG(uap, tp), sizeof(ats)));
151 }
152 
153 /* ARGSUSED */
154 int
155 clock_settime(struct clock_settime_args *uap)
156 {
157 	struct thread *td = curthread;
158 	struct timeval atv;
159 	struct timespec ats;
160 	int error;
161 
162 	if ((error = suser(td)) != 0)
163 		return (error);
164 	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
165 		return (EINVAL);
166 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
167 		return (error);
168 	if (ats.tv_nsec < 0 || ats.tv_nsec >= 1000000000)
169 		return (EINVAL);
170 	/* XXX Don't convert nsec->usec and back */
171 	TIMESPEC_TO_TIMEVAL(&atv, &ats);
172 	if ((error = settime(&atv)))
173 		return (error);
174 	return (0);
175 }
176 
177 int
178 clock_getres(struct clock_getres_args *uap)
179 {
180 	struct timespec ts;
181 	int error;
182 
183 	if (SCARG(uap, clock_id) != CLOCK_REALTIME)
184 		return (EINVAL);
185 	error = 0;
186 	if (SCARG(uap, tp)) {
187 		ts.tv_sec = 0;
188 		/*
189 		 * Round up the result of the division cheaply by adding 1.
190 		 * Rounding up is especially important if rounding down
191 		 * would give 0.  Perfect rounding is unimportant.
192 		 */
193 		ts.tv_nsec = 1000000000 / timecounter->tc_frequency + 1;
194 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
195 	}
196 	return (error);
197 }
198 
199 static int nanowait;
200 
201 static int
202 nanosleep1(struct timespec *rqt, struct timespec *rmt)
203 {
204 	struct timespec ts, ts2, ts3;
205 	struct timeval tv;
206 	int error;
207 
208 	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
209 		return (EINVAL);
210 	if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
211 		return (0);
212 	getnanouptime(&ts);
213 	timespecadd(&ts, rqt);
214 	TIMESPEC_TO_TIMEVAL(&tv, rqt);
215 	for (;;) {
216 		error = tsleep(&nanowait, PCATCH, "nanslp",
217 		    tvtohz(&tv));
218 		getnanouptime(&ts2);
219 		if (error != EWOULDBLOCK) {
220 			if (error == ERESTART)
221 				error = EINTR;
222 			if (rmt != NULL) {
223 				timespecsub(&ts, &ts2);
224 				if (ts.tv_sec < 0)
225 					timespecclear(&ts);
226 				*rmt = ts;
227 			}
228 			return (error);
229 		}
230 		if (timespeccmp(&ts2, &ts, >=))
231 			return (0);
232 		ts3 = ts;
233 		timespecsub(&ts3, &ts2);
234 		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
235 	}
236 }
237 
238 static void nanosleep_done(void *arg);
239 static void nanosleep_return(lwkt_port_t port, lwkt_msg_t msg);
240 
241 /* ARGSUSED */
242 int
243 nanosleep(struct nanosleep_args *uap)
244 {
245 	int error;
246 	struct sysmsg_sleep *sysmsg = &uap->sysmsg.sm_sleep;
247 
248 	error = copyin(uap->rqtp, &sysmsg->rqt, sizeof(sysmsg->rqt));
249 	if (error)
250 		return (error);
251 	/*
252 	 * YYY clean this up to always use the callout, note that an abort
253 	 * implementation should record the residual in the async case.
254 	 */
255 	if (sysmsg->lmsg.ms_flags & MSGF_ASYNC) {
256 		quad_t ticks;
257 
258 		ticks = (quad_t)sysmsg->rqt.tv_nsec * hz / 1000000000LL;
259 		if (sysmsg->rqt.tv_sec)
260 			ticks += (quad_t)sysmsg->rqt.tv_sec * hz;
261 		if (ticks <= 0) {
262 			if (ticks == 0)
263 				error = 0;
264 			else
265 				error = EINVAL;
266 		} else {
267 			sysmsg->lmsg.ms_cleanupmsg = nanosleep_return;
268 			callout_init(&sysmsg->timer);
269 			callout_reset(&sysmsg->timer, ticks, nanosleep_done, uap);
270 			error = EASYNC;
271 		}
272 	} else {
273 		/*
274 		 * Old synchronous sleep code, copyout the residual if
275 		 * nanosleep was interrupted.
276 		 */
277 		error = nanosleep1(&sysmsg->rqt, &sysmsg->rmt);
278 		if (error && SCARG(uap, rmtp))
279 			error = copyout(&sysmsg->rmt, SCARG(uap, rmtp), sizeof(sysmsg->rmt));
280 	}
281 	return (error);
282 }
283 
284 /*
285  * Asynch completion for the nanosleep() syscall.  This function may be
286  * called from any context and cannot legally access the originating
287  * thread, proc, or its user space.
288  *
289  * YYY change the callout interface API so we can simply assign the replymsg
290  * function to it directly.
291  */
292 static void
293 nanosleep_done(void *arg)
294 {
295 	struct nanosleep_args *uap = arg;
296 
297 	lwkt_replymsg(&uap->sysmsg.lmsg, 0);
298 }
299 
300 /*
301  * Asynch return for the nanosleep() syscall, called in the context of the
302  * originating thread when it pulls the message off the reply port.  This
303  * function is responsible for any copyouts to userland.  Kernel threads
304  * which do their own internal system calls will not usually call the return
305  * function.
306  */
307 static void
308 nanosleep_return(lwkt_port_t port, lwkt_msg_t msg)
309 {
310 	struct nanosleep_args *uap = (void *)msg;
311 	struct sysmsg_sleep *sysmsg = &uap->sysmsg.sm_sleep;
312 
313 	if (sysmsg->lmsg.ms_error && uap->rmtp) {
314 		sysmsg->lmsg.ms_error =
315 		    copyout(&sysmsg->rmt, uap->rmtp, sizeof(sysmsg->rmt));
316 	}
317 }
318 
319 /* ARGSUSED */
320 int
321 gettimeofday(struct gettimeofday_args *uap)
322 {
323 	struct timeval atv;
324 	int error = 0;
325 
326 	if (uap->tp) {
327 		microtime(&atv);
328 		if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
329 		    sizeof (atv))))
330 			return (error);
331 	}
332 	if (uap->tzp)
333 		error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
334 		    sizeof (tz));
335 	return (error);
336 }
337 
338 /* ARGSUSED */
339 int
340 settimeofday(struct settimeofday_args *uap)
341 {
342 	struct thread *td = curthread;
343 	struct timeval atv;
344 	struct timezone atz;
345 	int error;
346 
347 	if ((error = suser(td)))
348 		return (error);
349 	/* Verify all parameters before changing time. */
350 	if (uap->tv) {
351 		if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
352 		    sizeof(atv))))
353 			return (error);
354 		if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
355 			return (EINVAL);
356 	}
357 	if (uap->tzp &&
358 	    (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
359 		return (error);
360 	if (uap->tv && (error = settime(&atv)))
361 		return (error);
362 	if (uap->tzp)
363 		tz = atz;
364 	return (0);
365 }
366 
367 int	tickdelta;			/* current clock skew, us. per tick */
368 long	timedelta;			/* unapplied time correction, us. */
369 static long	bigadj = 1000000;	/* use 10x skew above bigadj us. */
370 
371 /* ARGSUSED */
372 int
373 adjtime(struct adjtime_args *uap)
374 {
375 	struct thread *td = curthread;
376 	struct timeval atv;
377 	long ndelta, ntickdelta, odelta;
378 	int s, error;
379 
380 	if ((error = suser(td)))
381 		return (error);
382 	if ((error =
383 	    copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
384 		return (error);
385 
386 	/*
387 	 * Compute the total correction and the rate at which to apply it.
388 	 * Round the adjustment down to a whole multiple of the per-tick
389 	 * delta, so that after some number of incremental changes in
390 	 * hardclock(), tickdelta will become zero, lest the correction
391 	 * overshoot and start taking us away from the desired final time.
392 	 */
393 	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
394 	if (ndelta > bigadj || ndelta < -bigadj)
395 		ntickdelta = 10 * tickadj;
396 	else
397 		ntickdelta = tickadj;
398 	if (ndelta % ntickdelta)
399 		ndelta = ndelta / ntickdelta * ntickdelta;
400 
401 	/*
402 	 * To make hardclock()'s job easier, make the per-tick delta negative
403 	 * if we want time to run slower; then hardclock can simply compute
404 	 * tick + tickdelta, and subtract tickdelta from timedelta.
405 	 */
406 	if (ndelta < 0)
407 		ntickdelta = -ntickdelta;
408 	s = splclock();
409 	odelta = timedelta;
410 	timedelta = ndelta;
411 	tickdelta = ntickdelta;
412 	splx(s);
413 
414 	if (uap->olddelta) {
415 		atv.tv_sec = odelta / 1000000;
416 		atv.tv_usec = odelta % 1000000;
417 		(void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
418 		    sizeof(struct timeval));
419 	}
420 	return (0);
421 }
422 
423 /*
424  * Get value of an interval timer.  The process virtual and
425  * profiling virtual time timers are kept in the p_stats area, since
426  * they can be swapped out.  These are kept internally in the
427  * way they are specified externally: in time until they expire.
428  *
429  * The real time interval timer is kept in the process table slot
430  * for the process, and its value (it_value) is kept as an
431  * absolute time rather than as a delta, so that it is easy to keep
432  * periodic real-time signals from drifting.
433  *
434  * Virtual time timers are processed in the hardclock() routine of
435  * kern_clock.c.  The real time timer is processed by a timeout
436  * routine, called from the softclock() routine.  Since a callout
437  * may be delayed in real time due to interrupt processing in the system,
438  * it is possible for the real time timeout routine (realitexpire, given below),
439  * to be delayed in real time past when it is supposed to occur.  It
440  * does not suffice, therefore, to reload the real timer .it_value from the
441  * real time timers .it_interval.  Rather, we compute the next time in
442  * absolute time the timer should go off.
443  */
444 /* ARGSUSED */
445 int
446 getitimer(struct getitimer_args *uap)
447 {
448 	struct proc *p = curproc;
449 	struct timeval ctv;
450 	struct itimerval aitv;
451 	int s;
452 
453 	if (uap->which > ITIMER_PROF)
454 		return (EINVAL);
455 	s = splclock(); /* XXX still needed ? */
456 	if (uap->which == ITIMER_REAL) {
457 		/*
458 		 * Convert from absolute to relative time in .it_value
459 		 * part of real time timer.  If time for real time timer
460 		 * has passed return 0, else return difference between
461 		 * current time and time for the timer to go off.
462 		 */
463 		aitv = p->p_realtimer;
464 		if (timevalisset(&aitv.it_value)) {
465 			getmicrouptime(&ctv);
466 			if (timevalcmp(&aitv.it_value, &ctv, <))
467 				timevalclear(&aitv.it_value);
468 			else
469 				timevalsub(&aitv.it_value, &ctv);
470 		}
471 	} else
472 		aitv = p->p_stats->p_timer[uap->which];
473 	splx(s);
474 	return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
475 	    sizeof (struct itimerval)));
476 }
477 
478 /* ARGSUSED */
479 int
480 setitimer(struct setitimer_args *uap)
481 {
482 	struct itimerval aitv;
483 	struct timeval ctv;
484 	struct itimerval *itvp;
485 	struct proc *p = curproc;
486 	int s, error;
487 
488 	if (uap->which > ITIMER_PROF)
489 		return (EINVAL);
490 	itvp = uap->itv;
491 	if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
492 	    sizeof(struct itimerval))))
493 		return (error);
494 	if ((uap->itv = uap->oitv) &&
495 	    (error = getitimer((struct getitimer_args *)uap)))
496 		return (error);
497 	if (itvp == 0)
498 		return (0);
499 	if (itimerfix(&aitv.it_value))
500 		return (EINVAL);
501 	if (!timevalisset(&aitv.it_value))
502 		timevalclear(&aitv.it_interval);
503 	else if (itimerfix(&aitv.it_interval))
504 		return (EINVAL);
505 	s = splclock(); /* XXX: still needed ? */
506 	if (uap->which == ITIMER_REAL) {
507 		if (timevalisset(&p->p_realtimer.it_value))
508 			untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
509 		if (timevalisset(&aitv.it_value))
510 			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
511 						tvtohz(&aitv.it_value));
512 		getmicrouptime(&ctv);
513 		timevaladd(&aitv.it_value, &ctv);
514 		p->p_realtimer = aitv;
515 	} else
516 		p->p_stats->p_timer[uap->which] = aitv;
517 	splx(s);
518 	return (0);
519 }
520 
521 /*
522  * Real interval timer expired:
523  * send process whose timer expired an alarm signal.
524  * If time is not set up to reload, then just return.
525  * Else compute next time timer should go off which is > current time.
526  * This is where delay in processing this timeout causes multiple
527  * SIGALRM calls to be compressed into one.
528  * tvtohz() always adds 1 to allow for the time until the next clock
529  * interrupt being strictly less than 1 clock tick, but we don't want
530  * that here since we want to appear to be in sync with the clock
531  * interrupt even when we're delayed.
532  */
533 void
534 realitexpire(arg)
535 	void *arg;
536 {
537 	struct proc *p;
538 	struct timeval ctv, ntv;
539 	int s;
540 
541 	p = (struct proc *)arg;
542 	psignal(p, SIGALRM);
543 	if (!timevalisset(&p->p_realtimer.it_interval)) {
544 		timevalclear(&p->p_realtimer.it_value);
545 		return;
546 	}
547 	for (;;) {
548 		s = splclock(); /* XXX: still neeeded ? */
549 		timevaladd(&p->p_realtimer.it_value,
550 		    &p->p_realtimer.it_interval);
551 		getmicrouptime(&ctv);
552 		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
553 			ntv = p->p_realtimer.it_value;
554 			timevalsub(&ntv, &ctv);
555 			p->p_ithandle = timeout(realitexpire, (caddr_t)p,
556 			    tvtohz(&ntv) - 1);
557 			splx(s);
558 			return;
559 		}
560 		splx(s);
561 	}
562 }
563 
564 /*
565  * Check that a proposed value to load into the .it_value or
566  * .it_interval part of an interval timer is acceptable, and
567  * fix it to have at least minimal value (i.e. if it is less
568  * than the resolution of the clock, round it up.)
569  */
570 int
571 itimerfix(tv)
572 	struct timeval *tv;
573 {
574 
575 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
576 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
577 		return (EINVAL);
578 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
579 		tv->tv_usec = tick;
580 	return (0);
581 }
582 
583 /*
584  * Decrement an interval timer by a specified number
585  * of microseconds, which must be less than a second,
586  * i.e. < 1000000.  If the timer expires, then reload
587  * it.  In this case, carry over (usec - old value) to
588  * reduce the value reloaded into the timer so that
589  * the timer does not drift.  This routine assumes
590  * that it is called in a context where the timers
591  * on which it is operating cannot change in value.
592  */
593 int
594 itimerdecr(itp, usec)
595 	struct itimerval *itp;
596 	int usec;
597 {
598 
599 	if (itp->it_value.tv_usec < usec) {
600 		if (itp->it_value.tv_sec == 0) {
601 			/* expired, and already in next interval */
602 			usec -= itp->it_value.tv_usec;
603 			goto expire;
604 		}
605 		itp->it_value.tv_usec += 1000000;
606 		itp->it_value.tv_sec--;
607 	}
608 	itp->it_value.tv_usec -= usec;
609 	usec = 0;
610 	if (timevalisset(&itp->it_value))
611 		return (1);
612 	/* expired, exactly at end of interval */
613 expire:
614 	if (timevalisset(&itp->it_interval)) {
615 		itp->it_value = itp->it_interval;
616 		itp->it_value.tv_usec -= usec;
617 		if (itp->it_value.tv_usec < 0) {
618 			itp->it_value.tv_usec += 1000000;
619 			itp->it_value.tv_sec--;
620 		}
621 	} else
622 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
623 	return (0);
624 }
625 
626 /*
627  * Add and subtract routines for timevals.
628  * N.B.: subtract routine doesn't deal with
629  * results which are before the beginning,
630  * it just gets very confused in this case.
631  * Caveat emptor.
632  */
633 void
634 timevaladd(t1, t2)
635 	struct timeval *t1, *t2;
636 {
637 
638 	t1->tv_sec += t2->tv_sec;
639 	t1->tv_usec += t2->tv_usec;
640 	timevalfix(t1);
641 }
642 
643 void
644 timevalsub(t1, t2)
645 	struct timeval *t1, *t2;
646 {
647 
648 	t1->tv_sec -= t2->tv_sec;
649 	t1->tv_usec -= t2->tv_usec;
650 	timevalfix(t1);
651 }
652 
653 static void
654 timevalfix(t1)
655 	struct timeval *t1;
656 {
657 
658 	if (t1->tv_usec < 0) {
659 		t1->tv_sec--;
660 		t1->tv_usec += 1000000;
661 	}
662 	if (t1->tv_usec >= 1000000) {
663 		t1->tv_sec++;
664 		t1->tv_usec -= 1000000;
665 	}
666 }
667 
668 /*
669  * ratecheck(): simple time-based rate-limit checking.
670  */
671 int
672 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
673 {
674 	struct timeval tv, delta;
675 	int rv = 0;
676 
677 	getmicrouptime(&tv);		/* NB: 10ms precision */
678 	delta = tv;
679 	timevalsub(&delta, lasttime);
680 
681 	/*
682 	 * check for 0,0 is so that the message will be seen at least once,
683 	 * even if interval is huge.
684 	 */
685 	if (timevalcmp(&delta, mininterval, >=) ||
686 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
687 		*lasttime = tv;
688 		rv = 1;
689 	}
690 
691 	return (rv);
692 }
693 
694 /*
695  * ppsratecheck(): packets (or events) per second limitation.
696  *
697  * Return 0 if the limit is to be enforced (e.g. the caller
698  * should drop a packet because of the rate limitation).
699  *
700  * maxpps of 0 always causes zero to be returned.  maxpps of -1
701  * always causes 1 to be returned; this effectively defeats rate
702  * limiting.
703  *
704  * Note that we maintain the struct timeval for compatibility
705  * with other bsd systems.  We reuse the storage and just monitor
706  * clock ticks for minimal overhead.
707  */
708 int
709 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
710 {
711 	int now;
712 
713 	/*
714 	 * Reset the last time and counter if this is the first call
715 	 * or more than a second has passed since the last update of
716 	 * lasttime.
717 	 */
718 	now = ticks;
719 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
720 		lasttime->tv_sec = now;
721 		*curpps = 1;
722 		return (maxpps != 0);
723 	} else {
724 		(*curpps)++;		/* NB: ignore potential overflow */
725 		return (maxpps < 0 || *curpps < maxpps);
726 	}
727 }
728 
729