kernel - Refactor sysclock_t from 32 to 64 bits
[dragonfly.git] / sys / kern / kern_time.c
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)kern_time.c 8.1 (Berkeley) 6/10/93
30  * $FreeBSD: src/sys/kern/kern_time.c,v 1.68.2.1 2002/10/01 08:00:41 bde Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/buf.h>
36 #include <sys/sysproto.h>
37 #include <sys/resourcevar.h>
38 #include <sys/signalvar.h>
39 #include <sys/kernel.h>
40 #include <sys/sysent.h>
41 #include <sys/sysunion.h>
42 #include <sys/proc.h>
43 #include <sys/priv.h>
44 #include <sys/time.h>
45 #include <sys/vnode.h>
46 #include <sys/sysctl.h>
47 #include <sys/kern_syscall.h>
48 #include <sys/upmap.h>
49 #include <vm/vm.h>
50 #include <vm/vm_extern.h>
51
52 #include <sys/msgport2.h>
53 #include <sys/spinlock2.h>
54 #include <sys/thread2.h>
55
56 extern struct spinlock ntp_spin;
57
58 #define CPUCLOCK_BIT                    0x80000000
59 #define CPUCLOCK_ID_MASK                ~CPUCLOCK_BIT
60 #define CPUCLOCK2LWPID(clock_id)        (((clockid_t)(clock_id) >> 32) & CPUCLOCK_ID_MASK)
61 #define CPUCLOCK2PID(clock_id)          ((clock_id) & CPUCLOCK_ID_MASK)
62 #define MAKE_CPUCLOCK(pid, lwp_id)      ((clockid_t)(lwp_id) << 32 | (pid) | CPUCLOCK_BIT)
63
64 struct timezone tz;
65
66 /*
67  * Time of day and interval timer support.
68  *
69  * These routines provide the kernel entry points to get and set
70  * the time-of-day and per-process interval timers.  Subroutines
71  * here provide support for adding and subtracting timeval structures
72  * and decrementing interval timers, optionally reloading the interval
73  * timers when they expire.
74  */
75
76 static int      settime(struct timeval *);
77 static void     timevalfix(struct timeval *);
78 static void     realitexpire(void *arg);
79
80 static int sysctl_gettimeofday_quick(SYSCTL_HANDLER_ARGS);
81
82
83 /*
84  * Nanosleep tries very hard to sleep for a precisely requested time
85  * interval, down to 1uS.  The administrator can impose a minimum delay
86  * and a delay below which we hard-loop instead of initiate a timer
87  * interrupt and sleep.
88  *
89  * For machines under high loads it might be beneficial to increase min_us
90  * to e.g. 1000uS (1ms) so spining processes sleep meaningfully.
91  */
92 static int     nanosleep_min_us = 10;
93 static int     nanosleep_hard_us = 100;
94 static int     gettimeofday_quick = 0;
95 SYSCTL_INT(_kern, OID_AUTO, nanosleep_min_us, CTLFLAG_RW,
96            &nanosleep_min_us, 0, "");
97 SYSCTL_INT(_kern, OID_AUTO, nanosleep_hard_us, CTLFLAG_RW,
98            &nanosleep_hard_us, 0, "");
99 SYSCTL_PROC(_kern, OID_AUTO, gettimeofday_quick, CTLTYPE_INT | CTLFLAG_RW,
100            0, 0, sysctl_gettimeofday_quick, "I", "Quick mode gettimeofday");
101
102 static struct lock masterclock_lock = LOCK_INITIALIZER("mstrclk", 0, 0);
103
104 static int
105 settime(struct timeval *tv)
106 {
107         struct timeval delta, tv1, tv2;
108         static struct timeval maxtime, laststep;
109         struct timespec ts;
110         int origcpu;
111
112         if ((origcpu = mycpu->gd_cpuid) != 0)
113                 lwkt_setcpu_self(globaldata_find(0));
114
115         crit_enter();
116         microtime(&tv1);
117         delta = *tv;
118         timevalsub(&delta, &tv1);
119
120         /*
121          * If the system is secure, we do not allow the time to be 
122          * set to a value earlier than 1 second less than the highest
123          * time we have yet seen. The worst a miscreant can do in
124          * this circumstance is "freeze" time. He couldn't go
125          * back to the past.
126          *
127          * We similarly do not allow the clock to be stepped more
128          * than one second, nor more than once per second. This allows
129          * a miscreant to make the clock march double-time, but no worse.
130          */
131         if (securelevel > 1) {
132                 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
133                         /*
134                          * Update maxtime to latest time we've seen.
135                          */
136                         if (tv1.tv_sec > maxtime.tv_sec)
137                                 maxtime = tv1;
138                         tv2 = *tv;
139                         timevalsub(&tv2, &maxtime);
140                         if (tv2.tv_sec < -1) {
141                                 tv->tv_sec = maxtime.tv_sec - 1;
142                                 kprintf("Time adjustment clamped to -1 second\n");
143                         }
144                 } else {
145                         if (tv1.tv_sec == laststep.tv_sec) {
146                                 crit_exit();
147                                 return (EPERM);
148                         }
149                         if (delta.tv_sec > 1) {
150                                 tv->tv_sec = tv1.tv_sec + 1;
151                                 kprintf("Time adjustment clamped to +1 second\n");
152                         }
153                         laststep = *tv;
154                 }
155         }
156
157         ts.tv_sec = tv->tv_sec;
158         ts.tv_nsec = tv->tv_usec * 1000;
159         set_timeofday(&ts);
160         crit_exit();
161
162         if (origcpu != 0)
163                 lwkt_setcpu_self(globaldata_find(origcpu));
164
165         resettodr();
166         return (0);
167 }
168
169 static void
170 get_process_cputime(struct proc *p, struct timespec *ats)
171 {
172         struct rusage ru;
173
174         lwkt_gettoken(&p->p_token);
175         calcru_proc(p, &ru);
176         lwkt_reltoken(&p->p_token);
177         timevaladd(&ru.ru_utime, &ru.ru_stime);
178         TIMEVAL_TO_TIMESPEC(&ru.ru_utime, ats);
179 }
180
181 static void
182 get_process_usertime(struct proc *p, struct timespec *ats)
183 {
184         struct rusage ru;
185
186         lwkt_gettoken(&p->p_token);
187         calcru_proc(p, &ru);
188         lwkt_reltoken(&p->p_token);
189         TIMEVAL_TO_TIMESPEC(&ru.ru_utime, ats);
190 }
191
192 static void
193 get_thread_cputime(struct thread *td, struct timespec *ats)
194 {
195         struct timeval sys, user;
196
197         calcru(td->td_lwp, &user, &sys);
198         timevaladd(&user, &sys);
199         TIMEVAL_TO_TIMESPEC(&user, ats);
200 }
201
202 /*
203  * MPSAFE
204  */
205 int
206 kern_clock_gettime(clockid_t clock_id, struct timespec *ats)
207 {
208         struct proc *p;
209         struct lwp *lp;
210         lwpid_t lwp_id;
211
212         p = curproc;
213         switch(clock_id) {
214         case CLOCK_REALTIME:
215         case CLOCK_REALTIME_PRECISE:
216                 nanotime(ats);
217                 break;
218         case CLOCK_REALTIME_FAST:
219                 getnanotime(ats);
220                 break;
221         case CLOCK_MONOTONIC:
222         case CLOCK_MONOTONIC_PRECISE:
223         case CLOCK_UPTIME:
224         case CLOCK_UPTIME_PRECISE:
225                 nanouptime(ats);
226                 break;
227         case CLOCK_MONOTONIC_FAST:
228         case CLOCK_UPTIME_FAST:
229                 getnanouptime(ats);
230                 break;
231         case CLOCK_VIRTUAL:
232                 get_process_usertime(p, ats);
233                 break;
234         case CLOCK_PROF:
235         case CLOCK_PROCESS_CPUTIME_ID:
236                 get_process_cputime(p, ats);
237                 break;
238         case CLOCK_SECOND:
239                 ats->tv_sec = time_second;
240                 ats->tv_nsec = 0;
241                 break;
242         case CLOCK_THREAD_CPUTIME_ID:
243                 get_thread_cputime(curthread, ats);
244                 break;
245         default:
246                 if ((clock_id & CPUCLOCK_BIT) == 0)
247                         return (EINVAL);
248                 if ((p = pfind(CPUCLOCK2PID(clock_id))) == NULL)
249                         return (EINVAL);
250                 lwp_id = CPUCLOCK2LWPID(clock_id);
251                 if (lwp_id == 0) {
252                         get_process_cputime(p, ats);
253                 } else {
254                         lwkt_gettoken(&p->p_token);
255                         lp = lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, lwp_id);
256                         if (lp == NULL) {
257                                 lwkt_reltoken(&p->p_token);
258                                 PRELE(p);
259                                 return (EINVAL);
260                         }
261                         get_thread_cputime(lp->lwp_thread, ats);
262                         lwkt_reltoken(&p->p_token);
263                 }
264                 PRELE(p);
265         }
266         return (0);
267 }
268
269 /*
270  * MPSAFE
271  */
272 int
273 sys_clock_gettime(struct clock_gettime_args *uap)
274 {
275         struct timespec ats;
276         int error;
277
278         error = kern_clock_gettime(uap->clock_id, &ats);
279         if (error == 0)
280                 error = copyout(&ats, uap->tp, sizeof(ats));
281
282         return (error);
283 }
284
285 int
286 kern_clock_settime(clockid_t clock_id, struct timespec *ats)
287 {
288         struct thread *td = curthread;
289         struct timeval atv;
290         int error;
291
292         if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
293                 return (error);
294         if (clock_id != CLOCK_REALTIME)
295                 return (EINVAL);
296         if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
297                 return (EINVAL);
298
299         lockmgr(&masterclock_lock, LK_EXCLUSIVE);
300         TIMESPEC_TO_TIMEVAL(&atv, ats);
301         error = settime(&atv);
302         lockmgr(&masterclock_lock, LK_RELEASE);
303
304         return (error);
305 }
306
307 /*
308  * MPALMOSTSAFE
309  */
310 int
311 sys_clock_settime(struct clock_settime_args *uap)
312 {
313         struct timespec ats;
314         int error;
315
316         if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
317                 return (error);
318
319         error = kern_clock_settime(uap->clock_id, &ats);
320
321         return (error);
322 }
323
324 /*
325  * MPSAFE
326  */
327 int
328 kern_clock_getres(clockid_t clock_id, struct timespec *ts)
329 {
330         ts->tv_sec = 0;
331
332         switch(clock_id) {
333         case CLOCK_REALTIME:
334         case CLOCK_REALTIME_FAST:
335         case CLOCK_REALTIME_PRECISE:
336         case CLOCK_MONOTONIC:
337         case CLOCK_MONOTONIC_FAST:
338         case CLOCK_MONOTONIC_PRECISE:
339         case CLOCK_UPTIME:
340         case CLOCK_UPTIME_FAST:
341         case CLOCK_UPTIME_PRECISE:
342                 /*
343                  * Minimum reportable resolution is 1ns.  Rounding is
344                  * otherwise unimportant.
345                  */
346                 ts->tv_nsec = 999999999 / sys_cputimer->freq + 1;
347                 break;
348         case CLOCK_VIRTUAL:
349         case CLOCK_PROF:
350                 /* Accurately round up here because we can do so cheaply. */
351                 ts->tv_nsec = (1000000000 + hz - 1) / hz;
352                 break;
353         case CLOCK_SECOND:
354                 ts->tv_sec = 1;
355                 ts->tv_nsec = 0;
356                 break;
357         case CLOCK_THREAD_CPUTIME_ID:
358         case CLOCK_PROCESS_CPUTIME_ID:
359                 ts->tv_nsec = 1000;
360                 break;
361         default:
362                 if ((clock_id & CPUCLOCK_BIT) != 0)
363                         ts->tv_nsec = 1000;
364                 else
365                         return (EINVAL);
366         }
367
368         return (0);
369 }
370
371 /*
372  * MPSAFE
373  */
374 int
375 sys_clock_getres(struct clock_getres_args *uap)
376 {
377         int error;
378         struct timespec ts;
379
380         error = kern_clock_getres(uap->clock_id, &ts);
381         if (error == 0)
382                 error = copyout(&ts, uap->tp, sizeof(ts));
383
384         return (error);
385 }
386
387 static int
388 kern_getcpuclockid(pid_t pid, lwpid_t lwp_id, clockid_t *clock_id)
389 {
390         struct proc *p;
391         int error = 0;
392
393         if (pid == 0) {
394                 p = curproc;
395                 pid = p->p_pid;
396                 PHOLD(p);
397         } else {
398                 p = pfind(pid);
399                 if (p == NULL)
400                         return (ESRCH);
401         }
402         /* lwp_id can be 0 when called by clock_getcpuclockid() */
403         if (lwp_id < 0) {
404                 error = EINVAL;
405                 goto out;
406         }
407         lwkt_gettoken(&p->p_token);
408         if (lwp_id > 0 &&
409             lwp_rb_tree_RB_LOOKUP(&p->p_lwp_tree, lwp_id) == NULL) {
410                 lwkt_reltoken(&p->p_token);
411                 error = ESRCH;
412                 goto out;
413         }
414         *clock_id = MAKE_CPUCLOCK(pid, lwp_id);
415         lwkt_reltoken(&p->p_token);
416 out:
417         PRELE(p);
418         return (error);
419 }
420
421 int
422 sys_getcpuclockid(struct getcpuclockid_args *uap)
423 {
424         clockid_t clk_id;
425         int error;
426
427         error = kern_getcpuclockid(uap->pid, uap->lwp_id, &clk_id);
428         if (error == 0)
429                 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
430
431         return (error);
432 }
433
434 /*
435  * nanosleep1()
436  *
437  *      This is a general helper function for nanosleep() (aka sleep() aka
438  *      usleep()).
439  *
440  *      If there is less then one tick's worth of time left and
441  *      we haven't done a yield, or the remaining microseconds is
442  *      ridiculously low, do a yield.  This avoids having
443  *      to deal with systimer overheads when the system is under
444  *      heavy loads.  If we have done a yield already then use
445  *      a systimer and an uninterruptable thread wait.
446  *
447  *      If there is more then a tick's worth of time left,
448  *      calculate the baseline ticks and use an interruptable
449  *      tsleep, then handle the fine-grained delay on the next
450  *      loop.  This usually results in two sleeps occuring, a long one
451  *      and a short one.
452  *
453  * MPSAFE
454  */
455 static void
456 ns1_systimer(systimer_t info, int in_ipi __unused,
457     struct intrframe *frame __unused)
458 {
459         lwkt_schedule(info->data);
460 }
461
462 int
463 nanosleep1(struct timespec *rqt, struct timespec *rmt)
464 {
465         static int nanowait;
466         struct timespec ts, ts2, ts3;
467         struct timeval tv;
468         int error;
469
470         if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
471                 return (EINVAL);
472         /* XXX: imho this should return EINVAL at least for tv_sec < 0 */
473         if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
474                 return (0);
475         nanouptime(&ts);
476         timespecadd(&ts, rqt, &ts);     /* ts = target timestamp compare */
477         TIMESPEC_TO_TIMEVAL(&tv, rqt);  /* tv = sleep interval */
478
479         for (;;) {
480                 int ticks;
481                 struct systimer info;
482
483                 ticks = tv.tv_usec / ustick;    /* approximate */
484
485                 if (tv.tv_sec == 0 && ticks == 0) {
486                         thread_t td = curthread;
487                         if (tv.tv_usec > 0 && tv.tv_usec < nanosleep_min_us)
488                                 tv.tv_usec = nanosleep_min_us;
489                         if (tv.tv_usec < nanosleep_hard_us) {
490                                 lwkt_user_yield();
491                                 cpu_pause();
492                         } else {
493                                 crit_enter_quick(td);
494                                 systimer_init_oneshot(&info, ns1_systimer,
495                                                 td, tv.tv_usec);
496                                 lwkt_deschedule_self(td);
497                                 crit_exit_quick(td);
498                                 lwkt_switch();
499                                 systimer_del(&info); /* make sure it's gone */
500                         }
501                         error = iscaught(td->td_lwp);
502                 } else if (tv.tv_sec == 0) {
503                         error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
504                 } else {
505                         ticks = tvtohz_low(&tv); /* also handles overflow */
506                         error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
507                 }
508                 nanouptime(&ts2);
509                 if (error && error != EWOULDBLOCK) {
510                         if (error == ERESTART)
511                                 error = EINTR;
512                         if (rmt != NULL) {
513                                 timespecsub(&ts, &ts2, &ts);
514                                 if (ts.tv_sec < 0)
515                                         timespecclear(&ts);
516                                 *rmt = ts;
517                         }
518                         return (error);
519                 }
520                 if (timespeccmp(&ts2, &ts, >=))
521                         return (0);
522                 timespecsub(&ts, &ts2, &ts3);
523                 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
524         }
525 }
526
527 /*
528  * MPSAFE
529  */
530 int
531 sys_nanosleep(struct nanosleep_args *uap)
532 {
533         int error;
534         struct timespec rqt;
535         struct timespec rmt;
536
537         error = copyin(uap->rqtp, &rqt, sizeof(rqt));
538         if (error)
539                 return (error);
540
541         error = nanosleep1(&rqt, &rmt);
542
543         /*
544          * copyout the residual if nanosleep was interrupted.
545          */
546         if (error && uap->rmtp) {
547                 int error2;
548
549                 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
550                 if (error2)
551                         error = error2;
552         }
553         return (error);
554 }
555
556 /*
557  * The gettimeofday() system call is supposed to return a fine-grained
558  * realtime stamp.  However, acquiring a fine-grained stamp can create a
559  * bottleneck when multiple cpu cores are trying to accessing e.g. the
560  * HPET hardware timer all at the same time, so we have a sysctl that
561  * allows its behavior to be changed to a more coarse-grained timestamp
562  * which does not have to access a hardware timer.
563  */
564 int
565 sys_gettimeofday(struct gettimeofday_args *uap)
566 {
567         struct timeval atv;
568         int error = 0;
569
570         if (uap->tp) {
571                 if (gettimeofday_quick)
572                         getmicrotime(&atv);
573                 else
574                         microtime(&atv);
575                 if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
576                     sizeof (atv))))
577                         return (error);
578         }
579         if (uap->tzp)
580                 error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
581                     sizeof (tz));
582         return (error);
583 }
584
585 /*
586  * MPALMOSTSAFE
587  */
588 int
589 sys_settimeofday(struct settimeofday_args *uap)
590 {
591         struct thread *td = curthread;
592         struct timeval atv;
593         struct timezone atz;
594         int error;
595
596         if ((error = priv_check(td, PRIV_SETTIMEOFDAY)))
597                 return (error);
598         /*
599          * Verify all parameters before changing time.
600          *
601          * XXX: We do not allow the time to be set to 0.0, which also by
602          *      happy coincidence works around a pkgsrc bulk build bug.
603          */
604         if (uap->tv) {
605                 if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
606                     sizeof(atv))))
607                         return (error);
608                 if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
609                         return (EINVAL);
610                 if (atv.tv_sec == 0 && atv.tv_usec == 0)
611                         return (EINVAL);
612         }
613         if (uap->tzp &&
614             (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
615                 return (error);
616
617         lockmgr(&masterclock_lock, LK_EXCLUSIVE);
618         if (uap->tv && (error = settime(&atv))) {
619                 lockmgr(&masterclock_lock, LK_RELEASE);
620                 return (error);
621         }
622         lockmgr(&masterclock_lock, LK_RELEASE);
623
624         if (uap->tzp)
625                 tz = atz;
626         return (0);
627 }
628
629 /*
630  * WARNING! Run with ntp_spin held
631  */
632 static void
633 kern_adjtime_common(void)
634 {
635         if ((ntp_delta >= 0 && ntp_delta < ntp_default_tick_delta) ||
636             (ntp_delta < 0 && ntp_delta > -ntp_default_tick_delta))
637                 ntp_tick_delta = ntp_delta;
638         else if (ntp_delta > ntp_big_delta)
639                 ntp_tick_delta = 10 * ntp_default_tick_delta;
640         else if (ntp_delta < -ntp_big_delta)
641                 ntp_tick_delta = -10 * ntp_default_tick_delta;
642         else if (ntp_delta > 0)
643                 ntp_tick_delta = ntp_default_tick_delta;
644         else
645                 ntp_tick_delta = -ntp_default_tick_delta;
646 }
647
648 void
649 kern_adjtime(int64_t delta, int64_t *odelta)
650 {
651         spin_lock(&ntp_spin);
652         *odelta = ntp_delta;
653         ntp_delta = delta;
654         kern_adjtime_common();
655         spin_unlock(&ntp_spin);
656 }
657
658 static void
659 kern_get_ntp_delta(int64_t *delta)
660 {
661         *delta = ntp_delta;
662 }
663
664 void
665 kern_reladjtime(int64_t delta)
666 {
667         spin_lock(&ntp_spin);
668         ntp_delta += delta;
669         kern_adjtime_common();
670         spin_unlock(&ntp_spin);
671 }
672
673 static void
674 kern_adjfreq(int64_t rate)
675 {
676         spin_lock(&ntp_spin);
677         ntp_tick_permanent = rate;
678         spin_unlock(&ntp_spin);
679 }
680
681 /*
682  * MPALMOSTSAFE
683  */
684 int
685 sys_adjtime(struct adjtime_args *uap)
686 {
687         struct thread *td = curthread;
688         struct timeval atv;
689         int64_t ndelta, odelta;
690         int error;
691
692         if ((error = priv_check(td, PRIV_ADJTIME)))
693                 return (error);
694         error = copyin(uap->delta, &atv, sizeof(struct timeval));
695         if (error)
696                 return (error);
697
698         /*
699          * Compute the total correction and the rate at which to apply it.
700          * Round the adjustment down to a whole multiple of the per-tick
701          * delta, so that after some number of incremental changes in
702          * hardclock(), tickdelta will become zero, lest the correction
703          * overshoot and start taking us away from the desired final time.
704          */
705         ndelta = (int64_t)atv.tv_sec * 1000000000 + atv.tv_usec * 1000;
706         kern_adjtime(ndelta, &odelta);
707
708         if (uap->olddelta) {
709                 atv.tv_sec = odelta / 1000000000;
710                 atv.tv_usec = odelta % 1000000000 / 1000;
711                 copyout(&atv, uap->olddelta, sizeof(struct timeval));
712         }
713         return (0);
714 }
715
716 static int
717 sysctl_adjtime(SYSCTL_HANDLER_ARGS)
718 {
719         int64_t delta;
720         int error;
721
722         if (req->newptr != NULL) {
723                 if (priv_check(curthread, PRIV_ROOT))
724                         return (EPERM);
725                 error = SYSCTL_IN(req, &delta, sizeof(delta));
726                 if (error)
727                         return (error);
728                 kern_reladjtime(delta);
729         }
730
731         if (req->oldptr)
732                 kern_get_ntp_delta(&delta);
733         error = SYSCTL_OUT(req, &delta, sizeof(delta));
734         return (error);
735 }
736
737 /*
738  * delta is in nanoseconds.
739  */
740 static int
741 sysctl_delta(SYSCTL_HANDLER_ARGS)
742 {
743         int64_t delta, old_delta;
744         int error;
745
746         if (req->newptr != NULL) {
747                 if (priv_check(curthread, PRIV_ROOT))
748                         return (EPERM);
749                 error = SYSCTL_IN(req, &delta, sizeof(delta));
750                 if (error)
751                         return (error);
752                 kern_adjtime(delta, &old_delta);
753         }
754
755         if (req->oldptr != NULL)
756                 kern_get_ntp_delta(&old_delta);
757         error = SYSCTL_OUT(req, &old_delta, sizeof(old_delta));
758         return (error);
759 }
760
761 /*
762  * frequency is in nanoseconds per second shifted left 32.
763  * kern_adjfreq() needs it in nanoseconds per tick shifted left 32.
764  */
765 static int
766 sysctl_adjfreq(SYSCTL_HANDLER_ARGS)
767 {
768         int64_t freqdelta;
769         int error;
770
771         if (req->newptr != NULL) {
772                 if (priv_check(curthread, PRIV_ROOT))
773                         return (EPERM);
774                 error = SYSCTL_IN(req, &freqdelta, sizeof(freqdelta));
775                 if (error)
776                         return (error);
777                 
778                 freqdelta /= hz;
779                 kern_adjfreq(freqdelta);
780         }
781
782         if (req->oldptr != NULL)
783                 freqdelta = ntp_tick_permanent * hz;
784         error = SYSCTL_OUT(req, &freqdelta, sizeof(freqdelta));
785         if (error)
786                 return (error);
787
788         return (0);
789 }
790
791 SYSCTL_NODE(_kern, OID_AUTO, ntp, CTLFLAG_RW, 0, "NTP related controls");
792 SYSCTL_PROC(_kern_ntp, OID_AUTO, permanent,
793     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
794     sysctl_adjfreq, "Q", "permanent correction per second");
795 SYSCTL_PROC(_kern_ntp, OID_AUTO, delta,
796     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
797     sysctl_delta, "Q", "one-time delta");
798 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, big_delta, CTLFLAG_RD,
799     &ntp_big_delta, sizeof(ntp_big_delta), "Q",
800     "threshold for fast adjustment");
801 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, tick_delta, CTLFLAG_RD,
802     &ntp_tick_delta, sizeof(ntp_tick_delta), "LU",
803     "per-tick adjustment");
804 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, default_tick_delta, CTLFLAG_RD,
805     &ntp_default_tick_delta, sizeof(ntp_default_tick_delta), "LU",
806     "default per-tick adjustment");
807 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, next_leap_second, CTLFLAG_RW,
808     &ntp_leap_second, sizeof(ntp_leap_second), "LU",
809     "next leap second");
810 SYSCTL_INT(_kern_ntp, OID_AUTO, insert_leap_second, CTLFLAG_RW,
811     &ntp_leap_insert, 0, "insert or remove leap second");
812 SYSCTL_PROC(_kern_ntp, OID_AUTO, adjust,
813     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
814     sysctl_adjtime, "Q", "relative adjust for delta");
815
816 /*
817  * Get value of an interval timer.  The process virtual and
818  * profiling virtual time timers are kept in the p_stats area, since
819  * they can be swapped out.  These are kept internally in the
820  * way they are specified externally: in time until they expire.
821  *
822  * The real time interval timer is kept in the process table slot
823  * for the process, and its value (it_value) is kept as an
824  * absolute time rather than as a delta, so that it is easy to keep
825  * periodic real-time signals from drifting.
826  *
827  * Virtual time timers are processed in the hardclock() routine of
828  * kern_clock.c.  The real time timer is processed by a timeout
829  * routine, called from the softclock() routine.  Since a callout
830  * may be delayed in real time due to interrupt processing in the system,
831  * it is possible for the real time timeout routine (realitexpire, given below),
832  * to be delayed in real time past when it is supposed to occur.  It
833  * does not suffice, therefore, to reload the real timer .it_value from the
834  * real time timers .it_interval.  Rather, we compute the next time in
835  * absolute time the timer should go off.
836  *
837  * MPALMOSTSAFE
838  */
839 int
840 sys_getitimer(struct getitimer_args *uap)
841 {
842         struct proc *p = curproc;
843         struct timeval ctv;
844         struct itimerval aitv;
845
846         if (uap->which > ITIMER_PROF)
847                 return (EINVAL);
848         lwkt_gettoken(&p->p_token);
849         if (uap->which == ITIMER_REAL) {
850                 /*
851                  * Convert from absolute to relative time in .it_value
852                  * part of real time timer.  If time for real time timer
853                  * has passed return 0, else return difference between
854                  * current time and time for the timer to go off.
855                  */
856                 aitv = p->p_realtimer;
857                 if (timevalisset(&aitv.it_value)) {
858                         getmicrouptime(&ctv);
859                         if (timevalcmp(&aitv.it_value, &ctv, <))
860                                 timevalclear(&aitv.it_value);
861                         else
862                                 timevalsub(&aitv.it_value, &ctv);
863                 }
864         } else {
865                 aitv = p->p_timer[uap->which];
866         }
867         lwkt_reltoken(&p->p_token);
868         return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
869 }
870
871 /*
872  * MPALMOSTSAFE
873  */
874 int
875 sys_setitimer(struct setitimer_args *uap)
876 {
877         struct itimerval aitv;
878         struct timeval ctv;
879         struct itimerval *itvp;
880         struct proc *p = curproc;
881         int error;
882
883         if (uap->which > ITIMER_PROF)
884                 return (EINVAL);
885         itvp = uap->itv;
886         if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
887             sizeof(struct itimerval))))
888                 return (error);
889         if ((uap->itv = uap->oitv) &&
890             (error = sys_getitimer((struct getitimer_args *)uap)))
891                 return (error);
892         if (itvp == NULL)
893                 return (0);
894         if (itimerfix(&aitv.it_value))
895                 return (EINVAL);
896         if (!timevalisset(&aitv.it_value))
897                 timevalclear(&aitv.it_interval);
898         else if (itimerfix(&aitv.it_interval))
899                 return (EINVAL);
900         lwkt_gettoken(&p->p_token);
901         if (uap->which == ITIMER_REAL) {
902                 if (timevalisset(&p->p_realtimer.it_value))
903                         callout_cancel(&p->p_ithandle);
904                 if (timevalisset(&aitv.it_value)) 
905                         callout_reset(&p->p_ithandle,
906                             tvtohz_high(&aitv.it_value), realitexpire, p);
907                 getmicrouptime(&ctv);
908                 timevaladd(&aitv.it_value, &ctv);
909                 p->p_realtimer = aitv;
910         } else {
911                 p->p_timer[uap->which] = aitv;
912                 switch(uap->which) {
913                 case ITIMER_VIRTUAL:
914                         p->p_flags &= ~P_SIGVTALRM;
915                         break;
916                 case ITIMER_PROF:
917                         p->p_flags &= ~P_SIGPROF;
918                         break;
919                 }
920         }
921         lwkt_reltoken(&p->p_token);
922         return (0);
923 }
924
925 /*
926  * Real interval timer expired:
927  * send process whose timer expired an alarm signal.
928  * If time is not set up to reload, then just return.
929  * Else compute next time timer should go off which is > current time.
930  * This is where delay in processing this timeout causes multiple
931  * SIGALRM calls to be compressed into one.
932  * tvtohz_high() always adds 1 to allow for the time until the next clock
933  * interrupt being strictly less than 1 clock tick, but we don't want
934  * that here since we want to appear to be in sync with the clock
935  * interrupt even when we're delayed.
936  */
937 static
938 void
939 realitexpire(void *arg)
940 {
941         struct proc *p;
942         struct timeval ctv, ntv;
943
944         p = (struct proc *)arg;
945         PHOLD(p);
946         lwkt_gettoken(&p->p_token);
947         ksignal(p, SIGALRM);
948         if (!timevalisset(&p->p_realtimer.it_interval)) {
949                 timevalclear(&p->p_realtimer.it_value);
950                 goto done;
951         }
952         for (;;) {
953                 timevaladd(&p->p_realtimer.it_value,
954                            &p->p_realtimer.it_interval);
955                 getmicrouptime(&ctv);
956                 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
957                         ntv = p->p_realtimer.it_value;
958                         timevalsub(&ntv, &ctv);
959                         callout_reset(&p->p_ithandle, tvtohz_low(&ntv),
960                                       realitexpire, p);
961                         goto done;
962                 }
963         }
964 done:
965         lwkt_reltoken(&p->p_token);
966         PRELE(p);
967 }
968
969 /*
970  * Used to validate itimer timeouts and utimes*() timespecs.
971  */
972 int
973 itimerfix(struct timeval *tv)
974 {
975         if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
976                 return (EINVAL);
977         if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < ustick)
978                 tv->tv_usec = ustick;
979         return (0);
980 }
981
982 /*
983  * Used to validate timeouts and utimes*() timespecs.
984  */
985 int
986 itimespecfix(struct timespec *ts)
987 {
988         if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000ULL)
989                 return (EINVAL);
990         if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < nstick)
991                 ts->tv_nsec = nstick;
992         return (0);
993 }
994
995 /*
996  * Decrement an interval timer by a specified number
997  * of microseconds, which must be less than a second,
998  * i.e. < 1000000.  If the timer expires, then reload
999  * it.  In this case, carry over (usec - old value) to
1000  * reduce the value reloaded into the timer so that
1001  * the timer does not drift.  This routine assumes
1002  * that it is called in a context where the timers
1003  * on which it is operating cannot change in value.
1004  */
1005 int
1006 itimerdecr(struct itimerval *itp, int usec)
1007 {
1008
1009         if (itp->it_value.tv_usec < usec) {
1010                 if (itp->it_value.tv_sec == 0) {
1011                         /* expired, and already in next interval */
1012                         usec -= itp->it_value.tv_usec;
1013                         goto expire;
1014                 }
1015                 itp->it_value.tv_usec += 1000000;
1016                 itp->it_value.tv_sec--;
1017         }
1018         itp->it_value.tv_usec -= usec;
1019         usec = 0;
1020         if (timevalisset(&itp->it_value))
1021                 return (1);
1022         /* expired, exactly at end of interval */
1023 expire:
1024         if (timevalisset(&itp->it_interval)) {
1025                 itp->it_value = itp->it_interval;
1026                 itp->it_value.tv_usec -= usec;
1027                 if (itp->it_value.tv_usec < 0) {
1028                         itp->it_value.tv_usec += 1000000;
1029                         itp->it_value.tv_sec--;
1030                 }
1031         } else
1032                 itp->it_value.tv_usec = 0;              /* sec is already 0 */
1033         return (0);
1034 }
1035
1036 /*
1037  * Add and subtract routines for timevals.
1038  * N.B.: subtract routine doesn't deal with
1039  * results which are before the beginning,
1040  * it just gets very confused in this case.
1041  * Caveat emptor.
1042  */
1043 void
1044 timevaladd(struct timeval *t1, const struct timeval *t2)
1045 {
1046
1047         t1->tv_sec += t2->tv_sec;
1048         t1->tv_usec += t2->tv_usec;
1049         timevalfix(t1);
1050 }
1051
1052 void
1053 timevalsub(struct timeval *t1, const struct timeval *t2)
1054 {
1055
1056         t1->tv_sec -= t2->tv_sec;
1057         t1->tv_usec -= t2->tv_usec;
1058         timevalfix(t1);
1059 }
1060
1061 static void
1062 timevalfix(struct timeval *t1)
1063 {
1064
1065         if (t1->tv_usec < 0) {
1066                 t1->tv_sec--;
1067                 t1->tv_usec += 1000000;
1068         }
1069         if (t1->tv_usec >= 1000000) {
1070                 t1->tv_sec++;
1071                 t1->tv_usec -= 1000000;
1072         }
1073 }
1074
1075 /*
1076  * ratecheck(): simple time-based rate-limit checking.
1077  */
1078 int
1079 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1080 {
1081         struct timeval tv, delta;
1082         int rv = 0;
1083
1084         getmicrouptime(&tv);            /* NB: 10ms precision */
1085         delta = tv;
1086         timevalsub(&delta, lasttime);
1087
1088         /*
1089          * check for 0,0 is so that the message will be seen at least once,
1090          * even if interval is huge.
1091          */
1092         if (timevalcmp(&delta, mininterval, >=) ||
1093             (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1094                 *lasttime = tv;
1095                 rv = 1;
1096         }
1097
1098         return (rv);
1099 }
1100
1101 /*
1102  * ppsratecheck(): packets (or events) per second limitation.
1103  *
1104  * Return 0 if the limit is to be enforced (e.g. the caller
1105  * should drop a packet because of the rate limitation).
1106  *
1107  * maxpps of 0 always causes zero to be returned.  maxpps of -1
1108  * always causes 1 to be returned; this effectively defeats rate
1109  * limiting.
1110  *
1111  * Note that we maintain the struct timeval for compatibility
1112  * with other bsd systems.  We reuse the storage and just monitor
1113  * clock ticks for minimal overhead.  
1114  */
1115 int
1116 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1117 {
1118         int now;
1119
1120         /*
1121          * Reset the last time and counter if this is the first call
1122          * or more than a second has passed since the last update of
1123          * lasttime.
1124          */
1125         now = ticks;
1126         if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1127                 lasttime->tv_sec = now;
1128                 *curpps = 1;
1129                 return (maxpps != 0);
1130         } else {
1131                 (*curpps)++;            /* NB: ignore potential overflow */
1132                 return (maxpps < 0 || *curpps < maxpps);
1133         }
1134 }
1135
1136 static int
1137 sysctl_gettimeofday_quick(SYSCTL_HANDLER_ARGS)
1138 {
1139         int error;
1140         int gtod;
1141
1142         gtod = gettimeofday_quick;
1143         error = sysctl_handle_int(oidp, &gtod, 0, req);
1144         if (error || req->newptr == NULL)
1145                 return error;
1146         gettimeofday_quick = gtod;
1147         if (kpmap)
1148                 kpmap->fast_gtod = gtod;
1149         return 0;
1150 }