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