]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/kern/kern_tc.c
Copy stable/8 to releng/8.2 in preparation for FreeBSD-8.2 release.
[FreeBSD/releng/8.2.git] / sys / kern / kern_tc.c
1 /*-
2  * ----------------------------------------------------------------------------
3  * "THE BEER-WARE LICENSE" (Revision 42):
4  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
5  * can do whatever you want with this stuff. If we meet some day, and you think
6  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7  * ----------------------------------------------------------------------------
8  */
9
10 #include <sys/cdefs.h>
11 __FBSDID("$FreeBSD$");
12
13 #include "opt_ntp.h"
14
15 #include <sys/param.h>
16 #include <sys/kernel.h>
17 #include <sys/sysctl.h>
18 #include <sys/syslog.h>
19 #include <sys/systm.h>
20 #include <sys/timepps.h>
21 #include <sys/timetc.h>
22 #include <sys/timex.h>
23
24 /*
25  * A large step happens on boot.  This constant detects such steps.
26  * It is relatively small so that ntp_update_second gets called enough
27  * in the typical 'missed a couple of seconds' case, but doesn't loop
28  * forever when the time step is large.
29  */
30 #define LARGE_STEP      200
31
32 /*
33  * Implement a dummy timecounter which we can use until we get a real one
34  * in the air.  This allows the console and other early stuff to use
35  * time services.
36  */
37
38 static u_int
39 dummy_get_timecount(struct timecounter *tc)
40 {
41         static u_int now;
42
43         return (++now);
44 }
45
46 static struct timecounter dummy_timecounter = {
47         dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
48 };
49
50 struct timehands {
51         /* These fields must be initialized by the driver. */
52         struct timecounter      *th_counter;
53         int64_t                 th_adjustment;
54         u_int64_t               th_scale;
55         u_int                   th_offset_count;
56         struct bintime          th_offset;
57         struct timeval          th_microtime;
58         struct timespec         th_nanotime;
59         /* Fields not to be copied in tc_windup start with th_generation. */
60         volatile u_int          th_generation;
61         struct timehands        *th_next;
62 };
63
64 static struct timehands th0;
65 static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
66 static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
67 static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
68 static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
69 static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
70 static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
71 static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
72 static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
73 static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
74 static struct timehands th0 = {
75         &dummy_timecounter,
76         0,
77         (uint64_t)-1 / 1000000,
78         0,
79         {1, 0},
80         {0, 0},
81         {0, 0},
82         1,
83         &th1
84 };
85
86 static struct timehands *volatile timehands = &th0;
87 struct timecounter *timecounter = &dummy_timecounter;
88 static struct timecounter *timecounters = &dummy_timecounter;
89
90 time_t time_second = 1;
91 time_t time_uptime = 1;
92
93 static struct bintime boottimebin;
94 struct timeval boottime;
95 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
96 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
97     NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
98
99 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
100 SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
101
102 static int timestepwarnings;
103 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
104     &timestepwarnings, 0, "Log time steps");
105
106 static void tc_windup(void);
107 static void cpu_tick_calibrate(int);
108
109 static int
110 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
111 {
112 #ifdef SCTL_MASK32
113         int tv[2];
114
115         if (req->flags & SCTL_MASK32) {
116                 tv[0] = boottime.tv_sec;
117                 tv[1] = boottime.tv_usec;
118                 return SYSCTL_OUT(req, tv, sizeof(tv));
119         } else
120 #endif
121                 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
122 }
123
124 static int
125 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
126 {
127         u_int ncount;
128         struct timecounter *tc = arg1;
129
130         ncount = tc->tc_get_timecount(tc);
131         return sysctl_handle_int(oidp, &ncount, 0, req);
132 }
133
134 static int
135 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
136 {
137         u_int64_t freq;
138         struct timecounter *tc = arg1;
139
140         freq = tc->tc_frequency;
141         return sysctl_handle_quad(oidp, &freq, 0, req);
142 }
143
144 /*
145  * Return the difference between the timehands' counter value now and what
146  * was when we copied it to the timehands' offset_count.
147  */
148 static __inline u_int
149 tc_delta(struct timehands *th)
150 {
151         struct timecounter *tc;
152
153         tc = th->th_counter;
154         return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
155             tc->tc_counter_mask);
156 }
157
158 /*
159  * Functions for reading the time.  We have to loop until we are sure that
160  * the timehands that we operated on was not updated under our feet.  See
161  * the comment in <sys/time.h> for a description of these 12 functions.
162  */
163
164 void
165 binuptime(struct bintime *bt)
166 {
167         struct timehands *th;
168         u_int gen;
169
170         do {
171                 th = timehands;
172                 gen = th->th_generation;
173                 *bt = th->th_offset;
174                 bintime_addx(bt, th->th_scale * tc_delta(th));
175         } while (gen == 0 || gen != th->th_generation);
176 }
177
178 void
179 nanouptime(struct timespec *tsp)
180 {
181         struct bintime bt;
182
183         binuptime(&bt);
184         bintime2timespec(&bt, tsp);
185 }
186
187 void
188 microuptime(struct timeval *tvp)
189 {
190         struct bintime bt;
191
192         binuptime(&bt);
193         bintime2timeval(&bt, tvp);
194 }
195
196 void
197 bintime(struct bintime *bt)
198 {
199
200         binuptime(bt);
201         bintime_add(bt, &boottimebin);
202 }
203
204 void
205 nanotime(struct timespec *tsp)
206 {
207         struct bintime bt;
208
209         bintime(&bt);
210         bintime2timespec(&bt, tsp);
211 }
212
213 void
214 microtime(struct timeval *tvp)
215 {
216         struct bintime bt;
217
218         bintime(&bt);
219         bintime2timeval(&bt, tvp);
220 }
221
222 void
223 getbinuptime(struct bintime *bt)
224 {
225         struct timehands *th;
226         u_int gen;
227
228         do {
229                 th = timehands;
230                 gen = th->th_generation;
231                 *bt = th->th_offset;
232         } while (gen == 0 || gen != th->th_generation);
233 }
234
235 void
236 getnanouptime(struct timespec *tsp)
237 {
238         struct timehands *th;
239         u_int gen;
240
241         do {
242                 th = timehands;
243                 gen = th->th_generation;
244                 bintime2timespec(&th->th_offset, tsp);
245         } while (gen == 0 || gen != th->th_generation);
246 }
247
248 void
249 getmicrouptime(struct timeval *tvp)
250 {
251         struct timehands *th;
252         u_int gen;
253
254         do {
255                 th = timehands;
256                 gen = th->th_generation;
257                 bintime2timeval(&th->th_offset, tvp);
258         } while (gen == 0 || gen != th->th_generation);
259 }
260
261 void
262 getbintime(struct bintime *bt)
263 {
264         struct timehands *th;
265         u_int gen;
266
267         do {
268                 th = timehands;
269                 gen = th->th_generation;
270                 *bt = th->th_offset;
271         } while (gen == 0 || gen != th->th_generation);
272         bintime_add(bt, &boottimebin);
273 }
274
275 void
276 getnanotime(struct timespec *tsp)
277 {
278         struct timehands *th;
279         u_int gen;
280
281         do {
282                 th = timehands;
283                 gen = th->th_generation;
284                 *tsp = th->th_nanotime;
285         } while (gen == 0 || gen != th->th_generation);
286 }
287
288 void
289 getmicrotime(struct timeval *tvp)
290 {
291         struct timehands *th;
292         u_int gen;
293
294         do {
295                 th = timehands;
296                 gen = th->th_generation;
297                 *tvp = th->th_microtime;
298         } while (gen == 0 || gen != th->th_generation);
299 }
300
301 /*
302  * Initialize a new timecounter and possibly use it.
303  */
304 void
305 tc_init(struct timecounter *tc)
306 {
307         u_int u;
308         struct sysctl_oid *tc_root;
309
310         u = tc->tc_frequency / tc->tc_counter_mask;
311         /* XXX: We need some margin here, 10% is a guess */
312         u *= 11;
313         u /= 10;
314         if (u > hz && tc->tc_quality >= 0) {
315                 tc->tc_quality = -2000;
316                 if (bootverbose) {
317                         printf("Timecounter \"%s\" frequency %ju Hz",
318                             tc->tc_name, (uintmax_t)tc->tc_frequency);
319                         printf(" -- Insufficient hz, needs at least %u\n", u);
320                 }
321         } else if (tc->tc_quality >= 0 || bootverbose) {
322                 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
323                     tc->tc_name, (uintmax_t)tc->tc_frequency,
324                     tc->tc_quality);
325         }
326
327         tc->tc_next = timecounters;
328         timecounters = tc;
329         /*
330          * Set up sysctl tree for this counter.
331          */
332         tc_root = SYSCTL_ADD_NODE(NULL,
333             SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
334             CTLFLAG_RW, 0, "timecounter description");
335         SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
336             "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
337             "mask for implemented bits");
338         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
339             "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
340             sysctl_kern_timecounter_get, "IU", "current timecounter value");
341         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
342             "frequency", CTLTYPE_QUAD | CTLFLAG_RD, tc, sizeof(*tc),
343              sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
344         SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
345             "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
346             "goodness of time counter");
347         /*
348          * Never automatically use a timecounter with negative quality.
349          * Even though we run on the dummy counter, switching here may be
350          * worse since this timecounter may not be monotonous.
351          */
352         if (tc->tc_quality < 0)
353                 return;
354         if (tc->tc_quality < timecounter->tc_quality)
355                 return;
356         if (tc->tc_quality == timecounter->tc_quality &&
357             tc->tc_frequency < timecounter->tc_frequency)
358                 return;
359         (void)tc->tc_get_timecount(tc);
360         (void)tc->tc_get_timecount(tc);
361         timecounter = tc;
362 }
363
364 /* Report the frequency of the current timecounter. */
365 u_int64_t
366 tc_getfrequency(void)
367 {
368
369         return (timehands->th_counter->tc_frequency);
370 }
371
372 /*
373  * Step our concept of UTC.  This is done by modifying our estimate of
374  * when we booted.
375  * XXX: not locked.
376  */
377 void
378 tc_setclock(struct timespec *ts)
379 {
380         struct timespec tbef, taft;
381         struct bintime bt, bt2;
382
383         cpu_tick_calibrate(1);
384         nanotime(&tbef);
385         timespec2bintime(ts, &bt);
386         binuptime(&bt2);
387         bintime_sub(&bt, &bt2);
388         bintime_add(&bt2, &boottimebin);
389         boottimebin = bt;
390         bintime2timeval(&bt, &boottime);
391
392         /* XXX fiddle all the little crinkly bits around the fiords... */
393         tc_windup();
394         nanotime(&taft);
395         if (timestepwarnings) {
396                 log(LOG_INFO,
397                     "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
398                     (intmax_t)tbef.tv_sec, tbef.tv_nsec,
399                     (intmax_t)taft.tv_sec, taft.tv_nsec,
400                     (intmax_t)ts->tv_sec, ts->tv_nsec);
401         }
402         cpu_tick_calibrate(1);
403 }
404
405 /*
406  * Initialize the next struct timehands in the ring and make
407  * it the active timehands.  Along the way we might switch to a different
408  * timecounter and/or do seconds processing in NTP.  Slightly magic.
409  */
410 static void
411 tc_windup(void)
412 {
413         struct bintime bt;
414         struct timehands *th, *tho;
415         u_int64_t scale;
416         u_int delta, ncount, ogen;
417         int i;
418         time_t t;
419
420         /*
421          * Make the next timehands a copy of the current one, but do not
422          * overwrite the generation or next pointer.  While we update
423          * the contents, the generation must be zero.
424          */
425         tho = timehands;
426         th = tho->th_next;
427         ogen = th->th_generation;
428         th->th_generation = 0;
429         bcopy(tho, th, offsetof(struct timehands, th_generation));
430
431         /*
432          * Capture a timecounter delta on the current timecounter and if
433          * changing timecounters, a counter value from the new timecounter.
434          * Update the offset fields accordingly.
435          */
436         delta = tc_delta(th);
437         if (th->th_counter != timecounter)
438                 ncount = timecounter->tc_get_timecount(timecounter);
439         else
440                 ncount = 0;
441         th->th_offset_count += delta;
442         th->th_offset_count &= th->th_counter->tc_counter_mask;
443         while (delta > th->th_counter->tc_frequency) {
444                 /* Eat complete unadjusted seconds. */
445                 delta -= th->th_counter->tc_frequency;
446                 th->th_offset.sec++;
447         }
448         if ((delta > th->th_counter->tc_frequency / 2) &&
449             (th->th_scale * delta < ((uint64_t)1 << 63))) {
450                 /* The product th_scale * delta just barely overflows. */
451                 th->th_offset.sec++;
452         }
453         bintime_addx(&th->th_offset, th->th_scale * delta);
454
455         /*
456          * Hardware latching timecounters may not generate interrupts on
457          * PPS events, so instead we poll them.  There is a finite risk that
458          * the hardware might capture a count which is later than the one we
459          * got above, and therefore possibly in the next NTP second which might
460          * have a different rate than the current NTP second.  It doesn't
461          * matter in practice.
462          */
463         if (tho->th_counter->tc_poll_pps)
464                 tho->th_counter->tc_poll_pps(tho->th_counter);
465
466         /*
467          * Deal with NTP second processing.  The for loop normally
468          * iterates at most once, but in extreme situations it might
469          * keep NTP sane if timeouts are not run for several seconds.
470          * At boot, the time step can be large when the TOD hardware
471          * has been read, so on really large steps, we call
472          * ntp_update_second only twice.  We need to call it twice in
473          * case we missed a leap second.
474          */
475         bt = th->th_offset;
476         bintime_add(&bt, &boottimebin);
477         i = bt.sec - tho->th_microtime.tv_sec;
478         if (i > LARGE_STEP)
479                 i = 2;
480         for (; i > 0; i--) {
481                 t = bt.sec;
482                 ntp_update_second(&th->th_adjustment, &bt.sec);
483                 if (bt.sec != t)
484                         boottimebin.sec += bt.sec - t;
485         }
486         /* Update the UTC timestamps used by the get*() functions. */
487         /* XXX shouldn't do this here.  Should force non-`get' versions. */
488         bintime2timeval(&bt, &th->th_microtime);
489         bintime2timespec(&bt, &th->th_nanotime);
490
491         /* Now is a good time to change timecounters. */
492         if (th->th_counter != timecounter) {
493                 th->th_counter = timecounter;
494                 th->th_offset_count = ncount;
495         }
496
497         /*-
498          * Recalculate the scaling factor.  We want the number of 1/2^64
499          * fractions of a second per period of the hardware counter, taking
500          * into account the th_adjustment factor which the NTP PLL/adjtime(2)
501          * processing provides us with.
502          *
503          * The th_adjustment is nanoseconds per second with 32 bit binary
504          * fraction and we want 64 bit binary fraction of second:
505          *
506          *       x = a * 2^32 / 10^9 = a * 4.294967296
507          *
508          * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
509          * we can only multiply by about 850 without overflowing, that
510          * leaves no suitably precise fractions for multiply before divide.
511          *
512          * Divide before multiply with a fraction of 2199/512 results in a
513          * systematic undercompensation of 10PPM of th_adjustment.  On a
514          * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
515          *
516          * We happily sacrifice the lowest of the 64 bits of our result
517          * to the goddess of code clarity.
518          *
519          */
520         scale = (u_int64_t)1 << 63;
521         scale += (th->th_adjustment / 1024) * 2199;
522         scale /= th->th_counter->tc_frequency;
523         th->th_scale = scale * 2;
524
525         /*
526          * Now that the struct timehands is again consistent, set the new
527          * generation number, making sure to not make it zero.
528          */
529         if (++ogen == 0)
530                 ogen = 1;
531         th->th_generation = ogen;
532
533         /* Go live with the new struct timehands. */
534         time_second = th->th_microtime.tv_sec;
535         time_uptime = th->th_offset.sec;
536         timehands = th;
537 }
538
539 /* Report or change the active timecounter hardware. */
540 static int
541 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
542 {
543         char newname[32];
544         struct timecounter *newtc, *tc;
545         int error;
546
547         tc = timecounter;
548         strlcpy(newname, tc->tc_name, sizeof(newname));
549
550         error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
551         if (error != 0 || req->newptr == NULL ||
552             strcmp(newname, tc->tc_name) == 0)
553                 return (error);
554         for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
555                 if (strcmp(newname, newtc->tc_name) != 0)
556                         continue;
557
558                 /* Warm up new timecounter. */
559                 (void)newtc->tc_get_timecount(newtc);
560                 (void)newtc->tc_get_timecount(newtc);
561
562                 timecounter = newtc;
563                 return (0);
564         }
565         return (EINVAL);
566 }
567
568 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
569     0, 0, sysctl_kern_timecounter_hardware, "A",
570     "Timecounter hardware selected");
571
572
573 /* Report or change the active timecounter hardware. */
574 static int
575 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
576 {
577         char buf[32], *spc;
578         struct timecounter *tc;
579         int error;
580
581         spc = "";
582         error = 0;
583         for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
584                 sprintf(buf, "%s%s(%d)",
585                     spc, tc->tc_name, tc->tc_quality);
586                 error = SYSCTL_OUT(req, buf, strlen(buf));
587                 spc = " ";
588         }
589         return (error);
590 }
591
592 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
593     0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
594
595 /*
596  * RFC 2783 PPS-API implementation.
597  */
598
599 int
600 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
601 {
602         pps_params_t *app;
603         struct pps_fetch_args *fapi;
604 #ifdef PPS_SYNC
605         struct pps_kcbind_args *kapi;
606 #endif
607
608         KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
609         switch (cmd) {
610         case PPS_IOC_CREATE:
611                 return (0);
612         case PPS_IOC_DESTROY:
613                 return (0);
614         case PPS_IOC_SETPARAMS:
615                 app = (pps_params_t *)data;
616                 if (app->mode & ~pps->ppscap)
617                         return (EINVAL);
618                 pps->ppsparam = *app;
619                 return (0);
620         case PPS_IOC_GETPARAMS:
621                 app = (pps_params_t *)data;
622                 *app = pps->ppsparam;
623                 app->api_version = PPS_API_VERS_1;
624                 return (0);
625         case PPS_IOC_GETCAP:
626                 *(int*)data = pps->ppscap;
627                 return (0);
628         case PPS_IOC_FETCH:
629                 fapi = (struct pps_fetch_args *)data;
630                 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
631                         return (EINVAL);
632                 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
633                         return (EOPNOTSUPP);
634                 pps->ppsinfo.current_mode = pps->ppsparam.mode;
635                 fapi->pps_info_buf = pps->ppsinfo;
636                 return (0);
637         case PPS_IOC_KCBIND:
638 #ifdef PPS_SYNC
639                 kapi = (struct pps_kcbind_args *)data;
640                 /* XXX Only root should be able to do this */
641                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
642                         return (EINVAL);
643                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
644                         return (EINVAL);
645                 if (kapi->edge & ~pps->ppscap)
646                         return (EINVAL);
647                 pps->kcmode = kapi->edge;
648                 return (0);
649 #else
650                 return (EOPNOTSUPP);
651 #endif
652         default:
653                 return (ENOIOCTL);
654         }
655 }
656
657 void
658 pps_init(struct pps_state *pps)
659 {
660         pps->ppscap |= PPS_TSFMT_TSPEC;
661         if (pps->ppscap & PPS_CAPTUREASSERT)
662                 pps->ppscap |= PPS_OFFSETASSERT;
663         if (pps->ppscap & PPS_CAPTURECLEAR)
664                 pps->ppscap |= PPS_OFFSETCLEAR;
665 }
666
667 void
668 pps_capture(struct pps_state *pps)
669 {
670         struct timehands *th;
671
672         KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
673         th = timehands;
674         pps->capgen = th->th_generation;
675         pps->capth = th;
676         pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
677         if (pps->capgen != th->th_generation)
678                 pps->capgen = 0;
679 }
680
681 void
682 pps_event(struct pps_state *pps, int event)
683 {
684         struct bintime bt;
685         struct timespec ts, *tsp, *osp;
686         u_int tcount, *pcount;
687         int foff, fhard;
688         pps_seq_t *pseq;
689
690         KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
691         /* If the timecounter was wound up underneath us, bail out. */
692         if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
693                 return;
694
695         /* Things would be easier with arrays. */
696         if (event == PPS_CAPTUREASSERT) {
697                 tsp = &pps->ppsinfo.assert_timestamp;
698                 osp = &pps->ppsparam.assert_offset;
699                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
700                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
701                 pcount = &pps->ppscount[0];
702                 pseq = &pps->ppsinfo.assert_sequence;
703         } else {
704                 tsp = &pps->ppsinfo.clear_timestamp;
705                 osp = &pps->ppsparam.clear_offset;
706                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
707                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
708                 pcount = &pps->ppscount[1];
709                 pseq = &pps->ppsinfo.clear_sequence;
710         }
711
712         /*
713          * If the timecounter changed, we cannot compare the count values, so
714          * we have to drop the rest of the PPS-stuff until the next event.
715          */
716         if (pps->ppstc != pps->capth->th_counter) {
717                 pps->ppstc = pps->capth->th_counter;
718                 *pcount = pps->capcount;
719                 pps->ppscount[2] = pps->capcount;
720                 return;
721         }
722
723         /* Convert the count to a timespec. */
724         tcount = pps->capcount - pps->capth->th_offset_count;
725         tcount &= pps->capth->th_counter->tc_counter_mask;
726         bt = pps->capth->th_offset;
727         bintime_addx(&bt, pps->capth->th_scale * tcount);
728         bintime_add(&bt, &boottimebin);
729         bintime2timespec(&bt, &ts);
730
731         /* If the timecounter was wound up underneath us, bail out. */
732         if (pps->capgen != pps->capth->th_generation)
733                 return;
734
735         *pcount = pps->capcount;
736         (*pseq)++;
737         *tsp = ts;
738
739         if (foff) {
740                 timespecadd(tsp, osp);
741                 if (tsp->tv_nsec < 0) {
742                         tsp->tv_nsec += 1000000000;
743                         tsp->tv_sec -= 1;
744                 }
745         }
746 #ifdef PPS_SYNC
747         if (fhard) {
748                 u_int64_t scale;
749
750                 /*
751                  * Feed the NTP PLL/FLL.
752                  * The FLL wants to know how many (hardware) nanoseconds
753                  * elapsed since the previous event.
754                  */
755                 tcount = pps->capcount - pps->ppscount[2];
756                 pps->ppscount[2] = pps->capcount;
757                 tcount &= pps->capth->th_counter->tc_counter_mask;
758                 scale = (u_int64_t)1 << 63;
759                 scale /= pps->capth->th_counter->tc_frequency;
760                 scale *= 2;
761                 bt.sec = 0;
762                 bt.frac = 0;
763                 bintime_addx(&bt, scale * tcount);
764                 bintime2timespec(&bt, &ts);
765                 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
766         }
767 #endif
768 }
769
770 /*
771  * Timecounters need to be updated every so often to prevent the hardware
772  * counter from overflowing.  Updating also recalculates the cached values
773  * used by the get*() family of functions, so their precision depends on
774  * the update frequency.
775  */
776
777 static int tc_tick;
778 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
779     "Approximate number of hardclock ticks in a millisecond");
780
781 void
782 tc_ticktock(void)
783 {
784         static int count;
785         static time_t last_calib;
786
787         if (++count < tc_tick)
788                 return;
789         count = 0;
790         tc_windup();
791         if (time_uptime != last_calib && !(time_uptime & 0xf)) {
792                 cpu_tick_calibrate(0);
793                 last_calib = time_uptime;
794         }
795 }
796
797 static void
798 inittimecounter(void *dummy)
799 {
800         u_int p;
801
802         /*
803          * Set the initial timeout to
804          * max(1, <approx. number of hardclock ticks in a millisecond>).
805          * People should probably not use the sysctl to set the timeout
806          * to smaller than its inital value, since that value is the
807          * smallest reasonable one.  If they want better timestamps they
808          * should use the non-"get"* functions.
809          */
810         if (hz > 1000)
811                 tc_tick = (hz + 500) / 1000;
812         else
813                 tc_tick = 1;
814         p = (tc_tick * 1000000) / hz;
815         printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
816
817         /* warm up new timecounter (again) and get rolling. */
818         (void)timecounter->tc_get_timecount(timecounter);
819         (void)timecounter->tc_get_timecount(timecounter);
820 }
821
822 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
823
824 /* Cpu tick handling -------------------------------------------------*/
825
826 static int cpu_tick_variable;
827 static uint64_t cpu_tick_frequency;
828
829 static uint64_t
830 tc_cpu_ticks(void)
831 {
832         static uint64_t base;
833         static unsigned last;
834         unsigned u;
835         struct timecounter *tc;
836
837         tc = timehands->th_counter;
838         u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
839         if (u < last)
840                 base += (uint64_t)tc->tc_counter_mask + 1;
841         last = u;
842         return (u + base);
843 }
844
845 /*
846  * This function gets called every 16 seconds on only one designated
847  * CPU in the system from hardclock() via tc_ticktock().
848  *
849  * Whenever the real time clock is stepped we get called with reset=1
850  * to make sure we handle suspend/resume and similar events correctly.
851  */
852
853 static void
854 cpu_tick_calibrate(int reset)
855 {
856         static uint64_t c_last;
857         uint64_t c_this, c_delta;
858         static struct bintime  t_last;
859         struct bintime t_this, t_delta;
860         uint32_t divi;
861
862         if (reset) {
863                 /* The clock was stepped, abort & reset */
864                 t_last.sec = 0;
865                 return;
866         }
867
868         /* we don't calibrate fixed rate cputicks */
869         if (!cpu_tick_variable)
870                 return;
871
872         getbinuptime(&t_this);
873         c_this = cpu_ticks();
874         if (t_last.sec != 0) {
875                 c_delta = c_this - c_last;
876                 t_delta = t_this;
877                 bintime_sub(&t_delta, &t_last);
878                 /*
879                  * Validate that 16 +/- 1/256 seconds passed. 
880                  * After division by 16 this gives us a precision of
881                  * roughly 250PPM which is sufficient
882                  */
883                 if (t_delta.sec > 16 || (
884                     t_delta.sec == 16 && t_delta.frac >= (0x01LL << 56))) {
885                         /* too long */
886                         if (bootverbose)
887                                 printf("t_delta %ju.%016jx too long\n",
888                                     (uintmax_t)t_delta.sec,
889                                     (uintmax_t)t_delta.frac);
890                 } else if (t_delta.sec < 15 ||
891                     (t_delta.sec == 15 && t_delta.frac <= (0xffLL << 56))) {
892                         /* too short */
893                         if (bootverbose)
894                                 printf("t_delta %ju.%016jx too short\n",
895                                     (uintmax_t)t_delta.sec,
896                                     (uintmax_t)t_delta.frac);
897                 } else {
898                         /* just right */
899                         /*
900                          * Headroom:
901                          *      2^(64-20) / 16[s] =
902                          *      2^(44) / 16[s] =
903                          *      17.592.186.044.416 / 16 =
904                          *      1.099.511.627.776 [Hz]
905                          */
906                         divi = t_delta.sec << 20;
907                         divi |= t_delta.frac >> (64 - 20);
908                         c_delta <<= 20;
909                         c_delta /= divi;
910                         if (c_delta  > cpu_tick_frequency) {
911                                 if (0 && bootverbose)
912                                         printf("cpu_tick increased to %ju Hz\n",
913                                             c_delta);
914                                 cpu_tick_frequency = c_delta;
915                         }
916                 }
917         }
918         c_last = c_this;
919         t_last = t_this;
920 }
921
922 void
923 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
924 {
925
926         if (func == NULL) {
927                 cpu_ticks = tc_cpu_ticks;
928         } else {
929                 cpu_tick_frequency = freq;
930                 cpu_tick_variable = var;
931                 cpu_ticks = func;
932         }
933 }
934
935 uint64_t
936 cpu_tickrate(void)
937 {
938
939         if (cpu_ticks == tc_cpu_ticks) 
940                 return (tc_getfrequency());
941         return (cpu_tick_frequency);
942 }
943
944 /*
945  * We need to be slightly careful converting cputicks to microseconds.
946  * There is plenty of margin in 64 bits of microseconds (half a million
947  * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
948  * before divide conversion (to retain precision) we find that the
949  * margin shrinks to 1.5 hours (one millionth of 146y).
950  * With a three prong approach we never lose significant bits, no
951  * matter what the cputick rate and length of timeinterval is.
952  */
953
954 uint64_t
955 cputick2usec(uint64_t tick)
956 {
957
958         if (tick > 18446744073709551LL)         /* floor(2^64 / 1000) */
959                 return (tick / (cpu_tickrate() / 1000000LL));
960         else if (tick > 18446744073709LL)       /* floor(2^64 / 1000000) */
961                 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
962         else
963                 return ((tick * 1000000LL) / cpu_tickrate());
964 }
965
966 cpu_tick_f      *cpu_ticks = tc_cpu_ticks;