kern_time.c revision 1.148
1/*	$NetBSD: kern_time.c,v 1.148 2008/05/29 15:27:51 joerg Exp $	*/
2
3/*-
4 * Copyright (c) 2000, 2004, 2005, 2007, 2008 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 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32/*
33 * Copyright (c) 1982, 1986, 1989, 1993
34 *	The Regents of the University of California.  All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 *    notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 *    notice, this list of conditions and the following disclaimer in the
43 *    documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the University nor the names of its contributors
45 *    may be used to endorse or promote products derived from this software
46 *    without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
61 */
62
63#include <sys/cdefs.h>
64__KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.148 2008/05/29 15:27:51 joerg Exp $");
65
66#include <sys/param.h>
67#include <sys/resourcevar.h>
68#include <sys/kernel.h>
69#include <sys/systm.h>
70#include <sys/proc.h>
71#include <sys/vnode.h>
72#include <sys/signalvar.h>
73#include <sys/syslog.h>
74#include <sys/timetc.h>
75#include <sys/timex.h>
76#include <sys/kauth.h>
77#include <sys/mount.h>
78#include <sys/syscallargs.h>
79#include <sys/cpu.h>
80
81#include <uvm/uvm_extern.h>
82
83static void	timer_intr(void *);
84static void	itimerfire(struct ptimer *);
85static void	itimerfree(struct ptimers *, int);
86
87kmutex_t	timer_lock;
88
89static void	*timer_sih;
90static TAILQ_HEAD(, ptimer) timer_queue;
91
92POOL_INIT(ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
93    &pool_allocator_nointr, IPL_NONE);
94POOL_INIT(ptimers_pool, sizeof(struct ptimers), 0, 0, 0, "ptimerspl",
95    &pool_allocator_nointr, IPL_NONE);
96
97/*
98 * Initialize timekeeping.
99 */
100void
101time_init(void)
102{
103
104	/* nothing yet */
105}
106
107void
108time_init2(void)
109{
110
111	TAILQ_INIT(&timer_queue);
112	mutex_init(&timer_lock, MUTEX_DEFAULT, IPL_SCHED);
113	timer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
114	    timer_intr, NULL);
115}
116
117/* Time of day and interval timer support.
118 *
119 * These routines provide the kernel entry points to get and set
120 * the time-of-day and per-process interval timers.  Subroutines
121 * here provide support for adding and subtracting timeval structures
122 * and decrementing interval timers, optionally reloading the interval
123 * timers when they expire.
124 */
125
126/* This function is used by clock_settime and settimeofday */
127static int
128settime1(struct proc *p, struct timespec *ts, bool check_kauth)
129{
130	struct timeval delta, tv;
131	struct timeval now;
132	struct timespec ts1;
133	struct bintime btdelta;
134	lwp_t *l;
135	int s;
136
137	TIMESPEC_TO_TIMEVAL(&tv, ts);
138
139	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
140	s = splclock();
141	microtime(&now);
142	timersub(&tv, &now, &delta);
143
144	if (check_kauth && kauth_authorize_system(kauth_cred_get(),
145	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, ts, &delta,
146	    KAUTH_ARG(check_kauth ? false : true)) != 0) {
147		splx(s);
148		return (EPERM);
149	}
150
151#ifdef notyet
152	if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */
153		splx(s);
154		return (EPERM);
155	}
156#endif
157
158	TIMEVAL_TO_TIMESPEC(&tv, &ts1);
159	tc_setclock(&ts1);
160
161	timeradd(&boottime, &delta, &boottime);
162
163	/*
164	 * XXXSMP: There is a short race between setting the time above
165	 * and adjusting LWP's run times.  Fixing this properly means
166	 * pausing all CPUs while we adjust the clock.
167	 */
168	timeval2bintime(&delta, &btdelta);
169	mutex_enter(proc_lock);
170	LIST_FOREACH(l, &alllwp, l_list) {
171		lwp_lock(l);
172		bintime_add(&l->l_stime, &btdelta);
173		lwp_unlock(l);
174	}
175	mutex_exit(proc_lock);
176	resettodr();
177	splx(s);
178
179	return (0);
180}
181
182int
183settime(struct proc *p, struct timespec *ts)
184{
185	return (settime1(p, ts, true));
186}
187
188/* ARGSUSED */
189int
190sys_clock_gettime(struct lwp *l, const struct sys_clock_gettime_args *uap,
191    register_t *retval)
192{
193	/* {
194		syscallarg(clockid_t) clock_id;
195		syscallarg(struct timespec *) tp;
196	} */
197	clockid_t clock_id;
198	struct timespec ats;
199
200	clock_id = SCARG(uap, clock_id);
201	switch (clock_id) {
202	case CLOCK_REALTIME:
203		nanotime(&ats);
204		break;
205	case CLOCK_MONOTONIC:
206		nanouptime(&ats);
207		break;
208	default:
209		return (EINVAL);
210	}
211
212	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
213}
214
215/* ARGSUSED */
216int
217sys_clock_settime(struct lwp *l, const struct sys_clock_settime_args *uap,
218    register_t *retval)
219{
220	/* {
221		syscallarg(clockid_t) clock_id;
222		syscallarg(const struct timespec *) tp;
223	} */
224
225	return clock_settime1(l->l_proc, SCARG(uap, clock_id), SCARG(uap, tp),
226	    true);
227}
228
229
230int
231clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp,
232    bool check_kauth)
233{
234	struct timespec ats;
235	int error;
236
237	if ((error = copyin(tp, &ats, sizeof(ats))) != 0)
238		return (error);
239
240	switch (clock_id) {
241	case CLOCK_REALTIME:
242		if ((error = settime1(p, &ats, check_kauth)) != 0)
243			return (error);
244		break;
245	case CLOCK_MONOTONIC:
246		return (EINVAL);	/* read-only clock */
247	default:
248		return (EINVAL);
249	}
250
251	return 0;
252}
253
254int
255sys_clock_getres(struct lwp *l, const struct sys_clock_getres_args *uap,
256    register_t *retval)
257{
258	/* {
259		syscallarg(clockid_t) clock_id;
260		syscallarg(struct timespec *) tp;
261	} */
262	clockid_t clock_id;
263	struct timespec ts;
264	int error = 0;
265
266	clock_id = SCARG(uap, clock_id);
267	switch (clock_id) {
268	case CLOCK_REALTIME:
269	case CLOCK_MONOTONIC:
270		ts.tv_sec = 0;
271		if (tc_getfrequency() > 1000000000)
272			ts.tv_nsec = 1;
273		else
274			ts.tv_nsec = 1000000000 / tc_getfrequency();
275		break;
276	default:
277		return (EINVAL);
278	}
279
280	if (SCARG(uap, tp))
281		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
282
283	return error;
284}
285
286/* ARGSUSED */
287int
288sys_nanosleep(struct lwp *l, const struct sys_nanosleep_args *uap,
289    register_t *retval)
290{
291	/* {
292		syscallarg(struct timespec *) rqtp;
293		syscallarg(struct timespec *) rmtp;
294	} */
295	struct timespec rmt, rqt;
296	int error, error1;
297
298	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
299	if (error)
300		return (error);
301
302	error = nanosleep1(l, &rqt, SCARG(uap, rmtp) ? &rmt : NULL);
303	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
304		return error;
305
306	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
307	return error1 ? error1 : error;
308}
309
310int
311nanosleep1(struct lwp *l, struct timespec *rqt, struct timespec *rmt)
312{
313	struct timespec rmtstart;
314	int error, timo;
315
316	if (itimespecfix(rqt))
317		return (EINVAL);
318
319	timo = tstohz(rqt);
320	/*
321	 * Avoid inadvertantly sleeping forever
322	 */
323	if (timo == 0)
324		timo = 1;
325	getnanouptime(&rmtstart);
326again:
327	error = kpause("nanoslp", true, timo, NULL);
328	if (rmt != NULL || error == 0) {
329		struct timespec rmtend;
330		struct timespec t0;
331		struct timespec *t;
332
333		getnanouptime(&rmtend);
334		t = (rmt != NULL) ? rmt : &t0;
335		timespecsub(&rmtend, &rmtstart, t);
336		timespecsub(rqt, t, t);
337		if (t->tv_sec < 0)
338			timespecclear(t);
339		if (error == 0) {
340			timo = tstohz(t);
341			if (timo > 0)
342				goto again;
343		}
344	}
345
346	if (error == ERESTART)
347		error = EINTR;
348	if (error == EWOULDBLOCK)
349		error = 0;
350
351	return error;
352}
353
354/* ARGSUSED */
355int
356sys_gettimeofday(struct lwp *l, const struct sys_gettimeofday_args *uap,
357    register_t *retval)
358{
359	/* {
360		syscallarg(struct timeval *) tp;
361		syscallarg(void *) tzp;		really "struct timezone *";
362	} */
363	struct timeval atv;
364	int error = 0;
365	struct timezone tzfake;
366
367	if (SCARG(uap, tp)) {
368		microtime(&atv);
369		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
370		if (error)
371			return (error);
372	}
373	if (SCARG(uap, tzp)) {
374		/*
375		 * NetBSD has no kernel notion of time zone, so we just
376		 * fake up a timezone struct and return it if demanded.
377		 */
378		tzfake.tz_minuteswest = 0;
379		tzfake.tz_dsttime = 0;
380		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
381	}
382	return (error);
383}
384
385/* ARGSUSED */
386int
387sys_settimeofday(struct lwp *l, const struct sys_settimeofday_args *uap,
388    register_t *retval)
389{
390	/* {
391		syscallarg(const struct timeval *) tv;
392		syscallarg(const void *) tzp; really "const struct timezone *";
393	} */
394
395	return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
396}
397
398int
399settimeofday1(const struct timeval *utv, bool userspace,
400    const void *utzp, struct lwp *l, bool check_kauth)
401{
402	struct timeval atv;
403	struct timespec ts;
404	int error;
405
406	/* Verify all parameters before changing time. */
407
408	/*
409	 * NetBSD has no kernel notion of time zone, and only an
410	 * obsolete program would try to set it, so we log a warning.
411	 */
412	if (utzp)
413		log(LOG_WARNING, "pid %d attempted to set the "
414		    "(obsolete) kernel time zone\n", l->l_proc->p_pid);
415
416	if (utv == NULL)
417		return 0;
418
419	if (userspace) {
420		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
421			return error;
422		utv = &atv;
423	}
424
425	TIMEVAL_TO_TIMESPEC(utv, &ts);
426	return settime1(l->l_proc, &ts, check_kauth);
427}
428
429int	time_adjusted;			/* set if an adjustment is made */
430
431/* ARGSUSED */
432int
433sys_adjtime(struct lwp *l, const struct sys_adjtime_args *uap,
434    register_t *retval)
435{
436	/* {
437		syscallarg(const struct timeval *) delta;
438		syscallarg(struct timeval *) olddelta;
439	} */
440	int error;
441
442	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
443	    KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
444		return (error);
445
446	return adjtime1(SCARG(uap, delta), SCARG(uap, olddelta), l->l_proc);
447}
448
449int
450adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
451{
452	struct timeval atv;
453	int error = 0;
454
455	extern int64_t time_adjtime;  /* in kern_ntptime.c */
456
457	if (olddelta) {
458		mutex_spin_enter(&timecounter_lock);
459		atv.tv_sec = time_adjtime / 1000000;
460		atv.tv_usec = time_adjtime % 1000000;
461		mutex_spin_exit(&timecounter_lock);
462		if (atv.tv_usec < 0) {
463			atv.tv_usec += 1000000;
464			atv.tv_sec--;
465		}
466		error = copyout(&atv, olddelta, sizeof(struct timeval));
467		if (error)
468			return (error);
469	}
470
471	if (delta) {
472		error = copyin(delta, &atv, sizeof(struct timeval));
473		if (error)
474			return (error);
475
476		mutex_spin_enter(&timecounter_lock);
477		time_adjtime = (int64_t)atv.tv_sec * 1000000 +
478			atv.tv_usec;
479		if (time_adjtime) {
480			/* We need to save the system time during shutdown */
481			time_adjusted |= 1;
482		}
483		mutex_spin_exit(&timecounter_lock);
484	}
485
486	return error;
487}
488
489/*
490 * Interval timer support. Both the BSD getitimer() family and the POSIX
491 * timer_*() family of routines are supported.
492 *
493 * All timers are kept in an array pointed to by p_timers, which is
494 * allocated on demand - many processes don't use timers at all. The
495 * first three elements in this array are reserved for the BSD timers:
496 * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, and element
497 * 2 is ITIMER_PROF. The rest may be allocated by the timer_create()
498 * syscall.
499 *
500 * Realtime timers are kept in the ptimer structure as an absolute
501 * time; virtual time timers are kept as a linked list of deltas.
502 * Virtual time timers are processed in the hardclock() routine of
503 * kern_clock.c.  The real time timer is processed by a callout
504 * routine, called from the softclock() routine.  Since a callout may
505 * be delayed in real time due to interrupt processing in the system,
506 * it is possible for the real time timeout routine (realtimeexpire,
507 * given below), to be delayed in real time past when it is supposed
508 * to occur.  It does not suffice, therefore, to reload the real timer
509 * .it_value from the real time timers .it_interval.  Rather, we
510 * compute the next time in absolute time the timer should go off.  */
511
512/* Allocate a POSIX realtime timer. */
513int
514sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap,
515    register_t *retval)
516{
517	/* {
518		syscallarg(clockid_t) clock_id;
519		syscallarg(struct sigevent *) evp;
520		syscallarg(timer_t *) timerid;
521	} */
522
523	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
524	    SCARG(uap, evp), copyin, l);
525}
526
527int
528timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
529    copyin_t fetch_event, struct lwp *l)
530{
531	int error;
532	timer_t timerid;
533	struct ptimers *pts;
534	struct ptimer *pt;
535	struct proc *p;
536
537	p = l->l_proc;
538
539	if (id < CLOCK_REALTIME || id > CLOCK_PROF)
540		return (EINVAL);
541
542	if ((pts = p->p_timers) == NULL)
543		pts = timers_alloc(p);
544
545	pt = pool_get(&ptimer_pool, PR_WAITOK);
546	if (evp != NULL) {
547		if (((error =
548		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
549		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
550			(pt->pt_ev.sigev_notify > SIGEV_SA))) {
551			pool_put(&ptimer_pool, pt);
552			return (error ? error : EINVAL);
553		}
554	}
555
556	/* Find a free timer slot, skipping those reserved for setitimer(). */
557	mutex_spin_enter(&timer_lock);
558	for (timerid = 3; timerid < TIMER_MAX; timerid++)
559		if (pts->pts_timers[timerid] == NULL)
560			break;
561	if (timerid == TIMER_MAX) {
562		mutex_spin_exit(&timer_lock);
563		pool_put(&ptimer_pool, pt);
564		return EAGAIN;
565	}
566	if (evp == NULL) {
567		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
568		switch (id) {
569		case CLOCK_REALTIME:
570			pt->pt_ev.sigev_signo = SIGALRM;
571			break;
572		case CLOCK_VIRTUAL:
573			pt->pt_ev.sigev_signo = SIGVTALRM;
574			break;
575		case CLOCK_PROF:
576			pt->pt_ev.sigev_signo = SIGPROF;
577			break;
578		}
579		pt->pt_ev.sigev_value.sival_int = timerid;
580	}
581	pt->pt_info.ksi_signo = pt->pt_ev.sigev_signo;
582	pt->pt_info.ksi_errno = 0;
583	pt->pt_info.ksi_code = 0;
584	pt->pt_info.ksi_pid = p->p_pid;
585	pt->pt_info.ksi_uid = kauth_cred_getuid(l->l_cred);
586	pt->pt_info.ksi_value = pt->pt_ev.sigev_value;
587	pt->pt_type = id;
588	pt->pt_proc = p;
589	pt->pt_overruns = 0;
590	pt->pt_poverruns = 0;
591	pt->pt_entry = timerid;
592	pt->pt_queued = false;
593	pt->pt_active = 0;
594	timerclear(&pt->pt_time.it_value);
595	callout_init(&pt->pt_ch, 0);
596	pts->pts_timers[timerid] = pt;
597	mutex_spin_exit(&timer_lock);
598
599	return copyout(&timerid, tid, sizeof(timerid));
600}
601
602/* Delete a POSIX realtime timer */
603int
604sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
605    register_t *retval)
606{
607	/* {
608		syscallarg(timer_t) timerid;
609	} */
610	struct proc *p = l->l_proc;
611	timer_t timerid;
612	struct ptimers *pts;
613	struct ptimer *pt, *ptn;
614
615	timerid = SCARG(uap, timerid);
616	pts = p->p_timers;
617
618	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
619		return (EINVAL);
620
621	mutex_spin_enter(&timer_lock);
622	if ((pt = pts->pts_timers[timerid]) == NULL) {
623		mutex_spin_exit(&timer_lock);
624		return (EINVAL);
625	}
626	if (pt->pt_active) {
627		ptn = LIST_NEXT(pt, pt_list);
628		LIST_REMOVE(pt, pt_list);
629		for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
630			timeradd(&pt->pt_time.it_value, &ptn->pt_time.it_value,
631			    &ptn->pt_time.it_value);
632		pt->pt_active = 0;
633	}
634	itimerfree(pts, timerid);
635
636	return (0);
637}
638
639/*
640 * Set up the given timer. The value in pt->pt_time.it_value is taken
641 * to be an absolute time for CLOCK_REALTIME timers and a relative
642 * time for virtual timers.
643 * Must be called at splclock().
644 */
645void
646timer_settime(struct ptimer *pt)
647{
648	struct ptimer *ptn, *pptn;
649	struct ptlist *ptl;
650
651	KASSERT(mutex_owned(&timer_lock));
652
653	if (pt->pt_type == CLOCK_REALTIME) {
654		callout_stop(&pt->pt_ch);
655		if (timerisset(&pt->pt_time.it_value)) {
656			/*
657			 * Don't need to check hzto() return value, here.
658			 * callout_reset() does it for us.
659			 */
660			callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
661			    realtimerexpire, pt);
662		}
663	} else {
664		if (pt->pt_active) {
665			ptn = LIST_NEXT(pt, pt_list);
666			LIST_REMOVE(pt, pt_list);
667			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
668				timeradd(&pt->pt_time.it_value,
669				    &ptn->pt_time.it_value,
670				    &ptn->pt_time.it_value);
671		}
672		if (timerisset(&pt->pt_time.it_value)) {
673			if (pt->pt_type == CLOCK_VIRTUAL)
674				ptl = &pt->pt_proc->p_timers->pts_virtual;
675			else
676				ptl = &pt->pt_proc->p_timers->pts_prof;
677
678			for (ptn = LIST_FIRST(ptl), pptn = NULL;
679			     ptn && timercmp(&pt->pt_time.it_value,
680				 &ptn->pt_time.it_value, >);
681			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
682				timersub(&pt->pt_time.it_value,
683				    &ptn->pt_time.it_value,
684				    &pt->pt_time.it_value);
685
686			if (pptn)
687				LIST_INSERT_AFTER(pptn, pt, pt_list);
688			else
689				LIST_INSERT_HEAD(ptl, pt, pt_list);
690
691			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
692				timersub(&ptn->pt_time.it_value,
693				    &pt->pt_time.it_value,
694				    &ptn->pt_time.it_value);
695
696			pt->pt_active = 1;
697		} else
698			pt->pt_active = 0;
699	}
700}
701
702void
703timer_gettime(struct ptimer *pt, struct itimerval *aitv)
704{
705	struct timeval now;
706	struct ptimer *ptn;
707
708	KASSERT(mutex_owned(&timer_lock));
709
710	*aitv = pt->pt_time;
711	if (pt->pt_type == CLOCK_REALTIME) {
712		/*
713		 * Convert from absolute to relative time in .it_value
714		 * part of real time timer.  If time for real time
715		 * timer has passed return 0, else return difference
716		 * between current time and time for the timer to go
717		 * off.
718		 */
719		if (timerisset(&aitv->it_value)) {
720			getmicrotime(&now);
721			if (timercmp(&aitv->it_value, &now, <))
722				timerclear(&aitv->it_value);
723			else
724				timersub(&aitv->it_value, &now,
725				    &aitv->it_value);
726		}
727	} else if (pt->pt_active) {
728		if (pt->pt_type == CLOCK_VIRTUAL)
729			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
730		else
731			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
732		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
733			timeradd(&aitv->it_value,
734			    &ptn->pt_time.it_value, &aitv->it_value);
735		KASSERT(ptn != NULL); /* pt should be findable on the list */
736	} else
737		timerclear(&aitv->it_value);
738}
739
740
741
742/* Set and arm a POSIX realtime timer */
743int
744sys_timer_settime(struct lwp *l, const struct sys_timer_settime_args *uap,
745    register_t *retval)
746{
747	/* {
748		syscallarg(timer_t) timerid;
749		syscallarg(int) flags;
750		syscallarg(const struct itimerspec *) value;
751		syscallarg(struct itimerspec *) ovalue;
752	} */
753	int error;
754	struct itimerspec value, ovalue, *ovp = NULL;
755
756	if ((error = copyin(SCARG(uap, value), &value,
757	    sizeof(struct itimerspec))) != 0)
758		return (error);
759
760	if (SCARG(uap, ovalue))
761		ovp = &ovalue;
762
763	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
764	    SCARG(uap, flags), l->l_proc)) != 0)
765		return error;
766
767	if (ovp)
768		return copyout(&ovalue, SCARG(uap, ovalue),
769		    sizeof(struct itimerspec));
770	return 0;
771}
772
773int
774dotimer_settime(int timerid, struct itimerspec *value,
775    struct itimerspec *ovalue, int flags, struct proc *p)
776{
777	struct timeval now;
778	struct itimerval val, oval;
779	struct ptimers *pts;
780	struct ptimer *pt;
781
782	pts = p->p_timers;
783
784	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
785		return EINVAL;
786	TIMESPEC_TO_TIMEVAL(&val.it_value, &value->it_value);
787	TIMESPEC_TO_TIMEVAL(&val.it_interval, &value->it_interval);
788	if (itimerfix(&val.it_value) || itimerfix(&val.it_interval))
789		return (EINVAL);
790
791	mutex_spin_enter(&timer_lock);
792	if ((pt = pts->pts_timers[timerid]) == NULL) {
793		mutex_spin_exit(&timer_lock);
794		return (EINVAL);
795	}
796
797	oval = pt->pt_time;
798	pt->pt_time = val;
799
800	/*
801	 * If we've been passed a relative time for a realtime timer,
802	 * convert it to absolute; if an absolute time for a virtual
803	 * timer, convert it to relative and make sure we don't set it
804	 * to zero, which would cancel the timer, or let it go
805	 * negative, which would confuse the comparison tests.
806	 */
807	if (timerisset(&pt->pt_time.it_value)) {
808		if (pt->pt_type == CLOCK_REALTIME) {
809			if ((flags & TIMER_ABSTIME) == 0) {
810				getmicrotime(&now);
811				timeradd(&pt->pt_time.it_value, &now,
812				    &pt->pt_time.it_value);
813			}
814		} else {
815			if ((flags & TIMER_ABSTIME) != 0) {
816				getmicrotime(&now);
817				timersub(&pt->pt_time.it_value, &now,
818				    &pt->pt_time.it_value);
819				if (!timerisset(&pt->pt_time.it_value) ||
820				    pt->pt_time.it_value.tv_sec < 0) {
821					pt->pt_time.it_value.tv_sec = 0;
822					pt->pt_time.it_value.tv_usec = 1;
823				}
824			}
825		}
826	}
827
828	timer_settime(pt);
829	mutex_spin_exit(&timer_lock);
830
831	if (ovalue) {
832		TIMEVAL_TO_TIMESPEC(&oval.it_value, &ovalue->it_value);
833		TIMEVAL_TO_TIMESPEC(&oval.it_interval, &ovalue->it_interval);
834	}
835
836	return (0);
837}
838
839/* Return the time remaining until a POSIX timer fires. */
840int
841sys_timer_gettime(struct lwp *l, const struct sys_timer_gettime_args *uap,
842    register_t *retval)
843{
844	/* {
845		syscallarg(timer_t) timerid;
846		syscallarg(struct itimerspec *) value;
847	} */
848	struct itimerspec its;
849	int error;
850
851	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
852	    &its)) != 0)
853		return error;
854
855	return copyout(&its, SCARG(uap, value), sizeof(its));
856}
857
858int
859dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
860{
861	struct ptimer *pt;
862	struct ptimers *pts;
863	struct itimerval aitv;
864
865	pts = p->p_timers;
866	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
867		return (EINVAL);
868	mutex_spin_enter(&timer_lock);
869	if ((pt = pts->pts_timers[timerid]) == NULL) {
870		mutex_spin_exit(&timer_lock);
871		return (EINVAL);
872	}
873	timer_gettime(pt, &aitv);
874	mutex_spin_exit(&timer_lock);
875
876	TIMEVAL_TO_TIMESPEC(&aitv.it_interval, &its->it_interval);
877	TIMEVAL_TO_TIMESPEC(&aitv.it_value, &its->it_value);
878
879	return 0;
880}
881
882/*
883 * Return the count of the number of times a periodic timer expired
884 * while a notification was already pending. The counter is reset when
885 * a timer expires and a notification can be posted.
886 */
887int
888sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
889    register_t *retval)
890{
891	/* {
892		syscallarg(timer_t) timerid;
893	} */
894	struct proc *p = l->l_proc;
895	struct ptimers *pts;
896	int timerid;
897	struct ptimer *pt;
898
899	timerid = SCARG(uap, timerid);
900
901	pts = p->p_timers;
902	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
903		return (EINVAL);
904	mutex_spin_enter(&timer_lock);
905	if ((pt = pts->pts_timers[timerid]) == NULL) {
906		mutex_spin_exit(&timer_lock);
907		return (EINVAL);
908	}
909	*retval = pt->pt_poverruns;
910	mutex_spin_exit(&timer_lock);
911
912	return (0);
913}
914
915/*
916 * Real interval timer expired:
917 * send process whose timer expired an alarm signal.
918 * If time is not set up to reload, then just return.
919 * Else compute next time timer should go off which is > current time.
920 * This is where delay in processing this timeout causes multiple
921 * SIGALRM calls to be compressed into one.
922 */
923void
924realtimerexpire(void *arg)
925{
926	uint64_t last_val, next_val, interval, now_ms;
927	struct timeval now, next;
928	struct ptimer *pt;
929	int backwards;
930
931	pt = arg;
932
933	mutex_spin_enter(&timer_lock);
934	itimerfire(pt);
935
936	if (!timerisset(&pt->pt_time.it_interval)) {
937		timerclear(&pt->pt_time.it_value);
938		mutex_spin_exit(&timer_lock);
939		return;
940	}
941
942	getmicrotime(&now);
943	backwards = (timercmp(&pt->pt_time.it_value, &now, >));
944	timeradd(&pt->pt_time.it_value, &pt->pt_time.it_interval, &next);
945	/* Handle the easy case of non-overflown timers first. */
946	if (!backwards && timercmp(&next, &now, >)) {
947		pt->pt_time.it_value = next;
948	} else {
949#define TV2MS(x) (((uint64_t)(x)->tv_sec) * 1000000 + (x)->tv_usec)
950		now_ms = TV2MS(&now);
951		last_val = TV2MS(&pt->pt_time.it_value);
952		interval = TV2MS(&pt->pt_time.it_interval);
953#undef TV2MS
954
955		next_val = now_ms +
956		    (now_ms - last_val + interval - 1) % interval;
957
958		if (backwards)
959			next_val += interval;
960		else
961			pt->pt_overruns += (now_ms - last_val) / interval;
962
963		pt->pt_time.it_value.tv_sec = next_val / 1000000;
964		pt->pt_time.it_value.tv_usec = next_val % 1000000;
965	}
966
967	/*
968	 * Don't need to check hzto() return value, here.
969	 * callout_reset() does it for us.
970	 */
971	callout_reset(&pt->pt_ch, hzto(&pt->pt_time.it_value),
972	    realtimerexpire, pt);
973	mutex_spin_exit(&timer_lock);
974}
975
976/* BSD routine to get the value of an interval timer. */
977/* ARGSUSED */
978int
979sys_getitimer(struct lwp *l, const struct sys_getitimer_args *uap,
980    register_t *retval)
981{
982	/* {
983		syscallarg(int) which;
984		syscallarg(struct itimerval *) itv;
985	} */
986	struct proc *p = l->l_proc;
987	struct itimerval aitv;
988	int error;
989
990	error = dogetitimer(p, SCARG(uap, which), &aitv);
991	if (error)
992		return error;
993	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
994}
995
996int
997dogetitimer(struct proc *p, int which, struct itimerval *itvp)
998{
999	struct ptimers *pts;
1000	struct ptimer *pt;
1001
1002	if ((u_int)which > ITIMER_PROF)
1003		return (EINVAL);
1004
1005	mutex_spin_enter(&timer_lock);
1006	pts = p->p_timers;
1007	if (pts == NULL || (pt = pts->pts_timers[which]) == NULL) {
1008		timerclear(&itvp->it_value);
1009		timerclear(&itvp->it_interval);
1010	} else
1011		timer_gettime(pt, itvp);
1012	mutex_spin_exit(&timer_lock);
1013
1014	return 0;
1015}
1016
1017/* BSD routine to set/arm an interval timer. */
1018/* ARGSUSED */
1019int
1020sys_setitimer(struct lwp *l, const struct sys_setitimer_args *uap,
1021    register_t *retval)
1022{
1023	/* {
1024		syscallarg(int) which;
1025		syscallarg(const struct itimerval *) itv;
1026		syscallarg(struct itimerval *) oitv;
1027	} */
1028	struct proc *p = l->l_proc;
1029	int which = SCARG(uap, which);
1030	struct sys_getitimer_args getargs;
1031	const struct itimerval *itvp;
1032	struct itimerval aitv;
1033	int error;
1034
1035	if ((u_int)which > ITIMER_PROF)
1036		return (EINVAL);
1037	itvp = SCARG(uap, itv);
1038	if (itvp &&
1039	    (error = copyin(itvp, &aitv, sizeof(struct itimerval)) != 0))
1040		return (error);
1041	if (SCARG(uap, oitv) != NULL) {
1042		SCARG(&getargs, which) = which;
1043		SCARG(&getargs, itv) = SCARG(uap, oitv);
1044		if ((error = sys_getitimer(l, &getargs, retval)) != 0)
1045			return (error);
1046	}
1047	if (itvp == 0)
1048		return (0);
1049
1050	return dosetitimer(p, which, &aitv);
1051}
1052
1053int
1054dosetitimer(struct proc *p, int which, struct itimerval *itvp)
1055{
1056	struct timeval now;
1057	struct ptimers *pts;
1058	struct ptimer *pt, *spare;
1059
1060	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
1061		return (EINVAL);
1062
1063	/*
1064	 * Don't bother allocating data structures if the process just
1065	 * wants to clear the timer.
1066	 */
1067	spare = NULL;
1068	pts = p->p_timers;
1069 retry:
1070	if (!timerisset(&itvp->it_value) && (pts == NULL ||
1071	    pts->pts_timers[which] == NULL))
1072		return (0);
1073	if (pts == NULL)
1074		pts = timers_alloc(p);
1075	mutex_spin_enter(&timer_lock);
1076	pt = pts->pts_timers[which];
1077	if (pt == NULL) {
1078		if (spare == NULL) {
1079			mutex_spin_exit(&timer_lock);
1080			spare = pool_get(&ptimer_pool, PR_WAITOK);
1081			goto retry;
1082		}
1083		pt = spare;
1084		spare = NULL;
1085		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
1086		pt->pt_ev.sigev_value.sival_int = which;
1087		pt->pt_overruns = 0;
1088		pt->pt_proc = p;
1089		pt->pt_type = which;
1090		pt->pt_entry = which;
1091		pt->pt_active = 0;
1092		pt->pt_queued = false;
1093		callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
1094		switch (which) {
1095		case ITIMER_REAL:
1096			pt->pt_ev.sigev_signo = SIGALRM;
1097			break;
1098		case ITIMER_VIRTUAL:
1099			pt->pt_ev.sigev_signo = SIGVTALRM;
1100			break;
1101		case ITIMER_PROF:
1102			pt->pt_ev.sigev_signo = SIGPROF;
1103			break;
1104		}
1105		pts->pts_timers[which] = pt;
1106	}
1107	pt->pt_time = *itvp;
1108
1109	if ((which == ITIMER_REAL) && timerisset(&pt->pt_time.it_value)) {
1110		/* Convert to absolute time */
1111		/* XXX need to wrap in splclock for timecounters case? */
1112		getmicrotime(&now);
1113		timeradd(&pt->pt_time.it_value, &now, &pt->pt_time.it_value);
1114	}
1115	timer_settime(pt);
1116	mutex_spin_exit(&timer_lock);
1117	if (spare != NULL)
1118		pool_put(&ptimer_pool, spare);
1119
1120	return (0);
1121}
1122
1123/* Utility routines to manage the array of pointers to timers. */
1124struct ptimers *
1125timers_alloc(struct proc *p)
1126{
1127	struct ptimers *pts;
1128	int i;
1129
1130	pts = pool_get(&ptimers_pool, PR_WAITOK);
1131	LIST_INIT(&pts->pts_virtual);
1132	LIST_INIT(&pts->pts_prof);
1133	for (i = 0; i < TIMER_MAX; i++)
1134		pts->pts_timers[i] = NULL;
1135	pts->pts_fired = 0;
1136	mutex_spin_enter(&timer_lock);
1137	if (p->p_timers == NULL) {
1138		p->p_timers = pts;
1139		mutex_spin_exit(&timer_lock);
1140		return pts;
1141	}
1142	mutex_spin_exit(&timer_lock);
1143	pool_put(&ptimers_pool, pts);
1144	return p->p_timers;
1145}
1146
1147/*
1148 * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
1149 * then clean up all timers and free all the data structures. If
1150 * "which" is set to TIMERS_POSIX, only clean up the timers allocated
1151 * by timer_create(), not the BSD setitimer() timers, and only free the
1152 * structure if none of those remain.
1153 */
1154void
1155timers_free(struct proc *p, int which)
1156{
1157	struct ptimers *pts;
1158	struct ptimer *ptn;
1159	struct timeval tv;
1160	int i;
1161
1162	if (p->p_timers == NULL)
1163		return;
1164
1165	pts = p->p_timers;
1166	mutex_spin_enter(&timer_lock);
1167	if (which == TIMERS_ALL) {
1168		p->p_timers = NULL;
1169		i = 0;
1170	} else {
1171		timerclear(&tv);
1172		for (ptn = LIST_FIRST(&pts->pts_virtual);
1173		     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
1174		     ptn = LIST_NEXT(ptn, pt_list))
1175			timeradd(&tv, &ptn->pt_time.it_value, &tv);
1176		LIST_FIRST(&pts->pts_virtual) = NULL;
1177		if (ptn) {
1178			timeradd(&tv, &ptn->pt_time.it_value,
1179			    &ptn->pt_time.it_value);
1180			LIST_INSERT_HEAD(&pts->pts_virtual, ptn, pt_list);
1181		}
1182		timerclear(&tv);
1183		for (ptn = LIST_FIRST(&pts->pts_prof);
1184		     ptn && ptn != pts->pts_timers[ITIMER_PROF];
1185		     ptn = LIST_NEXT(ptn, pt_list))
1186			timeradd(&tv, &ptn->pt_time.it_value, &tv);
1187		LIST_FIRST(&pts->pts_prof) = NULL;
1188		if (ptn) {
1189			timeradd(&tv, &ptn->pt_time.it_value,
1190			    &ptn->pt_time.it_value);
1191			LIST_INSERT_HEAD(&pts->pts_prof, ptn, pt_list);
1192		}
1193		i = 3;
1194	}
1195	for ( ; i < TIMER_MAX; i++) {
1196		if (pts->pts_timers[i] != NULL) {
1197			itimerfree(pts, i);
1198			mutex_spin_enter(&timer_lock);
1199		}
1200	}
1201	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
1202	    pts->pts_timers[2] == NULL) {
1203		p->p_timers = NULL;
1204		mutex_spin_exit(&timer_lock);
1205		pool_put(&ptimers_pool, pts);
1206	} else
1207		mutex_spin_exit(&timer_lock);
1208}
1209
1210static void
1211itimerfree(struct ptimers *pts, int index)
1212{
1213	struct ptimer *pt;
1214
1215	KASSERT(mutex_owned(&timer_lock));
1216
1217	pt = pts->pts_timers[index];
1218	pts->pts_timers[index] = NULL;
1219	if (pt->pt_type == CLOCK_REALTIME)
1220		callout_halt(&pt->pt_ch, &timer_lock);
1221	else if (pt->pt_queued)
1222		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1223	mutex_spin_exit(&timer_lock);
1224	callout_destroy(&pt->pt_ch);
1225	pool_put(&ptimer_pool, pt);
1226}
1227
1228/*
1229 * Decrement an interval timer by a specified number
1230 * of microseconds, which must be less than a second,
1231 * i.e. < 1000000.  If the timer expires, then reload
1232 * it.  In this case, carry over (usec - old value) to
1233 * reduce the value reloaded into the timer so that
1234 * the timer does not drift.  This routine assumes
1235 * that it is called in a context where the timers
1236 * on which it is operating cannot change in value.
1237 */
1238static int
1239itimerdecr(struct ptimer *pt, int usec)
1240{
1241	struct itimerval *itp;
1242
1243	KASSERT(mutex_owned(&timer_lock));
1244
1245	itp = &pt->pt_time;
1246	if (itp->it_value.tv_usec < usec) {
1247		if (itp->it_value.tv_sec == 0) {
1248			/* expired, and already in next interval */
1249			usec -= itp->it_value.tv_usec;
1250			goto expire;
1251		}
1252		itp->it_value.tv_usec += 1000000;
1253		itp->it_value.tv_sec--;
1254	}
1255	itp->it_value.tv_usec -= usec;
1256	usec = 0;
1257	if (timerisset(&itp->it_value))
1258		return (1);
1259	/* expired, exactly at end of interval */
1260expire:
1261	if (timerisset(&itp->it_interval)) {
1262		itp->it_value = itp->it_interval;
1263		itp->it_value.tv_usec -= usec;
1264		if (itp->it_value.tv_usec < 0) {
1265			itp->it_value.tv_usec += 1000000;
1266			itp->it_value.tv_sec--;
1267		}
1268		timer_settime(pt);
1269	} else
1270		itp->it_value.tv_usec = 0;		/* sec is already 0 */
1271	return (0);
1272}
1273
1274static void
1275itimerfire(struct ptimer *pt)
1276{
1277
1278	KASSERT(mutex_owned(&timer_lock));
1279
1280	/*
1281	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
1282	 * XXX Relying on the clock interrupt is stupid.
1283	 */
1284	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL || pt->pt_queued)
1285		return;
1286	TAILQ_INSERT_TAIL(&timer_queue, pt, pt_chain);
1287	pt->pt_queued = true;
1288	softint_schedule(timer_sih);
1289}
1290
1291void
1292timer_tick(lwp_t *l, bool user)
1293{
1294	struct ptimers *pts;
1295	struct ptimer *pt;
1296	proc_t *p;
1297
1298	p = l->l_proc;
1299	if (p->p_timers == NULL)
1300		return;
1301
1302	mutex_spin_enter(&timer_lock);
1303	if ((pts = l->l_proc->p_timers) != NULL) {
1304		/*
1305		 * Run current process's virtual and profile time, as needed.
1306		 */
1307		if (user && (pt = LIST_FIRST(&pts->pts_virtual)) != NULL)
1308			if (itimerdecr(pt, tick) == 0)
1309				itimerfire(pt);
1310		if ((pt = LIST_FIRST(&pts->pts_prof)) != NULL)
1311			if (itimerdecr(pt, tick) == 0)
1312				itimerfire(pt);
1313	}
1314	mutex_spin_exit(&timer_lock);
1315}
1316
1317static void
1318timer_intr(void *cookie)
1319{
1320	ksiginfo_t ksi;
1321	struct ptimer *pt;
1322	proc_t *p;
1323
1324	mutex_spin_enter(&timer_lock);
1325	while ((pt = TAILQ_FIRST(&timer_queue)) != NULL) {
1326		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
1327		KASSERT(pt->pt_queued);
1328		pt->pt_queued = false;
1329
1330		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL)
1331			continue;
1332		p = pt->pt_proc;
1333		if (pt->pt_proc->p_timers == NULL) {
1334			/* Process is dying. */
1335			continue;
1336		}
1337		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
1338			pt->pt_overruns++;
1339			continue;
1340		}
1341
1342		KSI_INIT(&ksi);
1343		ksi.ksi_signo = pt->pt_ev.sigev_signo;
1344		ksi.ksi_code = SI_TIMER;
1345		ksi.ksi_value = pt->pt_ev.sigev_value;
1346		pt->pt_poverruns = pt->pt_overruns;
1347		pt->pt_overruns = 0;
1348		mutex_spin_exit(&timer_lock);
1349
1350		mutex_enter(proc_lock);
1351		kpsignal(p, &ksi, NULL);
1352		mutex_exit(proc_lock);
1353
1354		mutex_spin_enter(&timer_lock);
1355	}
1356	mutex_spin_exit(&timer_lock);
1357}
1358
1359/*
1360 * ratecheck(): simple time-based rate-limit checking.  see ratecheck(9)
1361 * for usage and rationale.
1362 */
1363int
1364ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1365{
1366	struct timeval tv, delta;
1367	int rv = 0;
1368
1369	getmicrouptime(&tv);
1370	timersub(&tv, lasttime, &delta);
1371
1372	/*
1373	 * check for 0,0 is so that the message will be seen at least once,
1374	 * even if interval is huge.
1375	 */
1376	if (timercmp(&delta, mininterval, >=) ||
1377	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1378		*lasttime = tv;
1379		rv = 1;
1380	}
1381
1382	return (rv);
1383}
1384
1385/*
1386 * ppsratecheck(): packets (or events) per second limitation.
1387 */
1388int
1389ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1390{
1391	struct timeval tv, delta;
1392	int rv;
1393
1394	getmicrouptime(&tv);
1395	timersub(&tv, lasttime, &delta);
1396
1397	/*
1398	 * check for 0,0 is so that the message will be seen at least once.
1399	 * if more than one second have passed since the last update of
1400	 * lasttime, reset the counter.
1401	 *
1402	 * we do increment *curpps even in *curpps < maxpps case, as some may
1403	 * try to use *curpps for stat purposes as well.
1404	 */
1405	if ((lasttime->tv_sec == 0 && lasttime->tv_usec == 0) ||
1406	    delta.tv_sec >= 1) {
1407		*lasttime = tv;
1408		*curpps = 0;
1409	}
1410	if (maxpps < 0)
1411		rv = 1;
1412	else if (*curpps < maxpps)
1413		rv = 1;
1414	else
1415		rv = 0;
1416
1417#if 1 /*DIAGNOSTIC?*/
1418	/* be careful about wrap-around */
1419	if (*curpps + 1 > *curpps)
1420		*curpps = *curpps + 1;
1421#else
1422	/*
1423	 * assume that there's not too many calls to this function.
1424	 * not sure if the assumption holds, as it depends on *caller's*
1425	 * behavior, not the behavior of this function.
1426	 * IMHO it is wrong to make assumption on the caller's behavior,
1427	 * so the above #if is #if 1, not #ifdef DIAGNOSTIC.
1428	 */
1429	*curpps = *curpps + 1;
1430#endif
1431
1432	return (rv);
1433}
1434