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