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