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