xref: /openbsd-src/sys/kern/kern_time.c (revision e5157e49389faebcb42b7237d55fbf096d9c2523)
1 /*	$OpenBSD: kern_time.c,v 1.88 2014/05/15 04:36:33 guenther Exp $	*/
2 /*	$NetBSD: kern_time.c,v 1.20 1996/02/18 11:57:06 fvdl Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
33  */
34 
35 #include <sys/param.h>
36 #include <sys/resourcevar.h>
37 #include <sys/kernel.h>
38 #include <sys/systm.h>
39 #include <sys/proc.h>
40 #include <sys/ktrace.h>
41 #include <sys/vnode.h>
42 #include <sys/signalvar.h>
43 #include <sys/timetc.h>
44 
45 #include <sys/mount.h>
46 #include <sys/syscallargs.h>
47 
48 
49 int64_t adjtimedelta;		/* unapplied time correction (microseconds) */
50 
51 /*
52  * Time of day and interval timer support.
53  *
54  * These routines provide the kernel entry points to get and set
55  * the time-of-day and per-process interval timers.  Subroutines
56  * here provide support for adding and subtracting timeval structures
57  * and decrementing interval timers, optionally reloading the interval
58  * timers when they expire.
59  */
60 
61 /* This function is used by clock_settime and settimeofday */
62 int
63 settime(struct timespec *ts)
64 {
65 	struct timespec now;
66 
67 	/*
68 	 * Adjtime in progress is meaningless or harmful after
69 	 * setting the clock. Cancel adjtime and then set new time.
70 	 */
71 	adjtimedelta = 0;
72 
73 	/*
74 	 * Don't allow the time to be set forward so far it will wrap
75 	 * and become negative, thus allowing an attacker to bypass
76 	 * the next check below.  The cutoff is 1 year before rollover
77 	 * occurs, so even if the attacker uses adjtime(2) to move
78 	 * the time past the cutoff, it will take a very long time
79 	 * to get to the wrap point.
80 	 *
81 	 * XXX: we check against UINT_MAX until we can figure out
82 	 *	how to deal with the hardware RTCs.
83 	 */
84 	if (ts->tv_sec > UINT_MAX - 365*24*60*60) {
85 		printf("denied attempt to set clock forward to %lld\n",
86 		    (long long)ts->tv_sec);
87 		return (EPERM);
88 	}
89 	/*
90 	 * If the system is secure, we do not allow the time to be
91 	 * set to an earlier value (it may be slowed using adjtime,
92 	 * but not set back). This feature prevent interlopers from
93 	 * setting arbitrary time stamps on files.
94 	 */
95 	nanotime(&now);
96 	if (securelevel > 1 && timespeccmp(ts, &now, <)) {
97 		printf("denied attempt to set clock back %lld seconds\n",
98 		    (long long)now.tv_sec - ts->tv_sec);
99 		return (EPERM);
100 	}
101 
102 	tc_setrealtimeclock(ts);
103 	resettodr();
104 
105 	return (0);
106 }
107 
108 int
109 clock_gettime(struct proc *p, clockid_t clock_id, struct timespec *tp)
110 {
111 	struct bintime bt;
112 	struct proc *q;
113 
114 	switch (clock_id) {
115 	case CLOCK_REALTIME:
116 		nanotime(tp);
117 		break;
118 	case CLOCK_UPTIME:
119 		binuptime(&bt);
120 		bintime_sub(&bt, &naptime);
121 		bintime2timespec(&bt, tp);
122 		break;
123 	case CLOCK_MONOTONIC:
124 		nanouptime(tp);
125 		break;
126 	case CLOCK_PROCESS_CPUTIME_ID:
127 		nanouptime(tp);
128 		timespecsub(tp, &curcpu()->ci_schedstate.spc_runtime, tp);
129 		timespecadd(tp, &p->p_p->ps_tu.tu_runtime, tp);
130 		timespecadd(tp, &p->p_rtime, tp);
131 		break;
132 	case CLOCK_THREAD_CPUTIME_ID:
133 		nanouptime(tp);
134 		timespecsub(tp, &curcpu()->ci_schedstate.spc_runtime, tp);
135 		timespecadd(tp, &p->p_tu.tu_runtime, tp);
136 		timespecadd(tp, &p->p_rtime, tp);
137 		break;
138 	default:
139 		/* check for clock from pthread_getcpuclockid() */
140 		if (__CLOCK_TYPE(clock_id) == CLOCK_THREAD_CPUTIME_ID) {
141 			q = pfind(__CLOCK_PTID(clock_id) - THREAD_PID_OFFSET);
142 			if (q == NULL || q->p_p != p->p_p)
143 				return (ESRCH);
144 			*tp = q->p_tu.tu_runtime;
145 		} else
146 			return (EINVAL);
147 	}
148 	return (0);
149 }
150 
151 /* ARGSUSED */
152 int
153 sys_clock_gettime(struct proc *p, void *v, register_t *retval)
154 {
155 	struct sys_clock_gettime_args /* {
156 		syscallarg(clockid_t) clock_id;
157 		syscallarg(struct timespec *) tp;
158 	} */ *uap = v;
159 	struct timespec ats;
160 	int error;
161 
162 	memset(&ats, 0, sizeof(ats));
163 	if ((error = clock_gettime(p, SCARG(uap, clock_id), &ats)) != 0)
164 		return (error);
165 
166 	error = copyout(&ats, SCARG(uap, tp), sizeof(ats));
167 #ifdef KTRACE
168 	if (error == 0 && KTRPOINT(p, KTR_STRUCT)) {
169 		KERNEL_LOCK();
170 		ktrabstimespec(p, &ats);
171 		KERNEL_UNLOCK();
172 	}
173 #endif
174 	return (error);
175 }
176 
177 /* ARGSUSED */
178 int
179 sys_clock_settime(struct proc *p, void *v, register_t *retval)
180 {
181 	struct sys_clock_settime_args /* {
182 		syscallarg(clockid_t) clock_id;
183 		syscallarg(const struct timespec *) tp;
184 	} */ *uap = v;
185 	struct timespec ats;
186 	clockid_t clock_id;
187 	int error;
188 
189 	if ((error = suser(p, 0)) != 0)
190 		return (error);
191 
192 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
193 		return (error);
194 
195 	clock_id = SCARG(uap, clock_id);
196 	switch (clock_id) {
197 	case CLOCK_REALTIME:
198 		if ((error = settime(&ats)) != 0)
199 			return (error);
200 		break;
201 	default:	/* Other clocks are read-only */
202 		return (EINVAL);
203 	}
204 
205 	return (0);
206 }
207 
208 int
209 sys_clock_getres(struct proc *p, void *v, register_t *retval)
210 {
211 	struct sys_clock_getres_args /* {
212 		syscallarg(clockid_t) clock_id;
213 		syscallarg(struct timespec *) tp;
214 	} */ *uap = v;
215 	clockid_t clock_id;
216 	struct timespec ts;
217 	struct proc *q;
218 	int error = 0;
219 
220 	memset(&ts, 0, sizeof(ts));
221 	clock_id = SCARG(uap, clock_id);
222 	switch (clock_id) {
223 	case CLOCK_REALTIME:
224 	case CLOCK_MONOTONIC:
225 	case CLOCK_UPTIME:
226 	case CLOCK_PROCESS_CPUTIME_ID:
227 	case CLOCK_THREAD_CPUTIME_ID:
228 		ts.tv_sec = 0;
229 		ts.tv_nsec = 1000000000 / hz;
230 		break;
231 	default:
232 		/* check for clock from pthread_getcpuclockid() */
233 		if (__CLOCK_TYPE(clock_id) == CLOCK_THREAD_CPUTIME_ID) {
234 			q = pfind(__CLOCK_PTID(clock_id) - THREAD_PID_OFFSET);
235 			if (q == NULL || q->p_p != p->p_p)
236 				return (ESRCH);
237 			ts.tv_sec = 0;
238 			ts.tv_nsec = 1000000000 / hz;
239 		} else
240 			return (EINVAL);
241 	}
242 
243 	if (SCARG(uap, tp)) {
244 		error = copyout(&ts, SCARG(uap, tp), sizeof (ts));
245 #ifdef KTRACE
246 		if (error == 0 && KTRPOINT(p, KTR_STRUCT)) {
247 			KERNEL_LOCK();
248 			ktrreltimespec(p, &ts);
249 			KERNEL_UNLOCK();
250 		}
251 #endif
252 	}
253 
254 	return error;
255 }
256 
257 /* ARGSUSED */
258 int
259 sys_nanosleep(struct proc *p, void *v, register_t *retval)
260 {
261 	static int nanowait;
262 	struct sys_nanosleep_args/* {
263 		syscallarg(const struct timespec *) rqtp;
264 		syscallarg(struct timespec *) rmtp;
265 	} */ *uap = v;
266 	struct timespec rqt, rmt;
267 	struct timespec sts, ets;
268 	struct timespec *rmtp;
269 	struct timeval tv;
270 	int error, error1;
271 
272 	rmtp = SCARG(uap, rmtp);
273 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
274 	if (error)
275 		return (error);
276 #ifdef KTRACE
277         if (KTRPOINT(p, KTR_STRUCT)) {
278 		KERNEL_LOCK();
279 		ktrreltimespec(p, &rqt);
280 		KERNEL_UNLOCK();
281 	}
282 #endif
283 
284 	TIMESPEC_TO_TIMEVAL(&tv, &rqt);
285 	if (itimerfix(&tv))
286 		return (EINVAL);
287 
288 	if (rmtp)
289 		getnanouptime(&sts);
290 
291 	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep",
292 	    MAX(1, tvtohz(&tv)));
293 	if (error == ERESTART)
294 		error = EINTR;
295 	if (error == EWOULDBLOCK)
296 		error = 0;
297 
298 	if (rmtp) {
299 		getnanouptime(&ets);
300 
301 		memset(&rmt, 0, sizeof(rmt));
302 		timespecsub(&ets, &sts, &sts);
303 		timespecsub(&rqt, &sts, &rmt);
304 
305 		if (rmt.tv_sec < 0)
306 			timespecclear(&rmt);
307 
308 		error1 = copyout(&rmt, rmtp, sizeof(rmt));
309 		if (error1 != 0)
310 			error = error1;
311 #ifdef KTRACE
312 		if (error1 == 0 && KTRPOINT(p, KTR_STRUCT)) {
313 			KERNEL_LOCK();
314 			ktrreltimespec(p, &rmt);
315 			KERNEL_UNLOCK();
316 		}
317 #endif
318 	}
319 
320 	return error;
321 }
322 
323 /* ARGSUSED */
324 int
325 sys_gettimeofday(struct proc *p, void *v, register_t *retval)
326 {
327 	struct sys_gettimeofday_args /* {
328 		syscallarg(struct timeval *) tp;
329 		syscallarg(struct timezone *) tzp;
330 	} */ *uap = v;
331 	struct timeval atv;
332 	struct timeval *tp;
333 	struct timezone *tzp;
334 	int error = 0;
335 
336 	tp = SCARG(uap, tp);
337 	tzp = SCARG(uap, tzp);
338 
339 	if (tp) {
340 		memset(&atv, 0, sizeof(atv));
341 		microtime(&atv);
342 		if ((error = copyout(&atv, tp, sizeof (atv))))
343 			return (error);
344 #ifdef KTRACE
345 		if (KTRPOINT(p, KTR_STRUCT)) {
346 			KERNEL_LOCK();
347 			ktrabstimeval(p, &atv);
348 			KERNEL_UNLOCK();
349 		}
350 #endif
351 	}
352 	if (tzp)
353 		error = copyout(&tz, tzp, sizeof (tz));
354 	return (error);
355 }
356 
357 /* ARGSUSED */
358 int
359 sys_settimeofday(struct proc *p, void *v, register_t *retval)
360 {
361 	struct sys_settimeofday_args /* {
362 		syscallarg(const struct timeval *) tv;
363 		syscallarg(const struct timezone *) tzp;
364 	} */ *uap = v;
365 	struct timezone atz;
366 	struct timeval atv;
367 	const struct timeval *tv;
368 	const struct timezone *tzp;
369 	int error;
370 
371 	tv = SCARG(uap, tv);
372 	tzp = SCARG(uap, tzp);
373 
374 	if ((error = suser(p, 0)))
375 		return (error);
376 	/* Verify all parameters before changing time. */
377 	if (tv && (error = copyin(tv, &atv, sizeof(atv))))
378 		return (error);
379 	if (tzp && (error = copyin(tzp, &atz, sizeof(atz))))
380 		return (error);
381 	if (tv) {
382 		struct timespec ts;
383 
384 		TIMEVAL_TO_TIMESPEC(&atv, &ts);
385 		if ((error = settime(&ts)) != 0)
386 			return (error);
387 	}
388 	if (tzp)
389 		tz = atz;
390 	return (0);
391 }
392 
393 /* ARGSUSED */
394 int
395 sys_adjfreq(struct proc *p, void *v, register_t *retval)
396 {
397 	struct sys_adjfreq_args /* {
398 		syscallarg(const int64_t *) freq;
399 		syscallarg(int64_t *) oldfreq;
400 	} */ *uap = v;
401 	int error;
402 	int64_t f;
403 	const int64_t *freq = SCARG(uap, freq);
404 	int64_t *oldfreq = SCARG(uap, oldfreq);
405 	if (oldfreq) {
406 		if ((error = tc_adjfreq(&f, NULL)))
407 			return (error);
408 		if ((error = copyout(&f, oldfreq, sizeof(f))))
409 			return (error);
410 	}
411 	if (freq) {
412 		if ((error = suser(p, 0)))
413 			return (error);
414 		if ((error = copyin(freq, &f, sizeof(f))))
415 			return (error);
416 		if ((error = tc_adjfreq(NULL, &f)))
417 			return (error);
418 	}
419 	return (0);
420 }
421 
422 /* ARGSUSED */
423 int
424 sys_adjtime(struct proc *p, void *v, register_t *retval)
425 {
426 	struct sys_adjtime_args /* {
427 		syscallarg(const struct timeval *) delta;
428 		syscallarg(struct timeval *) olddelta;
429 	} */ *uap = v;
430 	const struct timeval *delta = SCARG(uap, delta);
431 	struct timeval *olddelta = SCARG(uap, olddelta);
432 	struct timeval atv;
433 	int error;
434 
435 	if (olddelta) {
436 		memset(&atv, 0, sizeof(atv));
437 		atv.tv_sec = adjtimedelta / 1000000;
438 		atv.tv_usec = adjtimedelta % 1000000;
439 		if (atv.tv_usec < 0) {
440 			atv.tv_usec += 1000000;
441 			atv.tv_sec--;
442 		}
443 
444 		if ((error = copyout(&atv, olddelta, sizeof(struct timeval))))
445 			return (error);
446 	}
447 
448 	if (delta) {
449 		if ((error = suser(p, 0)))
450 			return (error);
451 
452 		if ((error = copyin(delta, &atv, sizeof(struct timeval))))
453 			return (error);
454 
455 		/* XXX Check for overflow? */
456 		adjtimedelta = (int64_t)atv.tv_sec * 1000000 + atv.tv_usec;
457 	}
458 
459 	return (0);
460 }
461 
462 
463 /*
464  * Get value of an interval timer.  The process virtual and
465  * profiling virtual time timers are kept internally in the
466  * way they are specified externally: in time until they expire.
467  *
468  * The real time interval timer's it_value, in contast, is kept as an
469  * absolute time rather than as a delta, so that it is easy to keep
470  * periodic real-time signals from drifting.
471  *
472  * Virtual time timers are processed in the hardclock() routine of
473  * kern_clock.c.  The real time timer is processed by a timeout
474  * routine, called from the softclock() routine.  Since a callout
475  * may be delayed in real time due to interrupt processing in the system,
476  * it is possible for the real time timeout routine (realitexpire, given below),
477  * to be delayed in real time past when it is supposed to occur.  It
478  * does not suffice, therefore, to reload the real timer .it_value from the
479  * real time timers .it_interval.  Rather, we compute the next time in
480  * absolute time the timer should go off.
481  */
482 /* ARGSUSED */
483 int
484 sys_getitimer(struct proc *p, void *v, register_t *retval)
485 {
486 	struct sys_getitimer_args /* {
487 		syscallarg(int) which;
488 		syscallarg(struct itimerval *) itv;
489 	} */ *uap = v;
490 	struct itimerval aitv;
491 	int s;
492 	int which;
493 
494 	which = SCARG(uap, which);
495 
496 	if (which < ITIMER_REAL || which > ITIMER_PROF)
497 		return (EINVAL);
498 	memset(&aitv, 0, sizeof(aitv));
499 	s = splclock();
500 	aitv.it_interval.tv_sec  = p->p_p->ps_timer[which].it_interval.tv_sec;
501 	aitv.it_interval.tv_usec = p->p_p->ps_timer[which].it_interval.tv_usec;
502 	aitv.it_value.tv_sec     = p->p_p->ps_timer[which].it_value.tv_sec;
503 	aitv.it_value.tv_usec    = p->p_p->ps_timer[which].it_value.tv_usec;
504 
505 	if (which == ITIMER_REAL) {
506 		struct timeval now;
507 
508 		getmicrouptime(&now);
509 		/*
510 		 * Convert from absolute to relative time in .it_value
511 		 * part of real time timer.  If time for real time timer
512 		 * has passed return 0, else return difference between
513 		 * current time and time for the timer to go off.
514 		 */
515 		if (timerisset(&aitv.it_value)) {
516 			if (timercmp(&aitv.it_value, &now, <))
517 				timerclear(&aitv.it_value);
518 			else
519 				timersub(&aitv.it_value, &now,
520 				    &aitv.it_value);
521 		}
522 	}
523 	splx(s);
524 	return (copyout(&aitv, SCARG(uap, itv), sizeof (struct itimerval)));
525 }
526 
527 /* ARGSUSED */
528 int
529 sys_setitimer(struct proc *p, void *v, register_t *retval)
530 {
531 	struct sys_setitimer_args /* {
532 		syscallarg(int) which;
533 		syscallarg(const struct itimerval *) itv;
534 		syscallarg(struct itimerval *) oitv;
535 	} */ *uap = v;
536 	struct sys_getitimer_args getargs;
537 	struct itimerval aitv;
538 	const struct itimerval *itvp;
539 	struct itimerval *oitv;
540 	struct process *pr = p->p_p;
541 	int error;
542 	int timo;
543 	int which;
544 
545 	which = SCARG(uap, which);
546 	oitv = SCARG(uap, oitv);
547 
548 	if (which < ITIMER_REAL || which > ITIMER_PROF)
549 		return (EINVAL);
550 	itvp = SCARG(uap, itv);
551 	if (itvp && (error = copyin((void *)itvp, (void *)&aitv,
552 	    sizeof(struct itimerval))))
553 		return (error);
554 	if (oitv != NULL) {
555 		SCARG(&getargs, which) = which;
556 		SCARG(&getargs, itv) = oitv;
557 		if ((error = sys_getitimer(p, &getargs, retval)))
558 			return (error);
559 	}
560 	if (itvp == 0)
561 		return (0);
562 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
563 		return (EINVAL);
564 	if (which == ITIMER_REAL) {
565 		struct timeval ctv;
566 
567 		timeout_del(&pr->ps_realit_to);
568 		getmicrouptime(&ctv);
569 		if (timerisset(&aitv.it_value)) {
570 			timo = tvtohz(&aitv.it_value);
571 			timeout_add(&pr->ps_realit_to, timo);
572 			timeradd(&aitv.it_value, &ctv, &aitv.it_value);
573 		}
574 		pr->ps_timer[ITIMER_REAL] = aitv;
575 	} else {
576 		int s;
577 
578 		itimerround(&aitv.it_interval);
579 		s = splclock();
580 		pr->ps_timer[which] = aitv;
581 		splx(s);
582 	}
583 
584 	return (0);
585 }
586 
587 /*
588  * Real interval timer expired:
589  * send process whose timer expired an alarm signal.
590  * If time is not set up to reload, then just return.
591  * Else compute next time timer should go off which is > current time.
592  * This is where delay in processing this timeout causes multiple
593  * SIGALRM calls to be compressed into one.
594  */
595 void
596 realitexpire(void *arg)
597 {
598 	struct process *pr = arg;
599 	struct itimerval *tp = &pr->ps_timer[ITIMER_REAL];
600 
601 	prsignal(pr, SIGALRM);
602 	if (!timerisset(&tp->it_interval)) {
603 		timerclear(&tp->it_value);
604 		return;
605 	}
606 	for (;;) {
607 		struct timeval ctv, ntv;
608 		int timo;
609 
610 		timeradd(&tp->it_value, &tp->it_interval, &tp->it_value);
611 		getmicrouptime(&ctv);
612 		if (timercmp(&tp->it_value, &ctv, >)) {
613 			ntv = tp->it_value;
614 			timersub(&ntv, &ctv, &ntv);
615 			timo = tvtohz(&ntv) - 1;
616 			if (timo <= 0)
617 				timo = 1;
618 			if ((pr->ps_flags & PS_EXITING) == 0)
619 				timeout_add(&pr->ps_realit_to, timo);
620 			return;
621 		}
622 	}
623 }
624 
625 /*
626  * Check that a timespec value is legit
627  */
628 int
629 timespecfix(struct timespec *ts)
630 {
631 	if (ts->tv_sec < 0 || ts->tv_sec > 100000000 ||
632 	    ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
633 		return (EINVAL);
634 	return (0);
635 }
636 
637 /*
638  * Check that a proposed value to load into the .it_value or
639  * .it_interval part of an interval timer is acceptable.
640  */
641 int
642 itimerfix(struct timeval *tv)
643 {
644 
645 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
646 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
647 		return (EINVAL);
648 
649 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
650 		tv->tv_usec = tick;
651 
652 	return (0);
653 }
654 
655 /*
656  * Nonzero timer interval smaller than the resolution of the
657  * system clock are rounded up.
658  */
659 void
660 itimerround(struct timeval *tv)
661 {
662 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
663 		tv->tv_usec = tick;
664 }
665 
666 /*
667  * Decrement an interval timer by a specified number
668  * of microseconds, which must be less than a second,
669  * i.e. < 1000000.  If the timer expires, then reload
670  * it.  In this case, carry over (usec - old value) to
671  * reduce the value reloaded into the timer so that
672  * the timer does not drift.  This routine assumes
673  * that it is called in a context where the timers
674  * on which it is operating cannot change in value.
675  */
676 int
677 itimerdecr(struct itimerval *itp, int usec)
678 {
679 
680 	if (itp->it_value.tv_usec < usec) {
681 		if (itp->it_value.tv_sec == 0) {
682 			/* expired, and already in next interval */
683 			usec -= itp->it_value.tv_usec;
684 			goto expire;
685 		}
686 		itp->it_value.tv_usec += 1000000;
687 		itp->it_value.tv_sec--;
688 	}
689 	itp->it_value.tv_usec -= usec;
690 	usec = 0;
691 	if (timerisset(&itp->it_value))
692 		return (1);
693 	/* expired, exactly at end of interval */
694 expire:
695 	if (timerisset(&itp->it_interval)) {
696 		itp->it_value = itp->it_interval;
697 		itp->it_value.tv_usec -= usec;
698 		if (itp->it_value.tv_usec < 0) {
699 			itp->it_value.tv_usec += 1000000;
700 			itp->it_value.tv_sec--;
701 		}
702 	} else
703 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
704 	return (0);
705 }
706 
707 /*
708  * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
709  * for usage and rationale.
710  */
711 int
712 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
713 {
714 	struct timeval tv, delta;
715 	int rv = 0;
716 
717 	getmicrouptime(&tv);
718 
719 	timersub(&tv, lasttime, &delta);
720 
721 	/*
722 	 * check for 0,0 is so that the message will be seen at least once,
723 	 * even if interval is huge.
724 	 */
725 	if (timercmp(&delta, mininterval, >=) ||
726 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
727 		*lasttime = tv;
728 		rv = 1;
729 	}
730 
731 	return (rv);
732 }
733 
734 /*
735  * ppsratecheck(): packets (or events) per second limitation.
736  */
737 int
738 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
739 {
740 	struct timeval tv, delta;
741 	int rv;
742 
743 	microuptime(&tv);
744 
745 	timersub(&tv, lasttime, &delta);
746 
747 	/*
748 	 * check for 0,0 is so that the message will be seen at least once.
749 	 * if more than one second have passed since the last update of
750 	 * lasttime, reset the counter.
751 	 *
752 	 * we do increment *curpps even in *curpps < maxpps case, as some may
753 	 * try to use *curpps for stat purposes as well.
754 	 */
755 	if (maxpps == 0)
756 		rv = 0;
757 	else if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
758 	    delta.tv_sec >= 1) {
759 		*lasttime = tv;
760 		*curpps = 0;
761 		rv = 1;
762 	} else if (maxpps < 0)
763 		rv = 1;
764 	else if (*curpps < maxpps)
765 		rv = 1;
766 	else
767 		rv = 0;
768 
769 #if 1 /*DIAGNOSTIC?*/
770 	/* be careful about wrap-around */
771 	if (*curpps + 1 > *curpps)
772 		*curpps = *curpps + 1;
773 #else
774 	/*
775 	 * assume that there's not too many calls to this function.
776 	 * not sure if the assumption holds, as it depends on *caller's*
777 	 * behavior, not the behavior of this function.
778 	 * IMHO it is wrong to make assumption on the caller's behavior,
779 	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
780 	 */
781 	*curpps = *curpps + 1;
782 #endif
783 
784 	return (rv);
785 }
786 
787