Merge from vendor branch OPENSSH:
[dragonfly.git] / sys / kern / kern_clock.c
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * Copyright (c) 1997, 1998 Poul-Henning Kamp <phk@FreeBSD.org>
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  * (c) UNIX System Laboratories, Inc.
38  * All or some portions of this file are derived from material licensed
39  * to the University of California by American Telephone and Telegraph
40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41  * the permission of UNIX System Laboratories, Inc.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *      This product includes software developed by the University of
54  *      California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  *
71  *      @(#)kern_clock.c        8.5 (Berkeley) 1/21/94
72  * $FreeBSD: src/sys/kern/kern_clock.c,v 1.105.2.10 2002/10/17 13:19:40 maxim Exp $
73  * $DragonFly: src/sys/kern/kern_clock.c,v 1.21 2004/07/16 05:51:09 dillon Exp $
74  */
75
76 #include "opt_ntp.h"
77
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/dkstat.h>
81 #include <sys/callout.h>
82 #include <sys/kernel.h>
83 #include <sys/proc.h>
84 #include <sys/malloc.h>
85 #include <sys/resourcevar.h>
86 #include <sys/signalvar.h>
87 #include <sys/timex.h>
88 #include <sys/timepps.h>
89 #include <vm/vm.h>
90 #include <sys/lock.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <sys/sysctl.h>
94 #include <sys/thread2.h>
95
96 #include <machine/cpu.h>
97 #include <machine/limits.h>
98 #include <machine/smp.h>
99
100 #ifdef GPROF
101 #include <sys/gmon.h>
102 #endif
103
104 #ifdef DEVICE_POLLING
105 extern void init_device_poll(void);
106 extern void hardclock_device_poll(void);
107 #endif /* DEVICE_POLLING */
108
109 static void initclocks (void *dummy);
110 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
111
112 /*
113  * Some of these don't belong here, but it's easiest to concentrate them.
114  * Note that cp_time[] counts in microseconds, but most userland programs
115  * just compare relative times against the total by delta.
116  */
117 long cp_time[CPUSTATES];
118
119 SYSCTL_OPAQUE(_kern, OID_AUTO, cp_time, CTLFLAG_RD, &cp_time, sizeof(cp_time),
120     "LU", "CPU time statistics");
121
122 long tk_cancc;
123 long tk_nin;
124 long tk_nout;
125 long tk_rawcc;
126
127 /*
128  * boottime is used to calculate the 'real' uptime.  Do not confuse this with
129  * microuptime().  microtime() is not drift compensated.  The real uptime
130  * with compensation is nanotime() - bootime.  boottime is recalculated
131  * whenever the real time is set based on the compensated elapsed time
132  * in seconds (gd->gd_time_seconds).
133  *
134  * basetime is used to calculate the compensated real time of day.  Chunky
135  * changes to the time, aka settimeofday(), are made by modifying basetime.
136  *
137  * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
138  * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
139  * the real time.
140  */
141 struct timespec boottime;       /* boot time (realtime) for reference only */
142 struct timespec basetime;       /* base time adjusts uptime -> realtime */
143 time_t time_second;             /* read-only 'passive' uptime in seconds */
144
145 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
146     &boottime, timeval, "System boottime");
147 SYSCTL_STRUCT(_kern, OID_AUTO, basetime, CTLFLAG_RD,
148     &basetime, timeval, "System basetime");
149
150 static void hardclock(systimer_t info, struct intrframe *frame);
151 static void statclock(systimer_t info, struct intrframe *frame);
152 static void schedclock(systimer_t info, struct intrframe *frame);
153
154 int     ticks;                  /* system master ticks at hz */
155 int64_t nsec_adj;               /* ntpd per-tick adjustment in nsec << 32 */
156 int64_t nsec_acc;               /* accumulator */
157
158 /*
159  * Finish initializing clock frequencies and start all clocks running.
160  */
161 /* ARGSUSED*/
162 static void
163 initclocks(void *dummy)
164 {
165         cpu_initclocks();
166 #ifdef DEVICE_POLLING
167         init_device_poll();
168 #endif
169         /*psratio = profhz / stathz;*/
170         initclocks_pcpu();
171 }
172
173 /*
174  * Called on a per-cpu basis
175  */
176 void
177 initclocks_pcpu(void)
178 {
179         struct globaldata *gd = mycpu;
180
181         crit_enter();
182         if (gd->gd_cpuid == 0) {
183             gd->gd_time_seconds = 1;
184             gd->gd_cpuclock_base = cputimer_count();
185         } else {
186             /* XXX */
187             gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
188             gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
189         }
190         systimer_init_periodic(&gd->gd_hardclock, hardclock, NULL, hz);
191         systimer_init_periodic(&gd->gd_statclock, statclock, NULL, stathz);
192         /* XXX correct the frequency for scheduler / estcpu tests */
193         systimer_init_periodic(&gd->gd_schedclock, schedclock, 
194                                 NULL, ESTCPUFREQ); 
195         crit_exit();
196 }
197
198 /*
199  * This sets the current real time of day.  Timespecs are in seconds and
200  * nanoseconds.  We do not mess with gd_time_seconds and gd_cpuclock_base,
201  * instead we adjust basetime so basetime + gd_* results in the current
202  * time of day.  This way the gd_* fields are guarenteed to represent
203  * a monotonically increasing 'uptime' value.
204  */
205 void
206 set_timeofday(struct timespec *ts)
207 {
208         struct timespec ts2;
209
210         /*
211          * XXX SMP / non-atomic basetime updates
212          */
213         crit_enter();
214         nanouptime(&ts2);
215         basetime.tv_sec = ts->tv_sec - ts2.tv_sec;
216         basetime.tv_nsec = ts->tv_nsec - ts2.tv_nsec;
217         if (basetime.tv_nsec < 0) {
218             basetime.tv_nsec += 1000000000;
219             --basetime.tv_sec;
220         }
221         boottime.tv_sec = basetime.tv_sec - mycpu->gd_time_seconds;
222         timedelta = 0;
223         crit_exit();
224 }
225         
226 /*
227  * Each cpu has its own hardclock, but we only increments ticks and softticks
228  * on cpu #0.
229  *
230  * NOTE! systimer! the MP lock might not be held here.  We can only safely
231  * manipulate objects owned by the current cpu.
232  */
233 static void
234 hardclock(systimer_t info, struct intrframe *frame)
235 {
236         sysclock_t cputicks;
237         struct proc *p;
238         struct pstats *pstats;
239         struct globaldata *gd = mycpu;
240
241         /*
242          * Realtime updates are per-cpu.  Note that timer corrections as
243          * returned by microtime() and friends make an additional adjustment
244          * using a system-wise 'basetime', but the running time is always
245          * taken from the per-cpu globaldata area.  Since the same clock
246          * is distributing (XXX SMP) to all cpus, the per-cpu timebases
247          * stay in synch.
248          *
249          * Note that we never allow info->time (aka gd->gd_hardclock.time)
250          * to reverse index gd_cpuclock_base.
251          */
252         cputicks = info->time - gd->gd_cpuclock_base;
253         if (cputicks > cputimer_freq) {
254                 ++gd->gd_time_seconds;
255                 gd->gd_cpuclock_base += cputimer_freq;
256         }
257
258         /*
259          * The system-wide ticks and softticks are only updated by cpu #0.
260          * Callwheel actions are also (at the moment) only handled by cpu #0.
261          * Finally, we also do NTP related timedelta/tickdelta adjustments
262          * by adjusting basetime.
263          */
264         if (gd->gd_cpuid == 0) {
265             struct timespec nts;
266             int leap;
267
268             ++ticks;
269
270 #ifdef DEVICE_POLLING
271             hardclock_device_poll();    /* mpsafe, short and quick */
272 #endif /* DEVICE_POLLING */
273
274             if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
275                 setsoftclock();
276             } else if (softticks + 1 == ticks) {
277                 ++softticks;
278             }
279
280 #if 0
281             if (tco->tc_poll_pps) 
282                 tco->tc_poll_pps(tco);
283 #endif
284             /*
285              * Apply adjtime corrections.  At the moment only do this if 
286              * we can get the MP lock to interlock with adjtime's modification
287              * of these variables.  Note that basetime adjustments are not
288              * MP safe either XXX.
289              */
290             if (timedelta != 0 && try_mplock()) {
291                 basetime.tv_nsec += tickdelta * 1000;
292                 if (basetime.tv_nsec >= 1000000000) {
293                     basetime.tv_nsec -= 1000000000;
294                     ++basetime.tv_sec;
295                 } else if (basetime.tv_nsec < 0) {
296                     basetime.tv_nsec += 1000000000;
297                     --basetime.tv_sec;
298                 }
299                 timedelta -= tickdelta;
300                 rel_mplock();
301             }
302
303             /*
304              * Apply per-tick compensation.  ticks_adj adjusts for both
305              * offset and frequency, and could be negative.
306              */
307             if (nsec_adj != 0 && try_mplock()) {
308                 nsec_acc += nsec_adj;
309                 if (nsec_acc >= 0x100000000LL) {
310                     basetime.tv_nsec += nsec_acc >> 32;
311                     nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
312                 } else if (nsec_acc <= -0x100000000LL) {
313                     basetime.tv_nsec -= -nsec_acc >> 32;
314                     nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
315                 }
316                 if (basetime.tv_nsec >= 1000000000) {
317                     basetime.tv_nsec -= 1000000000;
318                     ++basetime.tv_sec;
319                 } else if (basetime.tv_nsec < 0) {
320                     basetime.tv_nsec += 1000000000;
321                     --basetime.tv_sec;
322                 }
323                 rel_mplock();
324             }
325
326             /*
327              * If the realtime-adjusted seconds hand rolls over then tell
328              * ntp_update_second() what we did in the last second so it can
329              * calculate what to do in the next second.  It may also add
330              * or subtract a leap second.
331              */
332             getnanotime(&nts);
333             if (time_second != nts.tv_sec) {
334                 leap = ntp_update_second(time_second, &nsec_adj);
335                 basetime.tv_sec += leap;
336                 time_second = nts.tv_sec + leap;
337                 nsec_adj /= hz;
338             }
339         }
340
341         /*
342          * ITimer handling is per-tick, per-cpu.  I don't think psignal()
343          * is mpsafe on curproc, so XXX get the mplock.
344          */
345         if ((p = curproc) != NULL && try_mplock()) {
346                 pstats = p->p_stats;
347                 if (frame && CLKF_USERMODE(frame) &&
348                     timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
349                     itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
350                         psignal(p, SIGVTALRM);
351                 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
352                     itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
353                         psignal(p, SIGPROF);
354                 rel_mplock();
355         }
356         setdelayed();
357 }
358
359 /*
360  * The statistics clock typically runs at a 125Hz rate, and is intended
361  * to be frequency offset from the hardclock (typ 100Hz).  It is per-cpu.
362  *
363  * NOTE! systimer! the MP lock might not be held here.  We can only safely
364  * manipulate objects owned by the current cpu.
365  *
366  * The stats clock is responsible for grabbing a profiling sample.
367  * Most of the statistics are only used by user-level statistics programs.
368  * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
369  * p->p_estcpu.
370  *
371  * Like the other clocks, the stat clock is called from what is effectively
372  * a fast interrupt, so the context should be the thread/process that got
373  * interrupted.
374  */
375 static void
376 statclock(systimer_t info, struct intrframe *frame)
377 {
378 #ifdef GPROF
379         struct gmonparam *g;
380         int i;
381 #endif
382         thread_t td;
383         struct proc *p;
384         int bump;
385         struct timeval tv;
386         struct timeval *stv;
387
388         /*
389          * How big was our timeslice relative to the last time?
390          */
391         microuptime(&tv);       /* mpsafe */
392         stv = &mycpu->gd_stattv;
393         if (stv->tv_sec == 0) {
394             bump = 1;
395         } else {
396             bump = tv.tv_usec - stv->tv_usec +
397                 (tv.tv_sec - stv->tv_sec) * 1000000;
398             if (bump < 0)
399                 bump = 0;
400             if (bump > 1000000)
401                 bump = 1000000;
402         }
403         *stv = tv;
404
405         td = curthread;
406         p = td->td_proc;
407
408         if (frame && CLKF_USERMODE(frame)) {
409                 /*
410                  * Came from userland, handle user time and deal with
411                  * possible process.
412                  */
413                 if (p && (p->p_flag & P_PROFIL))
414                         addupc_intr(p, CLKF_PC(frame), 1);
415                 td->td_uticks += bump;
416
417                 /*
418                  * Charge the time as appropriate
419                  */
420                 if (p && p->p_nice > NZERO)
421                         cp_time[CP_NICE] += bump;
422                 else
423                         cp_time[CP_USER] += bump;
424         } else {
425 #ifdef GPROF
426                 /*
427                  * Kernel statistics are just like addupc_intr, only easier.
428                  */
429                 g = &_gmonparam;
430                 if (g->state == GMON_PROF_ON && frame) {
431                         i = CLKF_PC(frame) - g->lowpc;
432                         if (i < g->textsize) {
433                                 i /= HISTFRACTION * sizeof(*g->kcount);
434                                 g->kcount[i]++;
435                         }
436                 }
437 #endif
438                 /*
439                  * Came from kernel mode, so we were:
440                  * - handling an interrupt,
441                  * - doing syscall or trap work on behalf of the current
442                  *   user process, or
443                  * - spinning in the idle loop.
444                  * Whichever it is, charge the time as appropriate.
445                  * Note that we charge interrupts to the current process,
446                  * regardless of whether they are ``for'' that process,
447                  * so that we know how much of its real time was spent
448                  * in ``non-process'' (i.e., interrupt) work.
449                  *
450                  * XXX assume system if frame is NULL.  A NULL frame 
451                  * can occur if ipi processing is done from an splx().
452                  */
453                 if (frame && CLKF_INTR(frame))
454                         td->td_iticks += bump;
455                 else
456                         td->td_sticks += bump;
457
458                 if (frame && CLKF_INTR(frame)) {
459                         cp_time[CP_INTR] += bump;
460                 } else {
461                         if (td == &mycpu->gd_idlethread)
462                                 cp_time[CP_IDLE] += bump;
463                         else
464                                 cp_time[CP_SYS] += bump;
465                 }
466         }
467 }
468
469 /*
470  * The scheduler clock typically runs at a 20Hz rate.  NOTE! systimer,
471  * the MP lock might not be held.  We can safely manipulate parts of curproc
472  * but that's about it.
473  */
474 static void
475 schedclock(systimer_t info, struct intrframe *frame)
476 {
477         struct proc *p;
478         struct pstats *pstats;
479         struct rusage *ru;
480         struct vmspace *vm;
481         long rss;
482
483         schedulerclock(NULL);   /* mpsafe */
484         if ((p = curproc) != NULL) {
485                 /* Update resource usage integrals and maximums. */
486                 if ((pstats = p->p_stats) != NULL &&
487                     (ru = &pstats->p_ru) != NULL &&
488                     (vm = p->p_vmspace) != NULL) {
489                         ru->ru_ixrss += pgtok(vm->vm_tsize);
490                         ru->ru_idrss += pgtok(vm->vm_dsize);
491                         ru->ru_isrss += pgtok(vm->vm_ssize);
492                         rss = pgtok(vmspace_resident_count(vm));
493                         if (ru->ru_maxrss < rss)
494                                 ru->ru_maxrss = rss;
495                 }
496         }
497 }
498
499 /*
500  * Compute number of ticks for the specified amount of time.  The 
501  * return value is intended to be used in a clock interrupt timed
502  * operation and guarenteed to meet or exceed the requested time.
503  * If the representation overflows, return INT_MAX.  The minimum return
504  * value is 1 ticks and the function will average the calculation up.
505  * If any value greater then 0 microseconds is supplied, a value
506  * of at least 2 will be returned to ensure that a near-term clock
507  * interrupt does not cause the timeout to occur (degenerately) early.
508  *
509  * Note that limit checks must take into account microseconds, which is
510  * done simply by using the smaller signed long maximum instead of
511  * the unsigned long maximum.
512  *
513  * If ints have 32 bits, then the maximum value for any timeout in
514  * 10ms ticks is 248 days.
515  */
516 int
517 tvtohz_high(struct timeval *tv)
518 {
519         int ticks;
520         long sec, usec;
521
522         sec = tv->tv_sec;
523         usec = tv->tv_usec;
524         if (usec < 0) {
525                 sec--;
526                 usec += 1000000;
527         }
528         if (sec < 0) {
529 #ifdef DIAGNOSTIC
530                 if (usec > 0) {
531                         sec++;
532                         usec -= 1000000;
533                 }
534                 printf("tvotohz: negative time difference %ld sec %ld usec\n",
535                        sec, usec);
536 #endif
537                 ticks = 1;
538         } else if (sec <= INT_MAX / hz) {
539                 ticks = (int)(sec * hz + 
540                             ((u_long)usec + (tick - 1)) / tick) + 1;
541         } else {
542                 ticks = INT_MAX;
543         }
544         return (ticks);
545 }
546
547 /*
548  * Compute number of ticks for the specified amount of time, erroring on
549  * the side of it being too low to ensure that sleeping the returned number
550  * of ticks will not result in a late return.
551  *
552  * The supplied timeval may not be negative and should be normalized.  A
553  * return value of 0 is possible if the timeval converts to less then
554  * 1 tick.
555  *
556  * If ints have 32 bits, then the maximum value for any timeout in
557  * 10ms ticks is 248 days.
558  */
559 int
560 tvtohz_low(struct timeval *tv)
561 {
562         int ticks;
563         long sec;
564
565         sec = tv->tv_sec;
566         if (sec <= INT_MAX / hz)
567                 ticks = (int)(sec * hz + (u_long)tv->tv_usec / tick);
568         else
569                 ticks = INT_MAX;
570         return (ticks);
571 }
572
573
574 /*
575  * Start profiling on a process.
576  *
577  * Kernel profiling passes proc0 which never exits and hence
578  * keeps the profile clock running constantly.
579  */
580 void
581 startprofclock(struct proc *p)
582 {
583         if ((p->p_flag & P_PROFIL) == 0) {
584                 p->p_flag |= P_PROFIL;
585 #if 0   /* XXX */
586                 if (++profprocs == 1 && stathz != 0) {
587                         s = splstatclock();
588                         psdiv = psratio;
589                         setstatclockrate(profhz);
590                         splx(s);
591                 }
592 #endif
593         }
594 }
595
596 /*
597  * Stop profiling on a process.
598  */
599 void
600 stopprofclock(struct proc *p)
601 {
602         if (p->p_flag & P_PROFIL) {
603                 p->p_flag &= ~P_PROFIL;
604 #if 0   /* XXX */
605                 if (--profprocs == 0 && stathz != 0) {
606                         s = splstatclock();
607                         psdiv = 1;
608                         setstatclockrate(stathz);
609                         splx(s);
610                 }
611 #endif
612         }
613 }
614
615 /*
616  * Return information about system clocks.
617  */
618 static int
619 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
620 {
621         struct clockinfo clkinfo;
622         /*
623          * Construct clockinfo structure.
624          */
625         clkinfo.hz = hz;
626         clkinfo.tick = tick;
627         clkinfo.tickadj = tickadj;
628         clkinfo.profhz = profhz;
629         clkinfo.stathz = stathz ? stathz : hz;
630         return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
631 }
632
633 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
634         0, 0, sysctl_kern_clockrate, "S,clockinfo","");
635
636 /*
637  * We have eight functions for looking at the clock, four for
638  * microseconds and four for nanoseconds.  For each there is fast
639  * but less precise version "get{nano|micro}[up]time" which will
640  * return a time which is up to 1/HZ previous to the call, whereas
641  * the raw version "{nano|micro}[up]time" will return a timestamp
642  * which is as precise as possible.  The "up" variants return the
643  * time relative to system boot, these are well suited for time
644  * interval measurements.
645  *
646  * Each cpu independantly maintains the current time of day, so all
647  * we need to do to protect ourselves from changes is to do a loop
648  * check on the seconds field changing out from under us.
649  */
650 void
651 getmicrouptime(struct timeval *tvp)
652 {
653         struct globaldata *gd = mycpu;
654         sysclock_t delta;
655
656         do {
657                 tvp->tv_sec = gd->gd_time_seconds;
658                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
659         } while (tvp->tv_sec != gd->gd_time_seconds);
660         tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
661         if (tvp->tv_usec >= 1000000) {
662                 tvp->tv_usec -= 1000000;
663                 ++tvp->tv_sec;
664         }
665 }
666
667 void
668 getnanouptime(struct timespec *tsp)
669 {
670         struct globaldata *gd = mycpu;
671         sysclock_t delta;
672
673         do {
674                 tsp->tv_sec = gd->gd_time_seconds;
675                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
676         } while (tsp->tv_sec != gd->gd_time_seconds);
677         tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
678         if (tsp->tv_nsec >= 1000000000) {
679                 tsp->tv_nsec -= 1000000000;
680                 ++tsp->tv_sec;
681         }
682 }
683
684 void
685 microuptime(struct timeval *tvp)
686 {
687         struct globaldata *gd = mycpu;
688         sysclock_t delta;
689
690         do {
691                 tvp->tv_sec = gd->gd_time_seconds;
692                 delta = cputimer_count() - gd->gd_cpuclock_base;
693         } while (tvp->tv_sec != gd->gd_time_seconds);
694         tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
695         if (tvp->tv_usec >= 1000000) {
696                 tvp->tv_usec -= 1000000;
697                 ++tvp->tv_sec;
698         }
699 }
700
701 void
702 nanouptime(struct timespec *tsp)
703 {
704         struct globaldata *gd = mycpu;
705         sysclock_t delta;
706
707         do {
708                 tsp->tv_sec = gd->gd_time_seconds;
709                 delta = cputimer_count() - gd->gd_cpuclock_base;
710         } while (tsp->tv_sec != gd->gd_time_seconds);
711         tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
712         if (tsp->tv_nsec >= 1000000000) {
713                 tsp->tv_nsec -= 1000000000;
714                 ++tsp->tv_sec;
715         }
716 }
717
718 /*
719  * realtime routines
720  */
721
722 void
723 getmicrotime(struct timeval *tvp)
724 {
725         struct globaldata *gd = mycpu;
726         sysclock_t delta;
727
728         do {
729                 tvp->tv_sec = gd->gd_time_seconds;
730                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
731         } while (tvp->tv_sec != gd->gd_time_seconds);
732         tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
733
734         tvp->tv_sec += basetime.tv_sec;
735         tvp->tv_usec += basetime.tv_nsec / 1000;
736         while (tvp->tv_usec >= 1000000) {
737                 tvp->tv_usec -= 1000000;
738                 ++tvp->tv_sec;
739         }
740 }
741
742 void
743 getnanotime(struct timespec *tsp)
744 {
745         struct globaldata *gd = mycpu;
746         sysclock_t delta;
747
748         do {
749                 tsp->tv_sec = gd->gd_time_seconds;
750                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
751         } while (tsp->tv_sec != gd->gd_time_seconds);
752         tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
753
754         tsp->tv_sec += basetime.tv_sec;
755         tsp->tv_nsec += basetime.tv_nsec;
756         while (tsp->tv_nsec >= 1000000000) {
757                 tsp->tv_nsec -= 1000000000;
758                 ++tsp->tv_sec;
759         }
760 }
761
762 void
763 microtime(struct timeval *tvp)
764 {
765         struct globaldata *gd = mycpu;
766         sysclock_t delta;
767
768         do {
769                 tvp->tv_sec = gd->gd_time_seconds;
770                 delta = cputimer_count() - gd->gd_cpuclock_base;
771         } while (tvp->tv_sec != gd->gd_time_seconds);
772         tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
773
774         tvp->tv_sec += basetime.tv_sec;
775         tvp->tv_usec += basetime.tv_nsec / 1000;
776         while (tvp->tv_usec >= 1000000) {
777                 tvp->tv_usec -= 1000000;
778                 ++tvp->tv_sec;
779         }
780 }
781
782 void
783 nanotime(struct timespec *tsp)
784 {
785         struct globaldata *gd = mycpu;
786         sysclock_t delta;
787
788         do {
789                 tsp->tv_sec = gd->gd_time_seconds;
790                 delta = cputimer_count() - gd->gd_cpuclock_base;
791         } while (tsp->tv_sec != gd->gd_time_seconds);
792         tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
793
794         tsp->tv_sec += basetime.tv_sec;
795         tsp->tv_nsec += basetime.tv_nsec;
796         while (tsp->tv_nsec >= 1000000000) {
797                 tsp->tv_nsec -= 1000000000;
798                 ++tsp->tv_sec;
799         }
800 }
801
802 int
803 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
804 {
805         pps_params_t *app;
806         struct pps_fetch_args *fapi;
807 #ifdef PPS_SYNC
808         struct pps_kcbind_args *kapi;
809 #endif
810
811         switch (cmd) {
812         case PPS_IOC_CREATE:
813                 return (0);
814         case PPS_IOC_DESTROY:
815                 return (0);
816         case PPS_IOC_SETPARAMS:
817                 app = (pps_params_t *)data;
818                 if (app->mode & ~pps->ppscap)
819                         return (EINVAL);
820                 pps->ppsparam = *app;         
821                 return (0);
822         case PPS_IOC_GETPARAMS:
823                 app = (pps_params_t *)data;
824                 *app = pps->ppsparam;
825                 app->api_version = PPS_API_VERS_1;
826                 return (0);
827         case PPS_IOC_GETCAP:
828                 *(int*)data = pps->ppscap;
829                 return (0);
830         case PPS_IOC_FETCH:
831                 fapi = (struct pps_fetch_args *)data;
832                 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
833                         return (EINVAL);
834                 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
835                         return (EOPNOTSUPP);
836                 pps->ppsinfo.current_mode = pps->ppsparam.mode;         
837                 fapi->pps_info_buf = pps->ppsinfo;
838                 return (0);
839         case PPS_IOC_KCBIND:
840 #ifdef PPS_SYNC
841                 kapi = (struct pps_kcbind_args *)data;
842                 /* XXX Only root should be able to do this */
843                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
844                         return (EINVAL);
845                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
846                         return (EINVAL);
847                 if (kapi->edge & ~pps->ppscap)
848                         return (EINVAL);
849                 pps->kcmode = kapi->edge;
850                 return (0);
851 #else
852                 return (EOPNOTSUPP);
853 #endif
854         default:
855                 return (ENOTTY);
856         }
857 }
858
859 void
860 pps_init(struct pps_state *pps)
861 {
862         pps->ppscap |= PPS_TSFMT_TSPEC;
863         if (pps->ppscap & PPS_CAPTUREASSERT)
864                 pps->ppscap |= PPS_OFFSETASSERT;
865         if (pps->ppscap & PPS_CAPTURECLEAR)
866                 pps->ppscap |= PPS_OFFSETCLEAR;
867 }
868
869 void
870 pps_event(struct pps_state *pps, sysclock_t count, int event)
871 {
872         struct globaldata *gd;
873         struct timespec *tsp;
874         struct timespec *osp;
875         struct timespec ts;
876         sysclock_t *pcount;
877 #ifdef PPS_SYNC
878         sysclock_t tcount;
879 #endif
880         sysclock_t delta;
881         pps_seq_t *pseq;
882         int foff;
883         int fhard;
884
885         gd = mycpu;
886
887         /* Things would be easier with arrays... */
888         if (event == PPS_CAPTUREASSERT) {
889                 tsp = &pps->ppsinfo.assert_timestamp;
890                 osp = &pps->ppsparam.assert_offset;
891                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
892                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
893                 pcount = &pps->ppscount[0];
894                 pseq = &pps->ppsinfo.assert_sequence;
895         } else {
896                 tsp = &pps->ppsinfo.clear_timestamp;
897                 osp = &pps->ppsparam.clear_offset;
898                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
899                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
900                 pcount = &pps->ppscount[1];
901                 pseq = &pps->ppsinfo.clear_sequence;
902         }
903
904         /* Nothing really happened */
905         if (*pcount == count)
906                 return;
907
908         *pcount = count;
909
910         do {
911                 ts.tv_sec = gd->gd_time_seconds;
912                 delta = count - gd->gd_cpuclock_base;
913         } while (ts.tv_sec != gd->gd_time_seconds);
914         if (delta > cputimer_freq) {
915                 ts.tv_sec += delta / cputimer_freq;
916                 delta %= cputimer_freq;
917         }
918         ts.tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
919         ts.tv_sec += basetime.tv_sec;
920         ts.tv_nsec += basetime.tv_nsec;
921         while (ts.tv_nsec >= 1000000000) {
922                 ts.tv_nsec -= 1000000000;
923                 ++ts.tv_sec;
924         }
925
926         (*pseq)++;
927         *tsp = ts;
928
929         if (foff) {
930                 timespecadd(tsp, osp);
931                 if (tsp->tv_nsec < 0) {
932                         tsp->tv_nsec += 1000000000;
933                         tsp->tv_sec -= 1;
934                 }
935         }
936 #ifdef PPS_SYNC
937         if (fhard) {
938                 /* magic, at its best... */
939                 tcount = count - pps->ppscount[2];
940                 pps->ppscount[2] = count;
941                 delta = (cputimer_freq64_nsec * tcount) >> 32;
942                 hardpps(tsp, delta);
943         }
944 #endif
945 }
946