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