a1fb47f8fcedd08b4a42a16736af4aba4dae6ec8
[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.4 2003/06/28 04:16:04 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         thread_t td;
387         struct pstats *pstats;
388         long rss;
389         struct rusage *ru;
390         struct vmspace *vm;
391         struct proc *p;
392         int bump;
393         struct timeval tv;
394         struct timeval *stv;
395
396         /*
397          * How big was our timeslice relative to the last time
398          */
399         microuptime(&tv);
400         stv = &mycpu->gd_stattv;
401         if (stv->tv_sec == 0) {
402             bump = 1;
403         } else {
404             bump = tv.tv_usec - stv->tv_usec +
405                 (tv.tv_sec - stv->tv_sec) * 1000000;
406             if (bump < 0)
407                 bump = 0;
408             if (bump > 1000000)
409                 bump = 1000000;
410         }
411         *stv = tv;
412
413         td = curthread;
414         p = td->td_proc;
415
416         if (CLKF_USERMODE(frame)) {
417                 /*
418                  * Came from userland, handle user time and deal with
419                  * possible process.
420                  */
421                 if (p && (p->p_flag & P_PROFIL))
422                         addupc_intr(p, CLKF_PC(frame), 1);
423 #if defined(SMP) && defined(BETTER_CLOCK)
424                 if (stathz != 0)
425                         forward_statclock(pscnt);
426 #endif
427                 td->td_uticks += bump;
428                 if (--pscnt > 0)
429                         return;
430
431                 /*
432                  * Charge the time as appropriate
433                  */
434                 if (p && p->p_nice > NZERO)
435                         ++cp_time[CP_NICE];
436                 else
437                         ++cp_time[CP_USER];
438         } else {
439 #ifdef GPROF
440                 /*
441                  * Kernel statistics are just like addupc_intr, only easier.
442                  */
443                 g = &_gmonparam;
444                 if (g->state == GMON_PROF_ON) {
445                         i = CLKF_PC(frame) - g->lowpc;
446                         if (i < g->textsize) {
447                                 i /= HISTFRACTION * sizeof(*g->kcount);
448                                 g->kcount[i]++;
449                         }
450                 }
451 #endif
452 #if defined(SMP) && defined(BETTER_CLOCK)
453                 if (stathz != 0)
454                         forward_statclock(pscnt);
455 #endif
456                 /*
457                  * Came from kernel mode, so we were:
458                  * - handling an interrupt,
459                  * - doing syscall or trap work on behalf of the current
460                  *   user process, or
461                  * - spinning in the idle loop.
462                  * Whichever it is, charge the time as appropriate.
463                  * Note that we charge interrupts to the current process,
464                  * regardless of whether they are ``for'' that process,
465                  * so that we know how much of its real time was spent
466                  * in ``non-process'' (i.e., interrupt) work.
467                  */
468                 if (CLKF_INTR(frame))
469                         td->td_iticks += bump;
470                 else
471                         td->td_sticks += bump;
472
473                 if (--pscnt > 0)
474                         return;
475
476                 if (CLKF_INTR(frame)) {
477                         cp_time[CP_INTR]++;
478                 } else {
479                         if (td == mycpu->gd_idletd)
480                                 ++cp_time[CP_IDLE];
481                         else
482                                 ++cp_time[CP_SYS];
483                 }
484         }
485         pscnt = psdiv;
486
487         if (p != NULL) {
488                 schedclock(p);
489
490                 /* Update resource usage integrals and maximums. */
491                 if ((pstats = p->p_stats) != NULL &&
492                     (ru = &pstats->p_ru) != NULL &&
493                     (vm = p->p_vmspace) != NULL) {
494                         ru->ru_ixrss += pgtok(vm->vm_tsize);
495                         ru->ru_idrss += pgtok(vm->vm_dsize);
496                         ru->ru_isrss += pgtok(vm->vm_ssize);
497                         rss = pgtok(vmspace_resident_count(vm));
498                         if (ru->ru_maxrss < rss)
499                                 ru->ru_maxrss = rss;
500                 }
501         }
502 }
503
504 /*
505  * Return information about system clocks.
506  */
507 static int
508 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
509 {
510         struct clockinfo clkinfo;
511         /*
512          * Construct clockinfo structure.
513          */
514         clkinfo.hz = hz;
515         clkinfo.tick = tick;
516         clkinfo.tickadj = tickadj;
517         clkinfo.profhz = profhz;
518         clkinfo.stathz = stathz ? stathz : hz;
519         return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
520 }
521
522 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
523         0, 0, sysctl_kern_clockrate, "S,clockinfo","");
524
525 static __inline unsigned
526 tco_delta(struct timecounter *tc)
527 {
528
529         return ((tc->tc_get_timecount(tc) - tc->tc_offset_count) & 
530             tc->tc_counter_mask);
531 }
532
533 /*
534  * We have eight functions for looking at the clock, four for
535  * microseconds and four for nanoseconds.  For each there is fast
536  * but less precise version "get{nano|micro}[up]time" which will
537  * return a time which is up to 1/HZ previous to the call, whereas
538  * the raw version "{nano|micro}[up]time" will return a timestamp
539  * which is as precise as possible.  The "up" variants return the
540  * time relative to system boot, these are well suited for time
541  * interval measurements.
542  */
543
544 void
545 getmicrotime(struct timeval *tvp)
546 {
547         struct timecounter *tc;
548
549         if (!tco_method) {
550                 tc = timecounter;
551                 *tvp = tc->tc_microtime;
552         } else {
553                 microtime(tvp);
554         }
555 }
556
557 void
558 getnanotime(struct timespec *tsp)
559 {
560         struct timecounter *tc;
561
562         if (!tco_method) {
563                 tc = timecounter;
564                 *tsp = tc->tc_nanotime;
565         } else {
566                 nanotime(tsp);
567         }
568 }
569
570 void
571 microtime(struct timeval *tv)
572 {
573         struct timecounter *tc;
574
575         tc = timecounter;
576         tv->tv_sec = tc->tc_offset_sec;
577         tv->tv_usec = tc->tc_offset_micro;
578         tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
579         tv->tv_usec += boottime.tv_usec;
580         tv->tv_sec += boottime.tv_sec;
581         while (tv->tv_usec < 0) {
582                 tv->tv_usec += 1000000;
583                 if (tv->tv_sec > 0)
584                         tv->tv_sec--;
585         }
586         while (tv->tv_usec >= 1000000) {
587                 tv->tv_usec -= 1000000;
588                 tv->tv_sec++;
589         }
590 }
591
592 void
593 nanotime(struct timespec *ts)
594 {
595         unsigned count;
596         u_int64_t delta;
597         struct timecounter *tc;
598
599         tc = timecounter;
600         ts->tv_sec = tc->tc_offset_sec;
601         count = tco_delta(tc);
602         delta = tc->tc_offset_nano;
603         delta += ((u_int64_t)count * tc->tc_scale_nano_f);
604         delta >>= 32;
605         delta += ((u_int64_t)count * tc->tc_scale_nano_i);
606         delta += boottime.tv_usec * 1000;
607         ts->tv_sec += boottime.tv_sec;
608         while (delta < 0) {
609                 delta += 1000000000;
610                 if (ts->tv_sec > 0)
611                         ts->tv_sec--;
612         }
613         while (delta >= 1000000000) {
614                 delta -= 1000000000;
615                 ts->tv_sec++;
616         }
617         ts->tv_nsec = delta;
618 }
619
620 void
621 getmicrouptime(struct timeval *tvp)
622 {
623         struct timecounter *tc;
624
625         if (!tco_method) {
626                 tc = timecounter;
627                 tvp->tv_sec = tc->tc_offset_sec;
628                 tvp->tv_usec = tc->tc_offset_micro;
629         } else {
630                 microuptime(tvp);
631         }
632 }
633
634 void
635 getnanouptime(struct timespec *tsp)
636 {
637         struct timecounter *tc;
638
639         if (!tco_method) {
640                 tc = timecounter;
641                 tsp->tv_sec = tc->tc_offset_sec;
642                 tsp->tv_nsec = tc->tc_offset_nano >> 32;
643         } else {
644                 nanouptime(tsp);
645         }
646 }
647
648 void
649 microuptime(struct timeval *tv)
650 {
651         struct timecounter *tc;
652
653         tc = timecounter;
654         tv->tv_sec = tc->tc_offset_sec;
655         tv->tv_usec = tc->tc_offset_micro;
656         tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
657         while (tv->tv_usec < 0) {
658                 tv->tv_usec += 1000000;
659                 if (tv->tv_sec > 0)
660                         tv->tv_sec--;
661         }
662         while (tv->tv_usec >= 1000000) {
663                 tv->tv_usec -= 1000000;
664                 tv->tv_sec++;
665         }
666 }
667
668 void
669 nanouptime(struct timespec *ts)
670 {
671         unsigned count;
672         u_int64_t delta;
673         struct timecounter *tc;
674
675         tc = timecounter;
676         ts->tv_sec = tc->tc_offset_sec;
677         count = tco_delta(tc);
678         delta = tc->tc_offset_nano;
679         delta += ((u_int64_t)count * tc->tc_scale_nano_f);
680         delta >>= 32;
681         delta += ((u_int64_t)count * tc->tc_scale_nano_i);
682         while (delta < 0) {
683                 delta += 1000000000;
684                 if (ts->tv_sec > 0)
685                         ts->tv_sec--;
686         }
687         while (delta >= 1000000000) {
688                 delta -= 1000000000;
689                 ts->tv_sec++;
690         }
691         ts->tv_nsec = delta;
692 }
693
694 static void
695 tco_setscales(struct timecounter *tc)
696 {
697         u_int64_t scale;
698
699         scale = 1000000000LL << 32;
700         scale += tc->tc_adjustment;
701         scale /= tc->tc_tweak->tc_frequency;
702         tc->tc_scale_micro = scale / 1000;
703         tc->tc_scale_nano_f = scale & 0xffffffff;
704         tc->tc_scale_nano_i = scale >> 32;
705 }
706
707 void
708 update_timecounter(struct timecounter *tc)
709 {
710         tco_setscales(tc);
711 }
712
713 void
714 init_timecounter(struct timecounter *tc)
715 {
716         struct timespec ts1;
717         struct timecounter *t1, *t2, *t3;
718         unsigned u;
719         int i;
720
721         u = tc->tc_frequency / tc->tc_counter_mask;
722         if (u > hz) {
723                 printf("Timecounter \"%s\" frequency %lu Hz"
724                        " -- Insufficient hz, needs at least %u\n",
725                        tc->tc_name, (u_long) tc->tc_frequency, u);
726                 return;
727         }
728
729         tc->tc_adjustment = 0;
730         tc->tc_tweak = tc;
731         tco_setscales(tc);
732         tc->tc_offset_count = tc->tc_get_timecount(tc);
733         if (timecounter == &dummy_timecounter)
734                 tc->tc_avail = tc;
735         else {
736                 tc->tc_avail = timecounter->tc_tweak->tc_avail;
737                 timecounter->tc_tweak->tc_avail = tc;
738         }
739         MALLOC(t1, struct timecounter *, sizeof *t1, M_TIMECOUNTER, M_WAITOK);
740         tc->tc_other = t1;
741         *t1 = *tc;
742         t2 = t1;
743         for (i = 1; i < NTIMECOUNTER; i++) {
744                 MALLOC(t3, struct timecounter *, sizeof *t3,
745                     M_TIMECOUNTER, M_WAITOK);
746                 *t3 = *tc;
747                 t3->tc_other = t2;
748                 t2 = t3;
749         }
750         t1->tc_other = t3;
751         tc = t1;
752
753         printf("Timecounter \"%s\"  frequency %lu Hz\n", 
754             tc->tc_name, (u_long)tc->tc_frequency);
755
756         /* XXX: For now always start using the counter. */
757         tc->tc_offset_count = tc->tc_get_timecount(tc);
758         nanouptime(&ts1);
759         tc->tc_offset_nano = (u_int64_t)ts1.tv_nsec << 32;
760         tc->tc_offset_micro = ts1.tv_nsec / 1000;
761         tc->tc_offset_sec = ts1.tv_sec;
762         timecounter = tc;
763 }
764
765 void
766 set_timecounter(struct timespec *ts)
767 {
768         struct timespec ts2;
769
770         nanouptime(&ts2);
771         boottime.tv_sec = ts->tv_sec - ts2.tv_sec;
772         boottime.tv_usec = (ts->tv_nsec - ts2.tv_nsec) / 1000;
773         if (boottime.tv_usec < 0) {
774                 boottime.tv_usec += 1000000;
775                 boottime.tv_sec--;
776         }
777         /* fiddle all the little crinkly bits around the fiords... */
778         tco_forward(1);
779 }
780
781 static void
782 switch_timecounter(struct timecounter *newtc)
783 {
784         int s;
785         struct timecounter *tc;
786         struct timespec ts;
787
788         s = splclock();
789         tc = timecounter;
790         if (newtc->tc_tweak == tc->tc_tweak) {
791                 splx(s);
792                 return;
793         }
794         newtc = newtc->tc_tweak->tc_other;
795         nanouptime(&ts);
796         newtc->tc_offset_sec = ts.tv_sec;
797         newtc->tc_offset_nano = (u_int64_t)ts.tv_nsec << 32;
798         newtc->tc_offset_micro = ts.tv_nsec / 1000;
799         newtc->tc_offset_count = newtc->tc_get_timecount(newtc);
800         tco_setscales(newtc);
801         timecounter = newtc;
802         splx(s);
803 }
804
805 static struct timecounter *
806 sync_other_counter(void)
807 {
808         struct timecounter *tc, *tcn, *tco;
809         unsigned delta;
810
811         tco = timecounter;
812         tc = tco->tc_other;
813         tcn = tc->tc_other;
814         *tc = *tco;
815         tc->tc_other = tcn;
816         delta = tco_delta(tc);
817         tc->tc_offset_count += delta;
818         tc->tc_offset_count &= tc->tc_counter_mask;
819         tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_f;
820         tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_i << 32;
821         return (tc);
822 }
823
824 static void
825 tco_forward(int force)
826 {
827         struct timecounter *tc, *tco;
828         struct timeval tvt;
829
830         tco = timecounter;
831         tc = sync_other_counter();
832         /*
833          * We may be inducing a tiny error here, the tc_poll_pps() may
834          * process a latched count which happens after the tco_delta()
835          * in sync_other_counter(), which would extend the previous
836          * counters parameters into the domain of this new one.
837          * Since the timewindow is very small for this, the error is
838          * going to be only a few weenieseconds (as Dave Mills would
839          * say), so lets just not talk more about it, OK ?
840          */
841         if (tco->tc_poll_pps) 
842                 tco->tc_poll_pps(tco);
843         if (timedelta != 0) {
844                 tvt = boottime;
845                 tvt.tv_usec += tickdelta;
846                 if (tvt.tv_usec >= 1000000) {
847                         tvt.tv_sec++;
848                         tvt.tv_usec -= 1000000;
849                 } else if (tvt.tv_usec < 0) {
850                         tvt.tv_sec--;
851                         tvt.tv_usec += 1000000;
852                 }
853                 boottime = tvt;
854                 timedelta -= tickdelta;
855         }
856
857         while (tc->tc_offset_nano >= 1000000000ULL << 32) {
858                 tc->tc_offset_nano -= 1000000000ULL << 32;
859                 tc->tc_offset_sec++;
860                 ntp_update_second(tc);  /* XXX only needed if xntpd runs */
861                 tco_setscales(tc);
862                 force++;
863         }
864
865         if (tco_method && !force)
866                 return;
867
868         tc->tc_offset_micro = (tc->tc_offset_nano / 1000) >> 32;
869
870         /* Figure out the wall-clock time */
871         tc->tc_nanotime.tv_sec = tc->tc_offset_sec + boottime.tv_sec;
872         tc->tc_nanotime.tv_nsec = 
873             (tc->tc_offset_nano >> 32) + boottime.tv_usec * 1000;
874         tc->tc_microtime.tv_usec = tc->tc_offset_micro + boottime.tv_usec;
875         while (tc->tc_nanotime.tv_nsec >= 1000000000) {
876                 tc->tc_nanotime.tv_nsec -= 1000000000;
877                 tc->tc_microtime.tv_usec -= 1000000;
878                 tc->tc_nanotime.tv_sec++;
879         }
880         time_second = tc->tc_microtime.tv_sec = tc->tc_nanotime.tv_sec;
881
882         timecounter = tc;
883 }
884
885 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
886
887 SYSCTL_INT(_kern_timecounter, OID_AUTO, method, CTLFLAG_RW, &tco_method, 0,
888     "This variable determines the method used for updating timecounters. "
889     "If the default algorithm (0) fails with \"calcru negative...\" messages "
890     "try the alternate algorithm (1) which handles bad hardware better."
891
892 );
893
894 static int
895 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
896 {
897         char newname[32];
898         struct timecounter *newtc, *tc;
899         int error;
900
901         tc = timecounter->tc_tweak;
902         strncpy(newname, tc->tc_name, sizeof(newname));
903         error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
904         if (error == 0 && req->newptr != NULL &&
905             strcmp(newname, tc->tc_name) != 0) {
906                 for (newtc = tc->tc_avail; newtc != tc;
907                     newtc = newtc->tc_avail) {
908                         if (strcmp(newname, newtc->tc_name) == 0) {
909                                 /* Warm up new timecounter. */
910                                 (void)newtc->tc_get_timecount(newtc);
911
912                                 switch_timecounter(newtc);
913                                 return (0);
914                         }
915                 }
916                 return (EINVAL);
917         }
918         return (error);
919 }
920
921 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
922     0, 0, sysctl_kern_timecounter_hardware, "A", "");
923
924
925 int
926 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
927 {
928         pps_params_t *app;
929         struct pps_fetch_args *fapi;
930 #ifdef PPS_SYNC
931         struct pps_kcbind_args *kapi;
932 #endif
933
934         switch (cmd) {
935         case PPS_IOC_CREATE:
936                 return (0);
937         case PPS_IOC_DESTROY:
938                 return (0);
939         case PPS_IOC_SETPARAMS:
940                 app = (pps_params_t *)data;
941                 if (app->mode & ~pps->ppscap)
942                         return (EINVAL);
943                 pps->ppsparam = *app;         
944                 return (0);
945         case PPS_IOC_GETPARAMS:
946                 app = (pps_params_t *)data;
947                 *app = pps->ppsparam;
948                 app->api_version = PPS_API_VERS_1;
949                 return (0);
950         case PPS_IOC_GETCAP:
951                 *(int*)data = pps->ppscap;
952                 return (0);
953         case PPS_IOC_FETCH:
954                 fapi = (struct pps_fetch_args *)data;
955                 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
956                         return (EINVAL);
957                 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
958                         return (EOPNOTSUPP);
959                 pps->ppsinfo.current_mode = pps->ppsparam.mode;         
960                 fapi->pps_info_buf = pps->ppsinfo;
961                 return (0);
962         case PPS_IOC_KCBIND:
963 #ifdef PPS_SYNC
964                 kapi = (struct pps_kcbind_args *)data;
965                 /* XXX Only root should be able to do this */
966                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
967                         return (EINVAL);
968                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
969                         return (EINVAL);
970                 if (kapi->edge & ~pps->ppscap)
971                         return (EINVAL);
972                 pps->kcmode = kapi->edge;
973                 return (0);
974 #else
975                 return (EOPNOTSUPP);
976 #endif
977         default:
978                 return (ENOTTY);
979         }
980 }
981
982 void
983 pps_init(struct pps_state *pps)
984 {
985         pps->ppscap |= PPS_TSFMT_TSPEC;
986         if (pps->ppscap & PPS_CAPTUREASSERT)
987                 pps->ppscap |= PPS_OFFSETASSERT;
988         if (pps->ppscap & PPS_CAPTURECLEAR)
989                 pps->ppscap |= PPS_OFFSETCLEAR;
990 }
991
992 void
993 pps_event(struct pps_state *pps, struct timecounter *tc, unsigned count, int event)
994 {
995         struct timespec ts, *tsp, *osp;
996         u_int64_t delta;
997         unsigned tcount, *pcount;
998         int foff, fhard;
999         pps_seq_t       *pseq;
1000
1001         /* Things would be easier with arrays... */
1002         if (event == PPS_CAPTUREASSERT) {
1003                 tsp = &pps->ppsinfo.assert_timestamp;
1004                 osp = &pps->ppsparam.assert_offset;
1005                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1006                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1007                 pcount = &pps->ppscount[0];
1008                 pseq = &pps->ppsinfo.assert_sequence;
1009         } else {
1010                 tsp = &pps->ppsinfo.clear_timestamp;
1011                 osp = &pps->ppsparam.clear_offset;
1012                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1013                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1014                 pcount = &pps->ppscount[1];
1015                 pseq = &pps->ppsinfo.clear_sequence;
1016         }
1017
1018         /* The timecounter changed: bail */
1019         if (!pps->ppstc || 
1020             pps->ppstc->tc_name != tc->tc_name || 
1021             tc->tc_name != timecounter->tc_name) {
1022                 pps->ppstc = tc;
1023                 *pcount = count;
1024                 return;
1025         }
1026
1027         /* Nothing really happened */
1028         if (*pcount == count)
1029                 return;
1030
1031         *pcount = count;
1032
1033         /* Convert the count to timespec */
1034         ts.tv_sec = tc->tc_offset_sec;
1035         tcount = count - tc->tc_offset_count;
1036         tcount &= tc->tc_counter_mask;
1037         delta = tc->tc_offset_nano;
1038         delta += ((u_int64_t)tcount * tc->tc_scale_nano_f);
1039         delta >>= 32;
1040         delta += ((u_int64_t)tcount * tc->tc_scale_nano_i);
1041         delta += boottime.tv_usec * 1000;
1042         ts.tv_sec += boottime.tv_sec;
1043         while (delta >= 1000000000) {
1044                 delta -= 1000000000;
1045                 ts.tv_sec++;
1046         }
1047         ts.tv_nsec = delta;
1048
1049         (*pseq)++;
1050         *tsp = ts;
1051
1052         if (foff) {
1053                 timespecadd(tsp, osp);
1054                 if (tsp->tv_nsec < 0) {
1055                         tsp->tv_nsec += 1000000000;
1056                         tsp->tv_sec -= 1;
1057                 }
1058         }
1059 #ifdef PPS_SYNC
1060         if (fhard) {
1061                 /* magic, at its best... */
1062                 tcount = count - pps->ppscount[2];
1063                 pps->ppscount[2] = count;
1064                 tcount &= tc->tc_counter_mask;
1065                 delta = ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_f);
1066                 delta >>= 32;
1067                 delta += ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_i);
1068                 hardpps(tsp, delta);
1069         }
1070 #endif
1071 }