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