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