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