xref: /dragonfly/sys/kern/kern_time.c (revision 409b4c59)
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.40 2008/04/02 14:16:16 sephe 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/priv.h>
50 #include <sys/time.h>
51 #include <sys/vnode.h>
52 #include <sys/sysctl.h>
53 #include <sys/kern_syscall.h>
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <sys/msgport2.h>
57 #include <sys/thread2.h>
58 
59 struct timezone tz;
60 
61 /*
62  * Time of day and interval timer support.
63  *
64  * These routines provide the kernel entry points to get and set
65  * the time-of-day and per-process interval timers.  Subroutines
66  * here provide support for adding and subtracting timeval structures
67  * and decrementing interval timers, optionally reloading the interval
68  * timers when they expire.
69  */
70 
71 static int	nanosleep1(struct timespec *rqt, struct timespec *rmt);
72 static int	settime(struct timeval *);
73 static void	timevalfix(struct timeval *);
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 int
79 settime(struct timeval *tv)
80 {
81 	struct timeval delta, tv1, tv2;
82 	static struct timeval maxtime, laststep;
83 	struct timespec ts;
84 	int origcpu;
85 
86 	if ((origcpu = mycpu->gd_cpuid) != 0)
87 		lwkt_setcpu_self(globaldata_find(0));
88 
89 	crit_enter();
90 	microtime(&tv1);
91 	delta = *tv;
92 	timevalsub(&delta, &tv1);
93 
94 	/*
95 	 * If the system is secure, we do not allow the time to be
96 	 * set to a value earlier than 1 second less than the highest
97 	 * time we have yet seen. The worst a miscreant can do in
98 	 * this circumstance is "freeze" time. He couldn't go
99 	 * back to the past.
100 	 *
101 	 * We similarly do not allow the clock to be stepped more
102 	 * than one second, nor more than once per second. This allows
103 	 * a miscreant to make the clock march double-time, but no worse.
104 	 */
105 	if (securelevel > 1) {
106 		if (delta.tv_sec < 0 || delta.tv_usec < 0) {
107 			/*
108 			 * Update maxtime to latest time we've seen.
109 			 */
110 			if (tv1.tv_sec > maxtime.tv_sec)
111 				maxtime = tv1;
112 			tv2 = *tv;
113 			timevalsub(&tv2, &maxtime);
114 			if (tv2.tv_sec < -1) {
115 				tv->tv_sec = maxtime.tv_sec - 1;
116 				kprintf("Time adjustment clamped to -1 second\n");
117 			}
118 		} else {
119 			if (tv1.tv_sec == laststep.tv_sec) {
120 				crit_exit();
121 				return (EPERM);
122 			}
123 			if (delta.tv_sec > 1) {
124 				tv->tv_sec = tv1.tv_sec + 1;
125 				kprintf("Time adjustment clamped to +1 second\n");
126 			}
127 			laststep = *tv;
128 		}
129 	}
130 
131 	ts.tv_sec = tv->tv_sec;
132 	ts.tv_nsec = tv->tv_usec * 1000;
133 	set_timeofday(&ts);
134 	crit_exit();
135 
136 	if (origcpu != 0)
137 		lwkt_setcpu_self(globaldata_find(origcpu));
138 
139 	resettodr();
140 	return (0);
141 }
142 
143 int
144 kern_clock_gettime(clockid_t clock_id, struct timespec *ats)
145 {
146 	int error = 0;
147 
148 	switch(clock_id) {
149 	case CLOCK_REALTIME:
150 		nanotime(ats);
151 		break;
152 	case CLOCK_MONOTONIC:
153 		nanouptime(ats);
154 		break;
155 	default:
156 		error = EINVAL;
157 		break;
158 	}
159 	return (error);
160 }
161 
162 /* ARGSUSED */
163 int
164 sys_clock_gettime(struct clock_gettime_args *uap)
165 {
166 	struct timespec ats;
167 	int error;
168 
169 	error = kern_clock_gettime(uap->clock_id, &ats);
170 	if (error == 0)
171 		error = copyout(&ats, uap->tp, sizeof(ats));
172 
173 	return (error);
174 }
175 
176 int
177 kern_clock_settime(clockid_t clock_id, struct timespec *ats)
178 {
179 	struct thread *td = curthread;
180 	struct timeval atv;
181 	int error;
182 
183 	if ((error = priv_check(td, PRIV_ROOT)) != 0)
184 		return (error);
185 	if (clock_id != CLOCK_REALTIME)
186 		return (EINVAL);
187 	if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
188 		return (EINVAL);
189 
190 	TIMESPEC_TO_TIMEVAL(&atv, ats);
191 	error = settime(&atv);
192 	return (error);
193 }
194 
195 /* ARGSUSED */
196 int
197 sys_clock_settime(struct clock_settime_args *uap)
198 {
199 	struct timespec ats;
200 	int error;
201 
202 	if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
203 		return (error);
204 
205 	return (kern_clock_settime(uap->clock_id, &ats));
206 }
207 
208 int
209 kern_clock_getres(clockid_t clock_id, struct timespec *ts)
210 {
211 	int error;
212 
213 	switch(clock_id) {
214 	case CLOCK_REALTIME:
215 	case CLOCK_MONOTONIC:
216 		/*
217 		 * Round up the result of the division cheaply
218 		 * by adding 1.  Rounding up is especially important
219 		 * if rounding down would give 0.  Perfect rounding
220 		 * is unimportant.
221 		 */
222 		ts->tv_sec = 0;
223 		ts->tv_nsec = 1000000000 / sys_cputimer->freq + 1;
224 		error = 0;
225 		break;
226 	default:
227 		error = EINVAL;
228 		break;
229 	}
230 
231 	return(error);
232 }
233 
234 int
235 sys_clock_getres(struct clock_getres_args *uap)
236 {
237 	int error;
238 	struct timespec ts;
239 
240 	error = kern_clock_getres(uap->clock_id, &ts);
241 	if (error == 0)
242 		error = copyout(&ts, uap->tp, sizeof(ts));
243 
244 	return (error);
245 }
246 
247 /*
248  * nanosleep1()
249  *
250  *	This is a general helper function for nanosleep() (aka sleep() aka
251  *	usleep()).
252  *
253  *	If there is less then one tick's worth of time left and
254  *	we haven't done a yield, or the remaining microseconds is
255  *	ridiculously low, do a yield.  This avoids having
256  *	to deal with systimer overheads when the system is under
257  *	heavy loads.  If we have done a yield already then use
258  *	a systimer and an uninterruptable thread wait.
259  *
260  *	If there is more then a tick's worth of time left,
261  *	calculate the baseline ticks and use an interruptable
262  *	tsleep, then handle the fine-grained delay on the next
263  *	loop.  This usually results in two sleeps occuring, a long one
264  *	and a short one.
265  */
266 static void
267 ns1_systimer(systimer_t info)
268 {
269 	lwkt_schedule(info->data);
270 }
271 
272 static int
273 nanosleep1(struct timespec *rqt, struct timespec *rmt)
274 {
275 	static int nanowait;
276 	struct timespec ts, ts2, ts3;
277 	struct timeval tv;
278 	int error;
279 	int tried_yield;
280 
281 	if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
282 		return (EINVAL);
283 	if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
284 		return (0);
285 	nanouptime(&ts);
286 	timespecadd(&ts, rqt);		/* ts = target timestamp compare */
287 	TIMESPEC_TO_TIMEVAL(&tv, rqt);	/* tv = sleep interval */
288 	tried_yield = 0;
289 
290 	for (;;) {
291 		int ticks;
292 		struct systimer info;
293 
294 		ticks = tv.tv_usec / tick;	/* approximate */
295 
296 		if (tv.tv_sec == 0 && ticks == 0) {
297 			thread_t td = curthread;
298 			if (tried_yield || tv.tv_usec < sleep_hard_us) {
299 				tried_yield = 0;
300 				uio_yield();
301 			} else {
302 				crit_enter_quick(td);
303 				systimer_init_oneshot(&info, ns1_systimer,
304 						td, tv.tv_usec);
305 				lwkt_deschedule_self(td);
306 				crit_exit_quick(td);
307 				lwkt_switch();
308 				systimer_del(&info); /* make sure it's gone */
309 			}
310 			error = iscaught(td->td_lwp);
311 		} else if (tv.tv_sec == 0) {
312 			error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
313 		} else {
314 			ticks = tvtohz_low(&tv); /* also handles overflow */
315 			error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
316 		}
317 		nanouptime(&ts2);
318 		if (error && error != EWOULDBLOCK) {
319 			if (error == ERESTART)
320 				error = EINTR;
321 			if (rmt != NULL) {
322 				timespecsub(&ts, &ts2);
323 				if (ts.tv_sec < 0)
324 					timespecclear(&ts);
325 				*rmt = ts;
326 			}
327 			return (error);
328 		}
329 		if (timespeccmp(&ts2, &ts, >=))
330 			return (0);
331 		ts3 = ts;
332 		timespecsub(&ts3, &ts2);
333 		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
334 	}
335 }
336 
337 /* ARGSUSED */
338 int
339 sys_nanosleep(struct nanosleep_args *uap)
340 {
341 	int error;
342 	struct timespec rqt;
343 	struct timespec rmt;
344 
345 	error = copyin(uap->rqtp, &rqt, sizeof(rqt));
346 	if (error)
347 		return (error);
348 
349 	error = nanosleep1(&rqt, &rmt);
350 
351 	/*
352 	 * copyout the residual if nanosleep was interrupted.
353 	 */
354 	if (error && uap->rmtp)
355 		error = copyout(&rmt, uap->rmtp, sizeof(rmt));
356 	return (error);
357 }
358 
359 /* ARGSUSED */
360 int
361 sys_gettimeofday(struct gettimeofday_args *uap)
362 {
363 	struct timeval atv;
364 	int error = 0;
365 
366 	if (uap->tp) {
367 		microtime(&atv);
368 		if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
369 		    sizeof (atv))))
370 			return (error);
371 	}
372 	if (uap->tzp)
373 		error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
374 		    sizeof (tz));
375 	return (error);
376 }
377 
378 /* ARGSUSED */
379 int
380 sys_settimeofday(struct settimeofday_args *uap)
381 {
382 	struct thread *td = curthread;
383 	struct timeval atv;
384 	struct timezone atz;
385 	int error;
386 
387 	if ((error = priv_check(td, PRIV_ROOT)))
388 		return (error);
389 	/* Verify all parameters before changing time. */
390 	if (uap->tv) {
391 		if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
392 		    sizeof(atv))))
393 			return (error);
394 		if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
395 			return (EINVAL);
396 	}
397 	if (uap->tzp &&
398 	    (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
399 		return (error);
400 	if (uap->tv && (error = settime(&atv)))
401 		return (error);
402 	if (uap->tzp)
403 		tz = atz;
404 	return (0);
405 }
406 
407 static void
408 kern_adjtime_common(void)
409 {
410 	if ((ntp_delta >= 0 && ntp_delta < ntp_default_tick_delta) ||
411 	    (ntp_delta < 0 && ntp_delta > -ntp_default_tick_delta))
412 		ntp_tick_delta = ntp_delta;
413 	else if (ntp_delta > ntp_big_delta)
414 		ntp_tick_delta = 10 * ntp_default_tick_delta;
415 	else if (ntp_delta < -ntp_big_delta)
416 		ntp_tick_delta = -10 * ntp_default_tick_delta;
417 	else if (ntp_delta > 0)
418 		ntp_tick_delta = ntp_default_tick_delta;
419 	else
420 		ntp_tick_delta = -ntp_default_tick_delta;
421 }
422 
423 void
424 kern_adjtime(int64_t delta, int64_t *odelta)
425 {
426 	int origcpu;
427 
428 	if ((origcpu = mycpu->gd_cpuid) != 0)
429 		lwkt_setcpu_self(globaldata_find(0));
430 
431 	crit_enter();
432 	*odelta = ntp_delta;
433 	ntp_delta = delta;
434 	kern_adjtime_common();
435 	crit_exit();
436 
437 	if (origcpu != 0)
438 		lwkt_setcpu_self(globaldata_find(origcpu));
439 }
440 
441 static void
442 kern_get_ntp_delta(int64_t *delta)
443 {
444 	int origcpu;
445 
446 	if ((origcpu = mycpu->gd_cpuid) != 0)
447 		lwkt_setcpu_self(globaldata_find(0));
448 
449 	crit_enter();
450 	*delta = ntp_delta;
451 	crit_exit();
452 
453 	if (origcpu != 0)
454 		lwkt_setcpu_self(globaldata_find(origcpu));
455 }
456 
457 void
458 kern_reladjtime(int64_t delta)
459 {
460 	int origcpu;
461 
462 	if ((origcpu = mycpu->gd_cpuid) != 0)
463 		lwkt_setcpu_self(globaldata_find(0));
464 
465 	crit_enter();
466 	ntp_delta += delta;
467 	kern_adjtime_common();
468 	crit_exit();
469 
470 	if (origcpu != 0)
471 		lwkt_setcpu_self(globaldata_find(origcpu));
472 }
473 
474 static void
475 kern_adjfreq(int64_t rate)
476 {
477 	int origcpu;
478 
479 	if ((origcpu = mycpu->gd_cpuid) != 0)
480 		lwkt_setcpu_self(globaldata_find(0));
481 
482 	crit_enter();
483 	ntp_tick_permanent = rate;
484 	crit_exit();
485 
486 	if (origcpu != 0)
487 		lwkt_setcpu_self(globaldata_find(origcpu));
488 }
489 
490 /* ARGSUSED */
491 int
492 sys_adjtime(struct adjtime_args *uap)
493 {
494 	struct thread *td = curthread;
495 	struct timeval atv;
496 	int64_t ndelta, odelta;
497 	int error;
498 
499 	if ((error = priv_check(td, PRIV_ROOT)))
500 		return (error);
501 	if ((error =
502 	    copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
503 		return (error);
504 
505 	/*
506 	 * Compute the total correction and the rate at which to apply it.
507 	 * Round the adjustment down to a whole multiple of the per-tick
508 	 * delta, so that after some number of incremental changes in
509 	 * hardclock(), tickdelta will become zero, lest the correction
510 	 * overshoot and start taking us away from the desired final time.
511 	 */
512 	ndelta = (int64_t)atv.tv_sec * 1000000000 + atv.tv_usec * 1000;
513 	kern_adjtime(ndelta, &odelta);
514 
515 	if (uap->olddelta) {
516 		atv.tv_sec = odelta / 1000000000;
517 		atv.tv_usec = odelta % 1000000000 / 1000;
518 		(void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
519 		    sizeof(struct timeval));
520 	}
521 	return (0);
522 }
523 
524 static int
525 sysctl_adjtime(SYSCTL_HANDLER_ARGS)
526 {
527 	int64_t delta;
528 	int error;
529 
530 	if (req->newptr != NULL) {
531 		if (priv_check(curthread, PRIV_ROOT))
532 			return (EPERM);
533 		error = SYSCTL_IN(req, &delta, sizeof(delta));
534 		if (error)
535 			return (error);
536 		kern_reladjtime(delta);
537 	}
538 
539 	if (req->oldptr)
540 		kern_get_ntp_delta(&delta);
541 	error = SYSCTL_OUT(req, &delta, sizeof(delta));
542 	return (error);
543 }
544 
545 /*
546  * delta is in nanoseconds.
547  */
548 static int
549 sysctl_delta(SYSCTL_HANDLER_ARGS)
550 {
551 	int64_t delta, old_delta;
552 	int error;
553 
554 	if (req->newptr != NULL) {
555 		if (priv_check(curthread, PRIV_ROOT))
556 			return (EPERM);
557 		error = SYSCTL_IN(req, &delta, sizeof(delta));
558 		if (error)
559 			return (error);
560 		kern_adjtime(delta, &old_delta);
561 	}
562 
563 	if (req->oldptr != NULL)
564 		kern_get_ntp_delta(&old_delta);
565 	error = SYSCTL_OUT(req, &old_delta, sizeof(old_delta));
566 	return (error);
567 }
568 
569 /*
570  * frequency is in nanoseconds per second shifted left 32.
571  * kern_adjfreq() needs it in nanoseconds per tick shifted left 32.
572  */
573 static int
574 sysctl_adjfreq(SYSCTL_HANDLER_ARGS)
575 {
576 	int64_t freqdelta;
577 	int error;
578 
579 	if (req->newptr != NULL) {
580 		if (priv_check(curthread, PRIV_ROOT))
581 			return (EPERM);
582 		error = SYSCTL_IN(req, &freqdelta, sizeof(freqdelta));
583 		if (error)
584 			return (error);
585 
586 		freqdelta /= hz;
587 		kern_adjfreq(freqdelta);
588 	}
589 
590 	if (req->oldptr != NULL)
591 		freqdelta = ntp_tick_permanent * hz;
592 	error = SYSCTL_OUT(req, &freqdelta, sizeof(freqdelta));
593 	if (error)
594 		return (error);
595 
596 	return (0);
597 }
598 
599 SYSCTL_NODE(_kern, OID_AUTO, ntp, CTLFLAG_RW, 0, "NTP related controls");
600 SYSCTL_PROC(_kern_ntp, OID_AUTO, permanent,
601     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
602     sysctl_adjfreq, "Q", "permanent correction per second");
603 SYSCTL_PROC(_kern_ntp, OID_AUTO, delta,
604     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
605     sysctl_delta, "Q", "one-time delta");
606 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, big_delta, CTLFLAG_RD,
607     &ntp_big_delta, sizeof(ntp_big_delta), "Q",
608     "threshold for fast adjustment");
609 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, tick_delta, CTLFLAG_RD,
610     &ntp_tick_delta, sizeof(ntp_tick_delta), "LU",
611     "per-tick adjustment");
612 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, default_tick_delta, CTLFLAG_RD,
613     &ntp_default_tick_delta, sizeof(ntp_default_tick_delta), "LU",
614     "default per-tick adjustment");
615 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, next_leap_second, CTLFLAG_RW,
616     &ntp_leap_second, sizeof(ntp_leap_second), "LU",
617     "next leap second");
618 SYSCTL_INT(_kern_ntp, OID_AUTO, insert_leap_second, CTLFLAG_RW,
619     &ntp_leap_insert, 0, "insert or remove leap second");
620 SYSCTL_PROC(_kern_ntp, OID_AUTO, adjust,
621     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
622     sysctl_adjtime, "Q", "relative adjust for delta");
623 
624 /*
625  * Get value of an interval timer.  The process virtual and
626  * profiling virtual time timers are kept in the p_stats area, since
627  * they can be swapped out.  These are kept internally in the
628  * way they are specified externally: in time until they expire.
629  *
630  * The real time interval timer is kept in the process table slot
631  * for the process, and its value (it_value) is kept as an
632  * absolute time rather than as a delta, so that it is easy to keep
633  * periodic real-time signals from drifting.
634  *
635  * Virtual time timers are processed in the hardclock() routine of
636  * kern_clock.c.  The real time timer is processed by a timeout
637  * routine, called from the softclock() routine.  Since a callout
638  * may be delayed in real time due to interrupt processing in the system,
639  * it is possible for the real time timeout routine (realitexpire, given below),
640  * to be delayed in real time past when it is supposed to occur.  It
641  * does not suffice, therefore, to reload the real timer .it_value from the
642  * real time timers .it_interval.  Rather, we compute the next time in
643  * absolute time the timer should go off.
644  */
645 /* ARGSUSED */
646 int
647 sys_getitimer(struct getitimer_args *uap)
648 {
649 	struct proc *p = curproc;
650 	struct timeval ctv;
651 	struct itimerval aitv;
652 
653 	if (uap->which > ITIMER_PROF)
654 		return (EINVAL);
655 	crit_enter();
656 	if (uap->which == ITIMER_REAL) {
657 		/*
658 		 * Convert from absolute to relative time in .it_value
659 		 * part of real time timer.  If time for real time timer
660 		 * has passed return 0, else return difference between
661 		 * current time and time for the timer to go off.
662 		 */
663 		aitv = p->p_realtimer;
664 		if (timevalisset(&aitv.it_value)) {
665 			getmicrouptime(&ctv);
666 			if (timevalcmp(&aitv.it_value, &ctv, <))
667 				timevalclear(&aitv.it_value);
668 			else
669 				timevalsub(&aitv.it_value, &ctv);
670 		}
671 	} else {
672 		aitv = p->p_timer[uap->which];
673 	}
674 	crit_exit();
675 	return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
676 	    sizeof (struct itimerval)));
677 }
678 
679 /* ARGSUSED */
680 int
681 sys_setitimer(struct setitimer_args *uap)
682 {
683 	struct itimerval aitv;
684 	struct timeval ctv;
685 	struct itimerval *itvp;
686 	struct proc *p = curproc;
687 	int error;
688 
689 	if (uap->which > ITIMER_PROF)
690 		return (EINVAL);
691 	itvp = uap->itv;
692 	if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
693 	    sizeof(struct itimerval))))
694 		return (error);
695 	if ((uap->itv = uap->oitv) &&
696 	    (error = sys_getitimer((struct getitimer_args *)uap)))
697 		return (error);
698 	if (itvp == 0)
699 		return (0);
700 	if (itimerfix(&aitv.it_value))
701 		return (EINVAL);
702 	if (!timevalisset(&aitv.it_value))
703 		timevalclear(&aitv.it_interval);
704 	else if (itimerfix(&aitv.it_interval))
705 		return (EINVAL);
706 	crit_enter();
707 	if (uap->which == ITIMER_REAL) {
708 		if (timevalisset(&p->p_realtimer.it_value))
709 			callout_stop(&p->p_ithandle);
710 		if (timevalisset(&aitv.it_value))
711 			callout_reset(&p->p_ithandle,
712 			    tvtohz_high(&aitv.it_value), realitexpire, p);
713 		getmicrouptime(&ctv);
714 		timevaladd(&aitv.it_value, &ctv);
715 		p->p_realtimer = aitv;
716 	} else {
717 		p->p_timer[uap->which] = aitv;
718 	}
719 	crit_exit();
720 	return (0);
721 }
722 
723 /*
724  * Real interval timer expired:
725  * send process whose timer expired an alarm signal.
726  * If time is not set up to reload, then just return.
727  * Else compute next time timer should go off which is > current time.
728  * This is where delay in processing this timeout causes multiple
729  * SIGALRM calls to be compressed into one.
730  * tvtohz_high() always adds 1 to allow for the time until the next clock
731  * interrupt being strictly less than 1 clock tick, but we don't want
732  * that here since we want to appear to be in sync with the clock
733  * interrupt even when we're delayed.
734  */
735 void
736 realitexpire(void *arg)
737 {
738 	struct proc *p;
739 	struct timeval ctv, ntv;
740 
741 	p = (struct proc *)arg;
742 	ksignal(p, SIGALRM);
743 	if (!timevalisset(&p->p_realtimer.it_interval)) {
744 		timevalclear(&p->p_realtimer.it_value);
745 		return;
746 	}
747 	for (;;) {
748 		crit_enter();
749 		timevaladd(&p->p_realtimer.it_value,
750 		    &p->p_realtimer.it_interval);
751 		getmicrouptime(&ctv);
752 		if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
753 			ntv = p->p_realtimer.it_value;
754 			timevalsub(&ntv, &ctv);
755 			callout_reset(&p->p_ithandle, tvtohz_low(&ntv),
756 				      realitexpire, p);
757 			crit_exit();
758 			return;
759 		}
760 		crit_exit();
761 	}
762 }
763 
764 /*
765  * Check that a proposed value to load into the .it_value or
766  * .it_interval part of an interval timer is acceptable, and
767  * fix it to have at least minimal value (i.e. if it is less
768  * than the resolution of the clock, round it up.)
769  */
770 int
771 itimerfix(struct timeval *tv)
772 {
773 
774 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
775 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
776 		return (EINVAL);
777 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
778 		tv->tv_usec = tick;
779 	return (0);
780 }
781 
782 /*
783  * Decrement an interval timer by a specified number
784  * of microseconds, which must be less than a second,
785  * i.e. < 1000000.  If the timer expires, then reload
786  * it.  In this case, carry over (usec - old value) to
787  * reduce the value reloaded into the timer so that
788  * the timer does not drift.  This routine assumes
789  * that it is called in a context where the timers
790  * on which it is operating cannot change in value.
791  */
792 int
793 itimerdecr(struct itimerval *itp, int usec)
794 {
795 
796 	if (itp->it_value.tv_usec < usec) {
797 		if (itp->it_value.tv_sec == 0) {
798 			/* expired, and already in next interval */
799 			usec -= itp->it_value.tv_usec;
800 			goto expire;
801 		}
802 		itp->it_value.tv_usec += 1000000;
803 		itp->it_value.tv_sec--;
804 	}
805 	itp->it_value.tv_usec -= usec;
806 	usec = 0;
807 	if (timevalisset(&itp->it_value))
808 		return (1);
809 	/* expired, exactly at end of interval */
810 expire:
811 	if (timevalisset(&itp->it_interval)) {
812 		itp->it_value = itp->it_interval;
813 		itp->it_value.tv_usec -= usec;
814 		if (itp->it_value.tv_usec < 0) {
815 			itp->it_value.tv_usec += 1000000;
816 			itp->it_value.tv_sec--;
817 		}
818 	} else
819 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
820 	return (0);
821 }
822 
823 /*
824  * Add and subtract routines for timevals.
825  * N.B.: subtract routine doesn't deal with
826  * results which are before the beginning,
827  * it just gets very confused in this case.
828  * Caveat emptor.
829  */
830 void
831 timevaladd(struct timeval *t1, const struct timeval *t2)
832 {
833 
834 	t1->tv_sec += t2->tv_sec;
835 	t1->tv_usec += t2->tv_usec;
836 	timevalfix(t1);
837 }
838 
839 void
840 timevalsub(struct timeval *t1, const struct timeval *t2)
841 {
842 
843 	t1->tv_sec -= t2->tv_sec;
844 	t1->tv_usec -= t2->tv_usec;
845 	timevalfix(t1);
846 }
847 
848 static void
849 timevalfix(struct timeval *t1)
850 {
851 
852 	if (t1->tv_usec < 0) {
853 		t1->tv_sec--;
854 		t1->tv_usec += 1000000;
855 	}
856 	if (t1->tv_usec >= 1000000) {
857 		t1->tv_sec++;
858 		t1->tv_usec -= 1000000;
859 	}
860 }
861 
862 /*
863  * ratecheck(): simple time-based rate-limit checking.
864  */
865 int
866 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
867 {
868 	struct timeval tv, delta;
869 	int rv = 0;
870 
871 	getmicrouptime(&tv);		/* NB: 10ms precision */
872 	delta = tv;
873 	timevalsub(&delta, lasttime);
874 
875 	/*
876 	 * check for 0,0 is so that the message will be seen at least once,
877 	 * even if interval is huge.
878 	 */
879 	if (timevalcmp(&delta, mininterval, >=) ||
880 	    (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
881 		*lasttime = tv;
882 		rv = 1;
883 	}
884 
885 	return (rv);
886 }
887 
888 /*
889  * ppsratecheck(): packets (or events) per second limitation.
890  *
891  * Return 0 if the limit is to be enforced (e.g. the caller
892  * should drop a packet because of the rate limitation).
893  *
894  * maxpps of 0 always causes zero to be returned.  maxpps of -1
895  * always causes 1 to be returned; this effectively defeats rate
896  * limiting.
897  *
898  * Note that we maintain the struct timeval for compatibility
899  * with other bsd systems.  We reuse the storage and just monitor
900  * clock ticks for minimal overhead.
901  */
902 int
903 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
904 {
905 	int now;
906 
907 	/*
908 	 * Reset the last time and counter if this is the first call
909 	 * or more than a second has passed since the last update of
910 	 * lasttime.
911 	 */
912 	now = ticks;
913 	if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
914 		lasttime->tv_sec = now;
915 		*curpps = 1;
916 		return (maxpps != 0);
917 	} else {
918 		(*curpps)++;		/* NB: ignore potential overflow */
919 		return (maxpps < 0 || *curpps < maxpps);
920 	}
921 }
922 
923