Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / kern / kern_clock.c
1 /*-
2  * Copyright (c) 1997, 1998 Poul-Henning Kamp <phk@FreeBSD.org>
3  * Copyright (c) 1982, 1986, 1991, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  * (c) UNIX System Laboratories, Inc.
6  * All or some portions of this file are derived from material licensed
7  * to the University of California by American Telephone and Telegraph
8  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
9  * the permission of UNIX System Laboratories, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  *      @(#)kern_clock.c        8.5 (Berkeley) 1/21/94
40  * $FreeBSD: src/sys/kern/kern_clock.c,v 1.105.2.10 2002/10/17 13:19:40 maxim Exp $
41  * $DragonFly: src/sys/kern/kern_clock.c,v 1.2 2003/06/17 04:28:41 dillon Exp $
42  */
43
44 #include "opt_ntp.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/dkstat.h>
49 #include <sys/callout.h>
50 #include <sys/kernel.h>
51 #include <sys/proc.h>
52 #include <sys/malloc.h>
53 #include <sys/resourcevar.h>
54 #include <sys/signalvar.h>
55 #include <sys/timex.h>
56 #include <sys/timepps.h>
57 #include <vm/vm.h>
58 #include <sys/lock.h>
59 #include <vm/pmap.h>
60 #include <vm/vm_map.h>
61 #include <sys/sysctl.h>
62
63 #include <machine/cpu.h>
64 #include <machine/limits.h>
65 #include <machine/smp.h>
66
67 #ifdef GPROF
68 #include <sys/gmon.h>
69 #endif
70
71 #ifdef DEVICE_POLLING
72 extern void init_device_poll(void);
73 extern void hardclock_device_poll(void);
74 #endif /* DEVICE_POLLING */
75
76 /*
77  * Number of timecounters used to implement stable storage
78  */
79 #ifndef NTIMECOUNTER
80 #define NTIMECOUNTER    5
81 #endif
82
83 static MALLOC_DEFINE(M_TIMECOUNTER, "timecounter", 
84         "Timecounter stable storage");
85
86 static void initclocks __P((void *dummy));
87 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
88
89 static void tco_forward __P((int force));
90 static void tco_setscales __P((struct timecounter *tc));
91 static __inline unsigned tco_delta __P((struct timecounter *tc));
92
93 /* Some of these don't belong here, but it's easiest to concentrate them. */
94 long cp_time[CPUSTATES];
95
96 SYSCTL_OPAQUE(_kern, OID_AUTO, cp_time, CTLFLAG_RD, &cp_time, sizeof(cp_time),
97     "LU", "CPU time statistics");
98
99 long tk_cancc;
100 long tk_nin;
101 long tk_nout;
102 long tk_rawcc;
103
104 time_t time_second;
105
106 struct  timeval boottime;
107 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
108     &boottime, timeval, "System boottime");
109
110 /*
111  * Which update policy to use.
112  *   0 - every tick, bad hardware may fail with "calcru negative..."
113  *   1 - more resistent to the above hardware, but less efficient.
114  */
115 static int tco_method;
116
117 /*
118  * Implement a dummy timecounter which we can use until we get a real one
119  * in the air.  This allows the console and other early stuff to use
120  * timeservices.
121  */
122
123 static unsigned 
124 dummy_get_timecount(struct timecounter *tc)
125 {
126         static unsigned now;
127         return (++now);
128 }
129
130 static struct timecounter dummy_timecounter = {
131         dummy_get_timecount,
132         0,
133         ~0u,
134         1000000,
135         "dummy"
136 };
137
138 struct timecounter *timecounter = &dummy_timecounter;
139
140 /*
141  * Clock handling routines.
142  *
143  * This code is written to operate with two timers that run independently of
144  * each other.
145  *
146  * The main timer, running hz times per second, is used to trigger interval
147  * timers, timeouts and rescheduling as needed.
148  *
149  * The second timer handles kernel and user profiling,
150  * and does resource use estimation.  If the second timer is programmable,
151  * it is randomized to avoid aliasing between the two clocks.  For example,
152  * the randomization prevents an adversary from always giving up the cpu
153  * just before its quantum expires.  Otherwise, it would never accumulate
154  * cpu ticks.  The mean frequency of the second timer is stathz.
155  *
156  * If no second timer exists, stathz will be zero; in this case we drive
157  * profiling and statistics off the main clock.  This WILL NOT be accurate;
158  * do not do it unless absolutely necessary.
159  *
160  * The statistics clock may (or may not) be run at a higher rate while
161  * profiling.  This profile clock runs at profhz.  We require that profhz
162  * be an integral multiple of stathz.
163  *
164  * If the statistics clock is running fast, it must be divided by the ratio
165  * profhz/stathz for statistics.  (For profiling, every tick counts.)
166  *
167  * Time-of-day is maintained using a "timecounter", which may or may
168  * not be related to the hardware generating the above mentioned
169  * interrupts.
170  */
171
172 int     stathz;
173 int     profhz;
174 static int profprocs;
175 int     ticks;
176 static int psdiv, pscnt;                /* prof => stat divider */
177 int     psratio;                        /* ratio: prof / stat */
178
179 /*
180  * Initialize clock frequencies and start both clocks running.
181  */
182 /* ARGSUSED*/
183 static void
184 initclocks(dummy)
185         void *dummy;
186 {
187         register int i;
188
189         /*
190          * Set divisors to 1 (normal case) and let the machine-specific
191          * code do its bit.
192          */
193         psdiv = pscnt = 1;
194         cpu_initclocks();
195
196 #ifdef DEVICE_POLLING
197         init_device_poll();
198 #endif
199
200         /*
201          * Compute profhz/stathz, and fix profhz if needed.
202          */
203         i = stathz ? stathz : hz;
204         if (profhz == 0)
205                 profhz = i;
206         psratio = profhz / i;
207 }
208
209 /*
210  * The real-time timer, interrupting hz times per second.
211  */
212 void
213 hardclock(frame)
214         register struct clockframe *frame;
215 {
216         register struct proc *p;
217
218         p = curproc;
219         if (p) {
220                 register struct pstats *pstats;
221
222                 /*
223                  * Run current process's virtual and profile time, as needed.
224                  */
225                 pstats = p->p_stats;
226                 if (CLKF_USERMODE(frame) &&
227                     timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
228                     itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
229                         psignal(p, SIGVTALRM);
230                 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
231                     itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
232                         psignal(p, SIGPROF);
233         }
234
235 #if defined(SMP) && defined(BETTER_CLOCK)
236         forward_hardclock(pscnt);
237 #endif
238
239         /*
240          * If no separate statistics clock is available, run it from here.
241          */
242         if (stathz == 0)
243                 statclock(frame);
244
245         tco_forward(0);
246         ticks++;
247
248 #ifdef DEVICE_POLLING
249         hardclock_device_poll();        /* this is very short and quick */
250 #endif /* DEVICE_POLLING */
251
252         /*
253          * Process callouts at a very low cpu priority, so we don't keep the
254          * relatively high clock interrupt priority any longer than necessary.
255          */
256         if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
257                 if (CLKF_BASEPRI(frame)) {
258                         /*
259                          * Save the overhead of a software interrupt;
260                          * it will happen as soon as we return, so do it now.
261                          */
262                         (void)splsoftclock();
263                         softclock();
264                 } else
265                         setsoftclock();
266         } else if (softticks + 1 == ticks)
267                 ++softticks;
268 }
269
270 /*
271  * Compute number of ticks in the specified amount of time.
272  */
273 int
274 tvtohz(tv)
275         struct timeval *tv;
276 {
277         register unsigned long ticks;
278         register long sec, usec;
279
280         /*
281          * If the number of usecs in the whole seconds part of the time
282          * difference fits in a long, then the total number of usecs will
283          * fit in an unsigned long.  Compute the total and convert it to
284          * ticks, rounding up and adding 1 to allow for the current tick
285          * to expire.  Rounding also depends on unsigned long arithmetic
286          * to avoid overflow.
287          *
288          * Otherwise, if the number of ticks in the whole seconds part of
289          * the time difference fits in a long, then convert the parts to
290          * ticks separately and add, using similar rounding methods and
291          * overflow avoidance.  This method would work in the previous
292          * case but it is slightly slower and assumes that hz is integral.
293          *
294          * Otherwise, round the time difference down to the maximum
295          * representable value.
296          *
297          * If ints have 32 bits, then the maximum value for any timeout in
298          * 10ms ticks is 248 days.
299          */
300         sec = tv->tv_sec;
301         usec = tv->tv_usec;
302         if (usec < 0) {
303                 sec--;
304                 usec += 1000000;
305         }
306         if (sec < 0) {
307 #ifdef DIAGNOSTIC
308                 if (usec > 0) {
309                         sec++;
310                         usec -= 1000000;
311                 }
312                 printf("tvotohz: negative time difference %ld sec %ld usec\n",
313                        sec, usec);
314 #endif
315                 ticks = 1;
316         } else if (sec <= LONG_MAX / 1000000)
317                 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
318                         / tick + 1;
319         else if (sec <= LONG_MAX / hz)
320                 ticks = sec * hz
321                         + ((unsigned long)usec + (tick - 1)) / tick + 1;
322         else
323                 ticks = LONG_MAX;
324         if (ticks > INT_MAX)
325                 ticks = INT_MAX;
326         return ((int)ticks);
327 }
328
329 /*
330  * Start profiling on a process.
331  *
332  * Kernel profiling passes proc0 which never exits and hence
333  * keeps the profile clock running constantly.
334  */
335 void
336 startprofclock(p)
337         register struct proc *p;
338 {
339         int s;
340
341         if ((p->p_flag & P_PROFIL) == 0) {
342                 p->p_flag |= P_PROFIL;
343                 if (++profprocs == 1 && stathz != 0) {
344                         s = splstatclock();
345                         psdiv = pscnt = psratio;
346                         setstatclockrate(profhz);
347                         splx(s);
348                 }
349         }
350 }
351
352 /*
353  * Stop profiling on a process.
354  */
355 void
356 stopprofclock(p)
357         register struct proc *p;
358 {
359         int s;
360
361         if (p->p_flag & P_PROFIL) {
362                 p->p_flag &= ~P_PROFIL;
363                 if (--profprocs == 0 && stathz != 0) {
364                         s = splstatclock();
365                         psdiv = pscnt = 1;
366                         setstatclockrate(stathz);
367                         splx(s);
368                 }
369         }
370 }
371
372 /*
373  * Statistics clock.  Grab profile sample, and if divider reaches 0,
374  * do process and kernel statistics.  Most of the statistics are only
375  * used by user-level statistics programs.  The main exceptions are
376  * p->p_uticks, p->p_sticks, p->p_iticks, and p->p_estcpu.
377  */
378 void
379 statclock(frame)
380         register struct clockframe *frame;
381 {
382 #ifdef GPROF
383         register struct gmonparam *g;
384         int i;
385 #endif
386         register struct proc *p;
387         struct pstats *pstats;
388         long rss;
389         struct rusage *ru;
390         struct vmspace *vm;
391
392         if (curproc != NULL && CLKF_USERMODE(frame)) {
393                 /*
394                  * Came from user mode; CPU was in user state.
395                  * If this process is being profiled, record the tick.
396                  */
397                 p = curproc;
398                 if (p->p_flag & P_PROFIL)
399                         addupc_intr(p, CLKF_PC(frame), 1);
400 #if defined(SMP) && defined(BETTER_CLOCK)
401                 if (stathz != 0)
402                         forward_statclock(pscnt);
403 #endif
404                 if (--pscnt > 0)
405                         return;
406                 /*
407                  * Charge the time as appropriate.
408                  */
409                 p->p_uticks++;
410                 if (p->p_nice > NZERO)
411                         cp_time[CP_NICE]++;
412                 else
413                         cp_time[CP_USER]++;
414         } else {
415 #ifdef GPROF
416                 /*
417                  * Kernel statistics are just like addupc_intr, only easier.
418                  */
419                 g = &_gmonparam;
420                 if (g->state == GMON_PROF_ON) {
421                         i = CLKF_PC(frame) - g->lowpc;
422                         if (i < g->textsize) {
423                                 i /= HISTFRACTION * sizeof(*g->kcount);
424                                 g->kcount[i]++;
425                         }
426                 }
427 #endif
428 #if defined(SMP) && defined(BETTER_CLOCK)
429                 if (stathz != 0)
430                         forward_statclock(pscnt);
431 #endif
432                 if (--pscnt > 0)
433                         return;
434                 /*
435                  * Came from kernel mode, so we were:
436                  * - handling an interrupt,
437                  * - doing syscall or trap work on behalf of the current
438                  *   user process, or
439                  * - spinning in the idle loop.
440                  * Whichever it is, charge the time as appropriate.
441                  * Note that we charge interrupts to the current process,
442                  * regardless of whether they are ``for'' that process,
443                  * so that we know how much of its real time was spent
444                  * in ``non-process'' (i.e., interrupt) work.
445                  */
446                 p = curproc;
447                 if (CLKF_INTR(frame)) {
448                         if (p != NULL)
449                                 p->p_iticks++;
450                         cp_time[CP_INTR]++;
451                 } else if (p != NULL) {
452                         p->p_sticks++;
453                         cp_time[CP_SYS]++;
454                 } else
455                         cp_time[CP_IDLE]++;
456         }
457         pscnt = psdiv;
458
459         if (p != NULL) {
460                 schedclock(p);
461
462                 /* Update resource usage integrals and maximums. */
463                 if ((pstats = p->p_stats) != NULL &&
464                     (ru = &pstats->p_ru) != NULL &&
465                     (vm = p->p_vmspace) != NULL) {
466                         ru->ru_ixrss += pgtok(vm->vm_tsize);
467                         ru->ru_idrss += pgtok(vm->vm_dsize);
468                         ru->ru_isrss += pgtok(vm->vm_ssize);
469                         rss = pgtok(vmspace_resident_count(vm));
470                         if (ru->ru_maxrss < rss)
471                                 ru->ru_maxrss = rss;
472                 }
473         }
474 }
475
476 /*
477  * Return information about system clocks.
478  */
479 static int
480 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
481 {
482         struct clockinfo clkinfo;
483         /*
484          * Construct clockinfo structure.
485          */
486         clkinfo.hz = hz;
487         clkinfo.tick = tick;
488         clkinfo.tickadj = tickadj;
489         clkinfo.profhz = profhz;
490         clkinfo.stathz = stathz ? stathz : hz;
491         return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
492 }
493
494 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
495         0, 0, sysctl_kern_clockrate, "S,clockinfo","");
496
497 static __inline unsigned
498 tco_delta(struct timecounter *tc)
499 {
500
501         return ((tc->tc_get_timecount(tc) - tc->tc_offset_count) & 
502             tc->tc_counter_mask);
503 }
504
505 /*
506  * We have eight functions for looking at the clock, four for
507  * microseconds and four for nanoseconds.  For each there is fast
508  * but less precise version "get{nano|micro}[up]time" which will
509  * return a time which is up to 1/HZ previous to the call, whereas
510  * the raw version "{nano|micro}[up]time" will return a timestamp
511  * which is as precise as possible.  The "up" variants return the
512  * time relative to system boot, these are well suited for time
513  * interval measurements.
514  */
515
516 void
517 getmicrotime(struct timeval *tvp)
518 {
519         struct timecounter *tc;
520
521         if (!tco_method) {
522                 tc = timecounter;
523                 *tvp = tc->tc_microtime;
524         } else {
525                 microtime(tvp);
526         }
527 }
528
529 void
530 getnanotime(struct timespec *tsp)
531 {
532         struct timecounter *tc;
533
534         if (!tco_method) {
535                 tc = timecounter;
536                 *tsp = tc->tc_nanotime;
537         } else {
538                 nanotime(tsp);
539         }
540 }
541
542 void
543 microtime(struct timeval *tv)
544 {
545         struct timecounter *tc;
546
547         tc = timecounter;
548         tv->tv_sec = tc->tc_offset_sec;
549         tv->tv_usec = tc->tc_offset_micro;
550         tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
551         tv->tv_usec += boottime.tv_usec;
552         tv->tv_sec += boottime.tv_sec;
553         while (tv->tv_usec < 0) {
554                 tv->tv_usec += 1000000;
555                 if (tv->tv_sec > 0)
556                         tv->tv_sec--;
557         }
558         while (tv->tv_usec >= 1000000) {
559                 tv->tv_usec -= 1000000;
560                 tv->tv_sec++;
561         }
562 }
563
564 void
565 nanotime(struct timespec *ts)
566 {
567         unsigned count;
568         u_int64_t delta;
569         struct timecounter *tc;
570
571         tc = timecounter;
572         ts->tv_sec = tc->tc_offset_sec;
573         count = tco_delta(tc);
574         delta = tc->tc_offset_nano;
575         delta += ((u_int64_t)count * tc->tc_scale_nano_f);
576         delta >>= 32;
577         delta += ((u_int64_t)count * tc->tc_scale_nano_i);
578         delta += boottime.tv_usec * 1000;
579         ts->tv_sec += boottime.tv_sec;
580         while (delta < 0) {
581                 delta += 1000000000;
582                 if (ts->tv_sec > 0)
583                         ts->tv_sec--;
584         }
585         while (delta >= 1000000000) {
586                 delta -= 1000000000;
587                 ts->tv_sec++;
588         }
589         ts->tv_nsec = delta;
590 }
591
592 void
593 getmicrouptime(struct timeval *tvp)
594 {
595         struct timecounter *tc;
596
597         if (!tco_method) {
598                 tc = timecounter;
599                 tvp->tv_sec = tc->tc_offset_sec;
600                 tvp->tv_usec = tc->tc_offset_micro;
601         } else {
602                 microuptime(tvp);
603         }
604 }
605
606 void
607 getnanouptime(struct timespec *tsp)
608 {
609         struct timecounter *tc;
610
611         if (!tco_method) {
612                 tc = timecounter;
613                 tsp->tv_sec = tc->tc_offset_sec;
614                 tsp->tv_nsec = tc->tc_offset_nano >> 32;
615         } else {
616                 nanouptime(tsp);
617         }
618 }
619
620 void
621 microuptime(struct timeval *tv)
622 {
623         struct timecounter *tc;
624
625         tc = timecounter;
626         tv->tv_sec = tc->tc_offset_sec;
627         tv->tv_usec = tc->tc_offset_micro;
628         tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
629         while (tv->tv_usec < 0) {
630                 tv->tv_usec += 1000000;
631                 if (tv->tv_sec > 0)
632                         tv->tv_sec--;
633         }
634         while (tv->tv_usec >= 1000000) {
635                 tv->tv_usec -= 1000000;
636                 tv->tv_sec++;
637         }
638 }
639
640 void
641 nanouptime(struct timespec *ts)
642 {
643         unsigned count;
644         u_int64_t delta;
645         struct timecounter *tc;
646
647         tc = timecounter;
648         ts->tv_sec = tc->tc_offset_sec;
649         count = tco_delta(tc);
650         delta = tc->tc_offset_nano;
651         delta += ((u_int64_t)count * tc->tc_scale_nano_f);
652         delta >>= 32;
653         delta += ((u_int64_t)count * tc->tc_scale_nano_i);
654         while (delta < 0) {
655                 delta += 1000000000;
656                 if (ts->tv_sec > 0)
657                         ts->tv_sec--;
658         }
659         while (delta >= 1000000000) {
660                 delta -= 1000000000;
661                 ts->tv_sec++;
662         }
663         ts->tv_nsec = delta;
664 }
665
666 static void
667 tco_setscales(struct timecounter *tc)
668 {
669         u_int64_t scale;
670
671         scale = 1000000000LL << 32;
672         scale += tc->tc_adjustment;
673         scale /= tc->tc_tweak->tc_frequency;
674         tc->tc_scale_micro = scale / 1000;
675         tc->tc_scale_nano_f = scale & 0xffffffff;
676         tc->tc_scale_nano_i = scale >> 32;
677 }
678
679 void
680 update_timecounter(struct timecounter *tc)
681 {
682         tco_setscales(tc);
683 }
684
685 void
686 init_timecounter(struct timecounter *tc)
687 {
688         struct timespec ts1;
689         struct timecounter *t1, *t2, *t3;
690         unsigned u;
691         int i;
692
693         u = tc->tc_frequency / tc->tc_counter_mask;
694         if (u > hz) {
695                 printf("Timecounter \"%s\" frequency %lu Hz"
696                        " -- Insufficient hz, needs at least %u\n",
697                        tc->tc_name, (u_long) tc->tc_frequency, u);
698                 return;
699         }
700
701         tc->tc_adjustment = 0;
702         tc->tc_tweak = tc;
703         tco_setscales(tc);
704         tc->tc_offset_count = tc->tc_get_timecount(tc);
705         if (timecounter == &dummy_timecounter)
706                 tc->tc_avail = tc;
707         else {
708                 tc->tc_avail = timecounter->tc_tweak->tc_avail;
709                 timecounter->tc_tweak->tc_avail = tc;
710         }
711         MALLOC(t1, struct timecounter *, sizeof *t1, M_TIMECOUNTER, M_WAITOK);
712         tc->tc_other = t1;
713         *t1 = *tc;
714         t2 = t1;
715         for (i = 1; i < NTIMECOUNTER; i++) {
716                 MALLOC(t3, struct timecounter *, sizeof *t3,
717                     M_TIMECOUNTER, M_WAITOK);
718                 *t3 = *tc;
719                 t3->tc_other = t2;
720                 t2 = t3;
721         }
722         t1->tc_other = t3;
723         tc = t1;
724
725         printf("Timecounter \"%s\"  frequency %lu Hz\n", 
726             tc->tc_name, (u_long)tc->tc_frequency);
727
728         /* XXX: For now always start using the counter. */
729         tc->tc_offset_count = tc->tc_get_timecount(tc);
730         nanouptime(&ts1);
731         tc->tc_offset_nano = (u_int64_t)ts1.tv_nsec << 32;
732         tc->tc_offset_micro = ts1.tv_nsec / 1000;
733         tc->tc_offset_sec = ts1.tv_sec;
734         timecounter = tc;
735 }
736
737 void
738 set_timecounter(struct timespec *ts)
739 {
740         struct timespec ts2;
741
742         nanouptime(&ts2);
743         boottime.tv_sec = ts->tv_sec - ts2.tv_sec;
744         boottime.tv_usec = (ts->tv_nsec - ts2.tv_nsec) / 1000;
745         if (boottime.tv_usec < 0) {
746                 boottime.tv_usec += 1000000;
747                 boottime.tv_sec--;
748         }
749         /* fiddle all the little crinkly bits around the fiords... */
750         tco_forward(1);
751 }
752
753 static void
754 switch_timecounter(struct timecounter *newtc)
755 {
756         int s;
757         struct timecounter *tc;
758         struct timespec ts;
759
760         s = splclock();
761         tc = timecounter;
762         if (newtc->tc_tweak == tc->tc_tweak) {
763                 splx(s);
764                 return;
765         }
766         newtc = newtc->tc_tweak->tc_other;
767         nanouptime(&ts);
768         newtc->tc_offset_sec = ts.tv_sec;
769         newtc->tc_offset_nano = (u_int64_t)ts.tv_nsec << 32;
770         newtc->tc_offset_micro = ts.tv_nsec / 1000;
771         newtc->tc_offset_count = newtc->tc_get_timecount(newtc);
772         tco_setscales(newtc);
773         timecounter = newtc;
774         splx(s);
775 }
776
777 static struct timecounter *
778 sync_other_counter(void)
779 {
780         struct timecounter *tc, *tcn, *tco;
781         unsigned delta;
782
783         tco = timecounter;
784         tc = tco->tc_other;
785         tcn = tc->tc_other;
786         *tc = *tco;
787         tc->tc_other = tcn;
788         delta = tco_delta(tc);
789         tc->tc_offset_count += delta;
790         tc->tc_offset_count &= tc->tc_counter_mask;
791         tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_f;
792         tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_i << 32;
793         return (tc);
794 }
795
796 static void
797 tco_forward(int force)
798 {
799         struct timecounter *tc, *tco;
800         struct timeval tvt;
801
802         tco = timecounter;
803         tc = sync_other_counter();
804         /*
805          * We may be inducing a tiny error here, the tc_poll_pps() may
806          * process a latched count which happens after the tco_delta()
807          * in sync_other_counter(), which would extend the previous
808          * counters parameters into the domain of this new one.
809          * Since the timewindow is very small for this, the error is
810          * going to be only a few weenieseconds (as Dave Mills would
811          * say), so lets just not talk more about it, OK ?
812          */
813         if (tco->tc_poll_pps) 
814                 tco->tc_poll_pps(tco);
815         if (timedelta != 0) {
816                 tvt = boottime;
817                 tvt.tv_usec += tickdelta;
818                 if (tvt.tv_usec >= 1000000) {
819                         tvt.tv_sec++;
820                         tvt.tv_usec -= 1000000;
821                 } else if (tvt.tv_usec < 0) {
822                         tvt.tv_sec--;
823                         tvt.tv_usec += 1000000;
824                 }
825                 boottime = tvt;
826                 timedelta -= tickdelta;
827         }
828
829         while (tc->tc_offset_nano >= 1000000000ULL << 32) {
830                 tc->tc_offset_nano -= 1000000000ULL << 32;
831                 tc->tc_offset_sec++;
832                 ntp_update_second(tc);  /* XXX only needed if xntpd runs */
833                 tco_setscales(tc);
834                 force++;
835         }
836
837         if (tco_method && !force)
838                 return;
839
840         tc->tc_offset_micro = (tc->tc_offset_nano / 1000) >> 32;
841
842         /* Figure out the wall-clock time */
843         tc->tc_nanotime.tv_sec = tc->tc_offset_sec + boottime.tv_sec;
844         tc->tc_nanotime.tv_nsec = 
845             (tc->tc_offset_nano >> 32) + boottime.tv_usec * 1000;
846         tc->tc_microtime.tv_usec = tc->tc_offset_micro + boottime.tv_usec;
847         while (tc->tc_nanotime.tv_nsec >= 1000000000) {
848                 tc->tc_nanotime.tv_nsec -= 1000000000;
849                 tc->tc_microtime.tv_usec -= 1000000;
850                 tc->tc_nanotime.tv_sec++;
851         }
852         time_second = tc->tc_microtime.tv_sec = tc->tc_nanotime.tv_sec;
853
854         timecounter = tc;
855 }
856
857 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
858
859 SYSCTL_INT(_kern_timecounter, OID_AUTO, method, CTLFLAG_RW, &tco_method, 0,
860     "This variable determines the method used for updating timecounters. "
861     "If the default algorithm (0) fails with \"calcru negative...\" messages "
862     "try the alternate algorithm (1) which handles bad hardware better."
863
864 );
865
866 static int
867 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
868 {
869         char newname[32];
870         struct timecounter *newtc, *tc;
871         int error;
872
873         tc = timecounter->tc_tweak;
874         strncpy(newname, tc->tc_name, sizeof(newname));
875         error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
876         if (error == 0 && req->newptr != NULL &&
877             strcmp(newname, tc->tc_name) != 0) {
878                 for (newtc = tc->tc_avail; newtc != tc;
879                     newtc = newtc->tc_avail) {
880                         if (strcmp(newname, newtc->tc_name) == 0) {
881                                 /* Warm up new timecounter. */
882                                 (void)newtc->tc_get_timecount(newtc);
883
884                                 switch_timecounter(newtc);
885                                 return (0);
886                         }
887                 }
888                 return (EINVAL);
889         }
890         return (error);
891 }
892
893 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
894     0, 0, sysctl_kern_timecounter_hardware, "A", "");
895
896
897 int
898 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
899 {
900         pps_params_t *app;
901         struct pps_fetch_args *fapi;
902 #ifdef PPS_SYNC
903         struct pps_kcbind_args *kapi;
904 #endif
905
906         switch (cmd) {
907         case PPS_IOC_CREATE:
908                 return (0);
909         case PPS_IOC_DESTROY:
910                 return (0);
911         case PPS_IOC_SETPARAMS:
912                 app = (pps_params_t *)data;
913                 if (app->mode & ~pps->ppscap)
914                         return (EINVAL);
915                 pps->ppsparam = *app;         
916                 return (0);
917         case PPS_IOC_GETPARAMS:
918                 app = (pps_params_t *)data;
919                 *app = pps->ppsparam;
920                 app->api_version = PPS_API_VERS_1;
921                 return (0);
922         case PPS_IOC_GETCAP:
923                 *(int*)data = pps->ppscap;
924                 return (0);
925         case PPS_IOC_FETCH:
926                 fapi = (struct pps_fetch_args *)data;
927                 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
928                         return (EINVAL);
929                 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
930                         return (EOPNOTSUPP);
931                 pps->ppsinfo.current_mode = pps->ppsparam.mode;         
932                 fapi->pps_info_buf = pps->ppsinfo;
933                 return (0);
934         case PPS_IOC_KCBIND:
935 #ifdef PPS_SYNC
936                 kapi = (struct pps_kcbind_args *)data;
937                 /* XXX Only root should be able to do this */
938                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
939                         return (EINVAL);
940                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
941                         return (EINVAL);
942                 if (kapi->edge & ~pps->ppscap)
943                         return (EINVAL);
944                 pps->kcmode = kapi->edge;
945                 return (0);
946 #else
947                 return (EOPNOTSUPP);
948 #endif
949         default:
950                 return (ENOTTY);
951         }
952 }
953
954 void
955 pps_init(struct pps_state *pps)
956 {
957         pps->ppscap |= PPS_TSFMT_TSPEC;
958         if (pps->ppscap & PPS_CAPTUREASSERT)
959                 pps->ppscap |= PPS_OFFSETASSERT;
960         if (pps->ppscap & PPS_CAPTURECLEAR)
961                 pps->ppscap |= PPS_OFFSETCLEAR;
962 }
963
964 void
965 pps_event(struct pps_state *pps, struct timecounter *tc, unsigned count, int event)
966 {
967         struct timespec ts, *tsp, *osp;
968         u_int64_t delta;
969         unsigned tcount, *pcount;
970         int foff, fhard;
971         pps_seq_t       *pseq;
972
973         /* Things would be easier with arrays... */
974         if (event == PPS_CAPTUREASSERT) {
975                 tsp = &pps->ppsinfo.assert_timestamp;
976                 osp = &pps->ppsparam.assert_offset;
977                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
978                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
979                 pcount = &pps->ppscount[0];
980                 pseq = &pps->ppsinfo.assert_sequence;
981         } else {
982                 tsp = &pps->ppsinfo.clear_timestamp;
983                 osp = &pps->ppsparam.clear_offset;
984                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
985                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
986                 pcount = &pps->ppscount[1];
987                 pseq = &pps->ppsinfo.clear_sequence;
988         }
989
990         /* The timecounter changed: bail */
991         if (!pps->ppstc || 
992             pps->ppstc->tc_name != tc->tc_name || 
993             tc->tc_name != timecounter->tc_name) {
994                 pps->ppstc = tc;
995                 *pcount = count;
996                 return;
997         }
998
999         /* Nothing really happened */
1000         if (*pcount == count)
1001                 return;
1002
1003         *pcount = count;
1004
1005         /* Convert the count to timespec */
1006         ts.tv_sec = tc->tc_offset_sec;
1007         tcount = count - tc->tc_offset_count;
1008         tcount &= tc->tc_counter_mask;
1009         delta = tc->tc_offset_nano;
1010         delta += ((u_int64_t)tcount * tc->tc_scale_nano_f);
1011         delta >>= 32;
1012         delta += ((u_int64_t)tcount * tc->tc_scale_nano_i);
1013         delta += boottime.tv_usec * 1000;
1014         ts.tv_sec += boottime.tv_sec;
1015         while (delta >= 1000000000) {
1016                 delta -= 1000000000;
1017                 ts.tv_sec++;
1018         }
1019         ts.tv_nsec = delta;
1020
1021         (*pseq)++;
1022         *tsp = ts;
1023
1024         if (foff) {
1025                 timespecadd(tsp, osp);
1026                 if (tsp->tv_nsec < 0) {
1027                         tsp->tv_nsec += 1000000000;
1028                         tsp->tv_sec -= 1;
1029                 }
1030         }
1031 #ifdef PPS_SYNC
1032         if (fhard) {
1033                 /* magic, at its best... */
1034                 tcount = count - pps->ppscount[2];
1035                 pps->ppscount[2] = count;
1036                 tcount &= tc->tc_counter_mask;
1037                 delta = ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_f);
1038                 delta >>= 32;
1039                 delta += ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_i);
1040                 hardpps(tsp, delta);
1041         }
1042 #endif
1043 }