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