]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_tc.c
Style fixes and simplifications.
[FreeBSD/FreeBSD.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  * Copyright (c) 2011 The FreeBSD Foundation
10  * All rights reserved.
11  *
12  * Portions of this software were developed by Julien Ridoux at the University
13  * of Melbourne under sponsorship from the FreeBSD Foundation.
14  */
15
16 #include <sys/cdefs.h>
17 __FBSDID("$FreeBSD$");
18
19 #include "opt_ntp.h"
20 #include "opt_ffclock.h"
21
22 #include <sys/param.h>
23 #include <sys/kernel.h>
24 #ifdef FFCLOCK
25 #include <sys/lock.h>
26 #include <sys/mutex.h>
27 #endif
28 #include <sys/sysctl.h>
29 #include <sys/syslog.h>
30 #include <sys/systm.h>
31 #include <sys/timeffc.h>
32 #include <sys/timepps.h>
33 #include <sys/timetc.h>
34 #include <sys/timex.h>
35
36 /*
37  * A large step happens on boot.  This constant detects such steps.
38  * It is relatively small so that ntp_update_second gets called enough
39  * in the typical 'missed a couple of seconds' case, but doesn't loop
40  * forever when the time step is large.
41  */
42 #define LARGE_STEP      200
43
44 /*
45  * Implement a dummy timecounter which we can use until we get a real one
46  * in the air.  This allows the console and other early stuff to use
47  * time services.
48  */
49
50 static u_int
51 dummy_get_timecount(struct timecounter *tc)
52 {
53         static u_int now;
54
55         return (++now);
56 }
57
58 static struct timecounter dummy_timecounter = {
59         dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
60 };
61
62 struct timehands {
63         /* These fields must be initialized by the driver. */
64         struct timecounter      *th_counter;
65         int64_t                 th_adjustment;
66         uint64_t                th_scale;
67         u_int                   th_offset_count;
68         struct bintime          th_offset;
69         struct timeval          th_microtime;
70         struct timespec         th_nanotime;
71         /* Fields not to be copied in tc_windup start with th_generation. */
72         volatile u_int          th_generation;
73         struct timehands        *th_next;
74 };
75
76 static struct timehands th0;
77 static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
78 static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
79 static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
80 static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
81 static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
82 static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
83 static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
84 static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
85 static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
86 static struct timehands th0 = {
87         &dummy_timecounter,
88         0,
89         (uint64_t)-1 / 1000000,
90         0,
91         {1, 0},
92         {0, 0},
93         {0, 0},
94         1,
95         &th1
96 };
97
98 static struct timehands *volatile timehands = &th0;
99 struct timecounter *timecounter = &dummy_timecounter;
100 static struct timecounter *timecounters = &dummy_timecounter;
101
102 int tc_min_ticktock_freq = 1;
103
104 time_t time_second = 1;
105 time_t time_uptime = 1;
106
107 struct bintime boottimebin;
108 struct timeval boottime;
109 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
110 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
111     NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
112
113 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
114 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
115
116 static int timestepwarnings;
117 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
118     &timestepwarnings, 0, "Log time steps");
119
120 static void tc_windup(void);
121 static void cpu_tick_calibrate(int);
122
123 static int
124 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
125 {
126 #ifndef __mips__
127 #ifdef SCTL_MASK32
128         int tv[2];
129
130         if (req->flags & SCTL_MASK32) {
131                 tv[0] = boottime.tv_sec;
132                 tv[1] = boottime.tv_usec;
133                 return SYSCTL_OUT(req, tv, sizeof(tv));
134         } else
135 #endif
136 #endif
137                 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
138 }
139
140 static int
141 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
142 {
143         u_int ncount;
144         struct timecounter *tc = arg1;
145
146         ncount = tc->tc_get_timecount(tc);
147         return sysctl_handle_int(oidp, &ncount, 0, req);
148 }
149
150 static int
151 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
152 {
153         uint64_t freq;
154         struct timecounter *tc = arg1;
155
156         freq = tc->tc_frequency;
157         return sysctl_handle_64(oidp, &freq, 0, req);
158 }
159
160 /*
161  * Return the difference between the timehands' counter value now and what
162  * was when we copied it to the timehands' offset_count.
163  */
164 static __inline u_int
165 tc_delta(struct timehands *th)
166 {
167         struct timecounter *tc;
168
169         tc = th->th_counter;
170         return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
171             tc->tc_counter_mask);
172 }
173
174 /*
175  * Functions for reading the time.  We have to loop until we are sure that
176  * the timehands that we operated on was not updated under our feet.  See
177  * the comment in <sys/time.h> for a description of these 12 functions.
178  */
179
180 #ifdef FFCLOCK
181 void
182 fbclock_binuptime(struct bintime *bt)
183 {
184         struct timehands *th;
185         unsigned int gen;
186
187         do {
188                 th = timehands;
189                 gen = th->th_generation;
190                 *bt = th->th_offset;
191                 bintime_addx(bt, th->th_scale * tc_delta(th));
192         } while (gen == 0 || gen != th->th_generation);
193 }
194
195 void
196 fbclock_nanouptime(struct timespec *tsp)
197 {
198         struct bintime bt;
199
200         fbclock_binuptime(&bt);
201         bintime2timespec(&bt, tsp);
202 }
203
204 void
205 fbclock_microuptime(struct timeval *tvp)
206 {
207         struct bintime bt;
208
209         fbclock_binuptime(&bt);
210         bintime2timeval(&bt, tvp);
211 }
212
213 void
214 fbclock_bintime(struct bintime *bt)
215 {
216
217         fbclock_binuptime(bt);
218         bintime_add(bt, &boottimebin);
219 }
220
221 void
222 fbclock_nanotime(struct timespec *tsp)
223 {
224         struct bintime bt;
225
226         fbclock_bintime(&bt);
227         bintime2timespec(&bt, tsp);
228 }
229
230 void
231 fbclock_microtime(struct timeval *tvp)
232 {
233         struct bintime bt;
234
235         fbclock_bintime(&bt);
236         bintime2timeval(&bt, tvp);
237 }
238
239 void
240 fbclock_getbinuptime(struct bintime *bt)
241 {
242         struct timehands *th;
243         unsigned int gen;
244
245         do {
246                 th = timehands;
247                 gen = th->th_generation;
248                 *bt = th->th_offset;
249         } while (gen == 0 || gen != th->th_generation);
250 }
251
252 void
253 fbclock_getnanouptime(struct timespec *tsp)
254 {
255         struct timehands *th;
256         unsigned int gen;
257
258         do {
259                 th = timehands;
260                 gen = th->th_generation;
261                 bintime2timespec(&th->th_offset, tsp);
262         } while (gen == 0 || gen != th->th_generation);
263 }
264
265 void
266 fbclock_getmicrouptime(struct timeval *tvp)
267 {
268         struct timehands *th;
269         unsigned int gen;
270
271         do {
272                 th = timehands;
273                 gen = th->th_generation;
274                 bintime2timeval(&th->th_offset, tvp);
275         } while (gen == 0 || gen != th->th_generation);
276 }
277
278 void
279 fbclock_getbintime(struct bintime *bt)
280 {
281         struct timehands *th;
282         unsigned int gen;
283
284         do {
285                 th = timehands;
286                 gen = th->th_generation;
287                 *bt = th->th_offset;
288         } while (gen == 0 || gen != th->th_generation);
289         bintime_add(bt, &boottimebin);
290 }
291
292 void
293 fbclock_getnanotime(struct timespec *tsp)
294 {
295         struct timehands *th;
296         unsigned int gen;
297
298         do {
299                 th = timehands;
300                 gen = th->th_generation;
301                 *tsp = th->th_nanotime;
302         } while (gen == 0 || gen != th->th_generation);
303 }
304
305 void
306 fbclock_getmicrotime(struct timeval *tvp)
307 {
308         struct timehands *th;
309         unsigned int gen;
310
311         do {
312                 th = timehands;
313                 gen = th->th_generation;
314                 *tvp = th->th_microtime;
315         } while (gen == 0 || gen != th->th_generation);
316 }
317 #else /* !FFCLOCK */
318 void
319 binuptime(struct bintime *bt)
320 {
321         struct timehands *th;
322         u_int gen;
323
324         do {
325                 th = timehands;
326                 gen = th->th_generation;
327                 *bt = th->th_offset;
328                 bintime_addx(bt, th->th_scale * tc_delta(th));
329         } while (gen == 0 || gen != th->th_generation);
330 }
331
332 void
333 nanouptime(struct timespec *tsp)
334 {
335         struct bintime bt;
336
337         binuptime(&bt);
338         bintime2timespec(&bt, tsp);
339 }
340
341 void
342 microuptime(struct timeval *tvp)
343 {
344         struct bintime bt;
345
346         binuptime(&bt);
347         bintime2timeval(&bt, tvp);
348 }
349
350 void
351 bintime(struct bintime *bt)
352 {
353
354         binuptime(bt);
355         bintime_add(bt, &boottimebin);
356 }
357
358 void
359 nanotime(struct timespec *tsp)
360 {
361         struct bintime bt;
362
363         bintime(&bt);
364         bintime2timespec(&bt, tsp);
365 }
366
367 void
368 microtime(struct timeval *tvp)
369 {
370         struct bintime bt;
371
372         bintime(&bt);
373         bintime2timeval(&bt, tvp);
374 }
375
376 void
377 getbinuptime(struct bintime *bt)
378 {
379         struct timehands *th;
380         u_int gen;
381
382         do {
383                 th = timehands;
384                 gen = th->th_generation;
385                 *bt = th->th_offset;
386         } while (gen == 0 || gen != th->th_generation);
387 }
388
389 void
390 getnanouptime(struct timespec *tsp)
391 {
392         struct timehands *th;
393         u_int gen;
394
395         do {
396                 th = timehands;
397                 gen = th->th_generation;
398                 bintime2timespec(&th->th_offset, tsp);
399         } while (gen == 0 || gen != th->th_generation);
400 }
401
402 void
403 getmicrouptime(struct timeval *tvp)
404 {
405         struct timehands *th;
406         u_int gen;
407
408         do {
409                 th = timehands;
410                 gen = th->th_generation;
411                 bintime2timeval(&th->th_offset, tvp);
412         } while (gen == 0 || gen != th->th_generation);
413 }
414
415 void
416 getbintime(struct bintime *bt)
417 {
418         struct timehands *th;
419         u_int gen;
420
421         do {
422                 th = timehands;
423                 gen = th->th_generation;
424                 *bt = th->th_offset;
425         } while (gen == 0 || gen != th->th_generation);
426         bintime_add(bt, &boottimebin);
427 }
428
429 void
430 getnanotime(struct timespec *tsp)
431 {
432         struct timehands *th;
433         u_int gen;
434
435         do {
436                 th = timehands;
437                 gen = th->th_generation;
438                 *tsp = th->th_nanotime;
439         } while (gen == 0 || gen != th->th_generation);
440 }
441
442 void
443 getmicrotime(struct timeval *tvp)
444 {
445         struct timehands *th;
446         u_int gen;
447
448         do {
449                 th = timehands;
450                 gen = th->th_generation;
451                 *tvp = th->th_microtime;
452         } while (gen == 0 || gen != th->th_generation);
453 }
454 #endif /* FFCLOCK */
455
456 #ifdef FFCLOCK
457 /*
458  * Support for feed-forward synchronization algorithms. This is heavily inspired
459  * by the timehands mechanism but kept independent from it. *_windup() functions
460  * have some connection to avoid accessing the timecounter hardware more than
461  * necessary.
462  */
463
464 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
465 struct ffclock_estimate ffclock_estimate;
466 struct bintime ffclock_boottime;        /* Feed-forward boot time estimate. */
467 uint32_t ffclock_status;                /* Feed-forward clock status. */
468 int8_t ffclock_updated;                 /* New estimates are available. */
469 struct mtx ffclock_mtx;                 /* Mutex on ffclock_estimate. */
470
471 struct fftimehands {
472         struct ffclock_estimate cest;
473         struct bintime          tick_time;
474         struct bintime          tick_time_lerp;
475         ffcounter               tick_ffcount;
476         uint64_t                period_lerp;
477         volatile uint8_t        gen;
478         struct fftimehands      *next;
479 };
480
481 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
482
483 static struct fftimehands ffth[10];
484 static struct fftimehands *volatile fftimehands = ffth;
485
486 static void
487 ffclock_init(void)
488 {
489         struct fftimehands *cur;
490         struct fftimehands *last;
491
492         memset(ffth, 0, sizeof(ffth));
493
494         last = ffth + NUM_ELEMENTS(ffth) - 1;
495         for (cur = ffth; cur < last; cur++)
496                 cur->next = cur + 1;
497         last->next = ffth;
498
499         ffclock_updated = 0;
500         ffclock_status = FFCLOCK_STA_UNSYNC;
501         mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
502 }
503
504 /*
505  * Reset the feed-forward clock estimates. Called from inittodr() to get things
506  * kick started and uses the timecounter nominal frequency as a first period
507  * estimate. Note: this function may be called several time just after boot.
508  * Note: this is the only function that sets the value of boot time for the
509  * monotonic (i.e. uptime) version of the feed-forward clock.
510  */
511 void
512 ffclock_reset_clock(struct timespec *ts)
513 {
514         struct timecounter *tc;
515         struct ffclock_estimate cest;
516
517         tc = timehands->th_counter;
518         memset(&cest, 0, sizeof(struct ffclock_estimate));
519
520         timespec2bintime(ts, &ffclock_boottime);
521         timespec2bintime(ts, &(cest.update_time));
522         ffclock_read_counter(&cest.update_ffcount);
523         cest.leapsec_next = 0;
524         cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
525         cest.errb_abs = 0;
526         cest.errb_rate = 0;
527         cest.status = FFCLOCK_STA_UNSYNC;
528         cest.leapsec_total = 0;
529         cest.leapsec = 0;
530
531         mtx_lock(&ffclock_mtx);
532         bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
533         ffclock_updated = INT8_MAX;
534         mtx_unlock(&ffclock_mtx);
535
536         printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
537             (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
538             (unsigned long)ts->tv_nsec);
539 }
540
541 /*
542  * Sub-routine to convert a time interval measured in RAW counter units to time
543  * in seconds stored in bintime format.
544  * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
545  * larger than the max value of u_int (on 32 bit architecture). Loop to consume
546  * extra cycles.
547  */
548 static void
549 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
550 {
551         struct bintime bt2;
552         ffcounter delta, delta_max;
553
554         delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
555         bintime_clear(bt);
556         do {
557                 if (ffdelta > delta_max)
558                         delta = delta_max;
559                 else
560                         delta = ffdelta;
561                 bt2.sec = 0;
562                 bt2.frac = period;
563                 bintime_mul(&bt2, (unsigned int)delta);
564                 bintime_add(bt, &bt2);
565                 ffdelta -= delta;
566         } while (ffdelta > 0);
567 }
568
569 /*
570  * Update the fftimehands.
571  * Push the tick ffcount and time(s) forward based on current clock estimate.
572  * The conversion from ffcounter to bintime relies on the difference clock
573  * principle, whose accuracy relies on computing small time intervals. If a new
574  * clock estimate has been passed by the synchronisation daemon, make it
575  * current, and compute the linear interpolation for monotonic time if needed.
576  */
577 static void
578 ffclock_windup(unsigned int delta)
579 {
580         struct ffclock_estimate *cest;
581         struct fftimehands *ffth;
582         struct bintime bt, gap_lerp;
583         ffcounter ffdelta;
584         uint64_t frac;
585         unsigned int polling;
586         uint8_t forward_jump, ogen;
587
588         /*
589          * Pick the next timehand, copy current ffclock estimates and move tick
590          * times and counter forward.
591          */
592         forward_jump = 0;
593         ffth = fftimehands->next;
594         ogen = ffth->gen;
595         ffth->gen = 0;
596         cest = &ffth->cest;
597         bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
598         ffdelta = (ffcounter)delta;
599         ffth->period_lerp = fftimehands->period_lerp;
600
601         ffth->tick_time = fftimehands->tick_time;
602         ffclock_convert_delta(ffdelta, cest->period, &bt);
603         bintime_add(&ffth->tick_time, &bt);
604
605         ffth->tick_time_lerp = fftimehands->tick_time_lerp;
606         ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
607         bintime_add(&ffth->tick_time_lerp, &bt);
608
609         ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
610
611         /*
612          * Assess the status of the clock, if the last update is too old, it is
613          * likely the synchronisation daemon is dead and the clock is free
614          * running.
615          */
616         if (ffclock_updated == 0) {
617                 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
618                 ffclock_convert_delta(ffdelta, cest->period, &bt);
619                 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
620                         ffclock_status |= FFCLOCK_STA_UNSYNC;
621         }
622
623         /*
624          * If available, grab updated clock estimates and make them current.
625          * Recompute time at this tick using the updated estimates. The clock
626          * estimates passed the feed-forward synchronisation daemon may result
627          * in time conversion that is not monotonically increasing (just after
628          * the update). time_lerp is a particular linear interpolation over the
629          * synchronisation algo polling period that ensures monotonicity for the
630          * clock ids requesting it.
631          */
632         if (ffclock_updated > 0) {
633                 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
634                 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
635                 ffth->tick_time = cest->update_time;
636                 ffclock_convert_delta(ffdelta, cest->period, &bt);
637                 bintime_add(&ffth->tick_time, &bt);
638
639                 /* ffclock_reset sets ffclock_updated to INT8_MAX */
640                 if (ffclock_updated == INT8_MAX)
641                         ffth->tick_time_lerp = ffth->tick_time;
642
643                 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
644                         forward_jump = 1;
645                 else
646                         forward_jump = 0;
647
648                 bintime_clear(&gap_lerp);
649                 if (forward_jump) {
650                         gap_lerp = ffth->tick_time;
651                         bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
652                 } else {
653                         gap_lerp = ffth->tick_time_lerp;
654                         bintime_sub(&gap_lerp, &ffth->tick_time);
655                 }
656
657                 /*
658                  * The reset from the RTC clock may be far from accurate, and
659                  * reducing the gap between real time and interpolated time
660                  * could take a very long time if the interpolated clock insists
661                  * on strict monotonicity. The clock is reset under very strict
662                  * conditions (kernel time is known to be wrong and
663                  * synchronization daemon has been restarted recently.
664                  * ffclock_boottime absorbs the jump to ensure boot time is
665                  * correct and uptime functions stay consistent.
666                  */
667                 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
668                     ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
669                     ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
670                         if (forward_jump)
671                                 bintime_add(&ffclock_boottime, &gap_lerp);
672                         else
673                                 bintime_sub(&ffclock_boottime, &gap_lerp);
674                         ffth->tick_time_lerp = ffth->tick_time;
675                         bintime_clear(&gap_lerp);
676                 }
677
678                 ffclock_status = cest->status;
679                 ffth->period_lerp = cest->period;
680
681                 /*
682                  * Compute corrected period used for the linear interpolation of
683                  * time. The rate of linear interpolation is capped to 5000PPM
684                  * (5ms/s).
685                  */
686                 if (bintime_isset(&gap_lerp)) {
687                         ffdelta = cest->update_ffcount;
688                         ffdelta -= fftimehands->cest.update_ffcount;
689                         ffclock_convert_delta(ffdelta, cest->period, &bt);
690                         polling = bt.sec;
691                         bt.sec = 0;
692                         bt.frac = 5000000 * (uint64_t)18446744073LL;
693                         bintime_mul(&bt, polling);
694                         if (bintime_cmp(&gap_lerp, &bt, >))
695                                 gap_lerp = bt;
696
697                         /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
698                         frac = 0;
699                         if (gap_lerp.sec > 0) {
700                                 frac -= 1;
701                                 frac /= ffdelta / gap_lerp.sec;
702                         }
703                         frac += gap_lerp.frac / ffdelta;
704
705                         if (forward_jump)
706                                 ffth->period_lerp += frac;
707                         else
708                                 ffth->period_lerp -= frac;
709                 }
710
711                 ffclock_updated = 0;
712         }
713         if (++ogen == 0)
714                 ogen = 1;
715         ffth->gen = ogen;
716         fftimehands = ffth;
717 }
718
719 /*
720  * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
721  * the old and new hardware counter cannot be read simultaneously. tc_windup()
722  * does read the two counters 'back to back', but a few cycles are effectively
723  * lost, and not accumulated in tick_ffcount. This is a fairly radical
724  * operation for a feed-forward synchronization daemon, and it is its job to not
725  * pushing irrelevant data to the kernel. Because there is no locking here,
726  * simply force to ignore pending or next update to give daemon a chance to
727  * realize the counter has changed.
728  */
729 static void
730 ffclock_change_tc(struct timehands *th)
731 {
732         struct fftimehands *ffth;
733         struct ffclock_estimate *cest;
734         struct timecounter *tc;
735         uint8_t ogen;
736
737         tc = th->th_counter;
738         ffth = fftimehands->next;
739         ogen = ffth->gen;
740         ffth->gen = 0;
741
742         cest = &ffth->cest;
743         bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
744         cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
745         cest->errb_abs = 0;
746         cest->errb_rate = 0;
747         cest->status |= FFCLOCK_STA_UNSYNC;
748
749         ffth->tick_ffcount = fftimehands->tick_ffcount;
750         ffth->tick_time_lerp = fftimehands->tick_time_lerp;
751         ffth->tick_time = fftimehands->tick_time;
752         ffth->period_lerp = cest->period;
753
754         /* Do not lock but ignore next update from synchronization daemon. */
755         ffclock_updated--;
756
757         if (++ogen == 0)
758                 ogen = 1;
759         ffth->gen = ogen;
760         fftimehands = ffth;
761 }
762
763 /*
764  * Retrieve feed-forward counter and time of last kernel tick.
765  */
766 void
767 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
768 {
769         struct fftimehands *ffth;
770         uint8_t gen;
771
772         /*
773          * No locking but check generation has not changed. Also need to make
774          * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
775          */
776         do {
777                 ffth = fftimehands;
778                 gen = ffth->gen;
779                 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
780                         *bt = ffth->tick_time_lerp;
781                 else
782                         *bt = ffth->tick_time;
783                 *ffcount = ffth->tick_ffcount;
784         } while (gen == 0 || gen != ffth->gen);
785 }
786
787 /*
788  * Absolute clock conversion. Low level function to convert ffcounter to
789  * bintime. The ffcounter is converted using the current ffclock period estimate
790  * or the "interpolated period" to ensure monotonicity.
791  * NOTE: this conversion may have been deferred, and the clock updated since the
792  * hardware counter has been read.
793  */
794 void
795 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
796 {
797         struct fftimehands *ffth;
798         struct bintime bt2;
799         ffcounter ffdelta;
800         uint8_t gen;
801
802         /*
803          * No locking but check generation has not changed. Also need to make
804          * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
805          */
806         do {
807                 ffth = fftimehands;
808                 gen = ffth->gen;
809                 if (ffcount > ffth->tick_ffcount)
810                         ffdelta = ffcount - ffth->tick_ffcount;
811                 else
812                         ffdelta = ffth->tick_ffcount - ffcount;
813
814                 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
815                         *bt = ffth->tick_time_lerp;
816                         ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
817                 } else {
818                         *bt = ffth->tick_time;
819                         ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
820                 }
821
822                 if (ffcount > ffth->tick_ffcount)
823                         bintime_add(bt, &bt2);
824                 else
825                         bintime_sub(bt, &bt2);
826         } while (gen == 0 || gen != ffth->gen);
827 }
828
829 /*
830  * Difference clock conversion.
831  * Low level function to Convert a time interval measured in RAW counter units
832  * into bintime. The difference clock allows measuring small intervals much more
833  * reliably than the absolute clock.
834  */
835 void
836 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
837 {
838         struct fftimehands *ffth;
839         uint8_t gen;
840
841         /* No locking but check generation has not changed. */
842         do {
843                 ffth = fftimehands;
844                 gen = ffth->gen;
845                 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
846         } while (gen == 0 || gen != ffth->gen);
847 }
848
849 /*
850  * Access to current ffcounter value.
851  */
852 void
853 ffclock_read_counter(ffcounter *ffcount)
854 {
855         struct timehands *th;
856         struct fftimehands *ffth;
857         unsigned int gen, delta;
858
859         /*
860          * ffclock_windup() called from tc_windup(), safe to rely on
861          * th->th_generation only, for correct delta and ffcounter.
862          */
863         do {
864                 th = timehands;
865                 gen = th->th_generation;
866                 ffth = fftimehands;
867                 delta = tc_delta(th);
868                 *ffcount = ffth->tick_ffcount;
869         } while (gen == 0 || gen != th->th_generation);
870
871         *ffcount += delta;
872 }
873
874 void
875 binuptime(struct bintime *bt)
876 {
877
878         binuptime_fromclock(bt, sysclock_active);
879 }
880
881 void
882 nanouptime(struct timespec *tsp)
883 {
884
885         nanouptime_fromclock(tsp, sysclock_active);
886 }
887
888 void
889 microuptime(struct timeval *tvp)
890 {
891
892         microuptime_fromclock(tvp, sysclock_active);
893 }
894
895 void
896 bintime(struct bintime *bt)
897 {
898
899         bintime_fromclock(bt, sysclock_active);
900 }
901
902 void
903 nanotime(struct timespec *tsp)
904 {
905
906         nanotime_fromclock(tsp, sysclock_active);
907 }
908
909 void
910 microtime(struct timeval *tvp)
911 {
912
913         microtime_fromclock(tvp, sysclock_active);
914 }
915
916 void
917 getbinuptime(struct bintime *bt)
918 {
919
920         getbinuptime_fromclock(bt, sysclock_active);
921 }
922
923 void
924 getnanouptime(struct timespec *tsp)
925 {
926
927         getnanouptime_fromclock(tsp, sysclock_active);
928 }
929
930 void
931 getmicrouptime(struct timeval *tvp)
932 {
933
934         getmicrouptime_fromclock(tvp, sysclock_active);
935 }
936
937 void
938 getbintime(struct bintime *bt)
939 {
940
941         getbintime_fromclock(bt, sysclock_active);
942 }
943
944 void
945 getnanotime(struct timespec *tsp)
946 {
947
948         getnanotime_fromclock(tsp, sysclock_active);
949 }
950
951 void
952 getmicrotime(struct timeval *tvp)
953 {
954
955         getmicrouptime_fromclock(tvp, sysclock_active);
956 }
957
958 #endif /* FFCLOCK */
959
960 /*
961  * System clock currently providing time to the system. Modifiable via sysctl
962  * when the FFCLOCK option is defined.
963  */
964 int sysclock_active = SYSCLOCK_FBCK;
965
966 /* Internal NTP status and error estimates. */
967 extern int time_status;
968 extern long time_esterror;
969
970 /*
971  * Take a snapshot of sysclock data which can be used to compare system clocks
972  * and generate timestamps after the fact.
973  */
974 void
975 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
976 {
977         struct fbclock_info *fbi;
978         struct timehands *th;
979         struct bintime bt;
980         unsigned int delta, gen;
981 #ifdef FFCLOCK
982         ffcounter ffcount;
983         struct fftimehands *ffth;
984         struct ffclock_info *ffi;
985         struct ffclock_estimate cest;
986
987         ffi = &clock_snap->ff_info;
988 #endif
989
990         fbi = &clock_snap->fb_info;
991         delta = 0;
992
993         do {
994                 th = timehands;
995                 gen = th->th_generation;
996                 fbi->th_scale = th->th_scale;
997                 fbi->tick_time = th->th_offset;
998 #ifdef FFCLOCK
999                 ffth = fftimehands;
1000                 ffi->tick_time = ffth->tick_time_lerp;
1001                 ffi->tick_time_lerp = ffth->tick_time_lerp;
1002                 ffi->period = ffth->cest.period;
1003                 ffi->period_lerp = ffth->period_lerp;
1004                 clock_snap->ffcount = ffth->tick_ffcount;
1005                 cest = ffth->cest;
1006 #endif
1007                 if (!fast)
1008                         delta = tc_delta(th);
1009         } while (gen == 0 || gen != th->th_generation);
1010
1011         clock_snap->delta = delta;
1012         clock_snap->sysclock_active = sysclock_active;
1013
1014         /* Record feedback clock status and error. */
1015         clock_snap->fb_info.status = time_status;
1016         /* XXX: Very crude estimate of feedback clock error. */
1017         bt.sec = time_esterror / 1000000;
1018         bt.frac = ((time_esterror - bt.sec) * 1000000) *
1019             (uint64_t)18446744073709ULL;
1020         clock_snap->fb_info.error = bt;
1021
1022 #ifdef FFCLOCK
1023         if (!fast)
1024                 clock_snap->ffcount += delta;
1025
1026         /* Record feed-forward clock leap second adjustment. */
1027         ffi->leapsec_adjustment = cest.leapsec_total;
1028         if (clock_snap->ffcount > cest.leapsec_next)
1029                 ffi->leapsec_adjustment -= cest.leapsec;
1030
1031         /* Record feed-forward clock status and error. */
1032         clock_snap->ff_info.status = cest.status;
1033         ffcount = clock_snap->ffcount - cest.update_ffcount;
1034         ffclock_convert_delta(ffcount, cest.period, &bt);
1035         /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1036         bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1037         /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1038         bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1039         clock_snap->ff_info.error = bt;
1040 #endif
1041 }
1042
1043 /*
1044  * Convert a sysclock snapshot into a struct bintime based on the specified
1045  * clock source and flags.
1046  */
1047 int
1048 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1049     int whichclock, uint32_t flags)
1050 {
1051 #ifdef FFCLOCK
1052         struct bintime bt2;
1053         uint64_t period;
1054 #endif
1055
1056         switch (whichclock) {
1057         case SYSCLOCK_FBCK:
1058                 *bt = cs->fb_info.tick_time;
1059
1060                 /* If snapshot was created with !fast, delta will be >0. */
1061                 if (cs->delta > 0)
1062                         bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1063
1064                 if ((flags & FBCLOCK_UPTIME) == 0)
1065                         bintime_add(bt, &boottimebin);
1066                 break;
1067 #ifdef FFCLOCK
1068         case SYSCLOCK_FFWD:
1069                 if (flags & FFCLOCK_LERP) {
1070                         *bt = cs->ff_info.tick_time_lerp;
1071                         period = cs->ff_info.period_lerp;
1072                 } else {
1073                         *bt = cs->ff_info.tick_time;
1074                         period = cs->ff_info.period;
1075                 }
1076
1077                 /* If snapshot was created with !fast, delta will be >0. */
1078                 if (cs->delta > 0) {
1079                         ffclock_convert_delta(cs->delta, period, &bt2);
1080                         bintime_add(bt, &bt2);
1081                 }
1082
1083                 /* Leap second adjustment. */
1084                 if (flags & FFCLOCK_LEAPSEC)
1085                         bt->sec -= cs->ff_info.leapsec_adjustment;
1086
1087                 /* Boot time adjustment, for uptime/monotonic clocks. */
1088                 if (flags & FFCLOCK_UPTIME)
1089                         bintime_sub(bt, &ffclock_boottime);
1090                 break;
1091 #endif
1092         default:
1093                 return (EINVAL);
1094                 break;
1095         }
1096
1097         return (0);
1098 }
1099
1100 /*
1101  * Initialize a new timecounter and possibly use it.
1102  */
1103 void
1104 tc_init(struct timecounter *tc)
1105 {
1106         u_int u;
1107         struct sysctl_oid *tc_root;
1108
1109         u = tc->tc_frequency / tc->tc_counter_mask;
1110         /* XXX: We need some margin here, 10% is a guess */
1111         u *= 11;
1112         u /= 10;
1113         if (u > hz && tc->tc_quality >= 0) {
1114                 tc->tc_quality = -2000;
1115                 if (bootverbose) {
1116                         printf("Timecounter \"%s\" frequency %ju Hz",
1117                             tc->tc_name, (uintmax_t)tc->tc_frequency);
1118                         printf(" -- Insufficient hz, needs at least %u\n", u);
1119                 }
1120         } else if (tc->tc_quality >= 0 || bootverbose) {
1121                 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1122                     tc->tc_name, (uintmax_t)tc->tc_frequency,
1123                     tc->tc_quality);
1124         }
1125
1126         tc->tc_next = timecounters;
1127         timecounters = tc;
1128         /*
1129          * Set up sysctl tree for this counter.
1130          */
1131         tc_root = SYSCTL_ADD_NODE(NULL,
1132             SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1133             CTLFLAG_RW, 0, "timecounter description");
1134         SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1135             "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1136             "mask for implemented bits");
1137         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1138             "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1139             sysctl_kern_timecounter_get, "IU", "current timecounter value");
1140         SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1141             "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1142              sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1143         SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1144             "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1145             "goodness of time counter");
1146         /*
1147          * Never automatically use a timecounter with negative quality.
1148          * Even though we run on the dummy counter, switching here may be
1149          * worse since this timecounter may not be monotonous.
1150          */
1151         if (tc->tc_quality < 0)
1152                 return;
1153         if (tc->tc_quality < timecounter->tc_quality)
1154                 return;
1155         if (tc->tc_quality == timecounter->tc_quality &&
1156             tc->tc_frequency < timecounter->tc_frequency)
1157                 return;
1158         (void)tc->tc_get_timecount(tc);
1159         (void)tc->tc_get_timecount(tc);
1160         timecounter = tc;
1161 }
1162
1163 /* Report the frequency of the current timecounter. */
1164 uint64_t
1165 tc_getfrequency(void)
1166 {
1167
1168         return (timehands->th_counter->tc_frequency);
1169 }
1170
1171 /*
1172  * Step our concept of UTC.  This is done by modifying our estimate of
1173  * when we booted.
1174  * XXX: not locked.
1175  */
1176 void
1177 tc_setclock(struct timespec *ts)
1178 {
1179         struct timespec tbef, taft;
1180         struct bintime bt, bt2;
1181
1182         cpu_tick_calibrate(1);
1183         nanotime(&tbef);
1184         timespec2bintime(ts, &bt);
1185         binuptime(&bt2);
1186         bintime_sub(&bt, &bt2);
1187         bintime_add(&bt2, &boottimebin);
1188         boottimebin = bt;
1189         bintime2timeval(&bt, &boottime);
1190
1191         /* XXX fiddle all the little crinkly bits around the fiords... */
1192         tc_windup();
1193         nanotime(&taft);
1194         if (timestepwarnings) {
1195                 log(LOG_INFO,
1196                     "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1197                     (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1198                     (intmax_t)taft.tv_sec, taft.tv_nsec,
1199                     (intmax_t)ts->tv_sec, ts->tv_nsec);
1200         }
1201         cpu_tick_calibrate(1);
1202 }
1203
1204 /*
1205  * Initialize the next struct timehands in the ring and make
1206  * it the active timehands.  Along the way we might switch to a different
1207  * timecounter and/or do seconds processing in NTP.  Slightly magic.
1208  */
1209 static void
1210 tc_windup(void)
1211 {
1212         struct bintime bt;
1213         struct timehands *th, *tho;
1214         uint64_t scale;
1215         u_int delta, ncount, ogen;
1216         int i;
1217         time_t t;
1218
1219         /*
1220          * Make the next timehands a copy of the current one, but do not
1221          * overwrite the generation or next pointer.  While we update
1222          * the contents, the generation must be zero.
1223          */
1224         tho = timehands;
1225         th = tho->th_next;
1226         ogen = th->th_generation;
1227         th->th_generation = 0;
1228         bcopy(tho, th, offsetof(struct timehands, th_generation));
1229
1230         /*
1231          * Capture a timecounter delta on the current timecounter and if
1232          * changing timecounters, a counter value from the new timecounter.
1233          * Update the offset fields accordingly.
1234          */
1235         delta = tc_delta(th);
1236         if (th->th_counter != timecounter)
1237                 ncount = timecounter->tc_get_timecount(timecounter);
1238         else
1239                 ncount = 0;
1240 #ifdef FFCLOCK
1241         ffclock_windup(delta);
1242 #endif
1243         th->th_offset_count += delta;
1244         th->th_offset_count &= th->th_counter->tc_counter_mask;
1245         while (delta > th->th_counter->tc_frequency) {
1246                 /* Eat complete unadjusted seconds. */
1247                 delta -= th->th_counter->tc_frequency;
1248                 th->th_offset.sec++;
1249         }
1250         if ((delta > th->th_counter->tc_frequency / 2) &&
1251             (th->th_scale * delta < ((uint64_t)1 << 63))) {
1252                 /* The product th_scale * delta just barely overflows. */
1253                 th->th_offset.sec++;
1254         }
1255         bintime_addx(&th->th_offset, th->th_scale * delta);
1256
1257         /*
1258          * Hardware latching timecounters may not generate interrupts on
1259          * PPS events, so instead we poll them.  There is a finite risk that
1260          * the hardware might capture a count which is later than the one we
1261          * got above, and therefore possibly in the next NTP second which might
1262          * have a different rate than the current NTP second.  It doesn't
1263          * matter in practice.
1264          */
1265         if (tho->th_counter->tc_poll_pps)
1266                 tho->th_counter->tc_poll_pps(tho->th_counter);
1267
1268         /*
1269          * Deal with NTP second processing.  The for loop normally
1270          * iterates at most once, but in extreme situations it might
1271          * keep NTP sane if timeouts are not run for several seconds.
1272          * At boot, the time step can be large when the TOD hardware
1273          * has been read, so on really large steps, we call
1274          * ntp_update_second only twice.  We need to call it twice in
1275          * case we missed a leap second.
1276          */
1277         bt = th->th_offset;
1278         bintime_add(&bt, &boottimebin);
1279         i = bt.sec - tho->th_microtime.tv_sec;
1280         if (i > LARGE_STEP)
1281                 i = 2;
1282         for (; i > 0; i--) {
1283                 t = bt.sec;
1284                 ntp_update_second(&th->th_adjustment, &bt.sec);
1285                 if (bt.sec != t)
1286                         boottimebin.sec += bt.sec - t;
1287         }
1288         /* Update the UTC timestamps used by the get*() functions. */
1289         /* XXX shouldn't do this here.  Should force non-`get' versions. */
1290         bintime2timeval(&bt, &th->th_microtime);
1291         bintime2timespec(&bt, &th->th_nanotime);
1292
1293         /* Now is a good time to change timecounters. */
1294         if (th->th_counter != timecounter) {
1295 #ifndef __arm__
1296                 if ((timecounter->tc_flags & TC_FLAGS_C3STOP) != 0)
1297                         cpu_disable_deep_sleep++;
1298                 if ((th->th_counter->tc_flags & TC_FLAGS_C3STOP) != 0)
1299                         cpu_disable_deep_sleep--;
1300 #endif
1301                 th->th_counter = timecounter;
1302                 th->th_offset_count = ncount;
1303                 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1304                     (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1305 #ifdef FFCLOCK
1306                 ffclock_change_tc(th);
1307 #endif
1308         }
1309
1310         /*-
1311          * Recalculate the scaling factor.  We want the number of 1/2^64
1312          * fractions of a second per period of the hardware counter, taking
1313          * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1314          * processing provides us with.
1315          *
1316          * The th_adjustment is nanoseconds per second with 32 bit binary
1317          * fraction and we want 64 bit binary fraction of second:
1318          *
1319          *       x = a * 2^32 / 10^9 = a * 4.294967296
1320          *
1321          * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1322          * we can only multiply by about 850 without overflowing, that
1323          * leaves no suitably precise fractions for multiply before divide.
1324          *
1325          * Divide before multiply with a fraction of 2199/512 results in a
1326          * systematic undercompensation of 10PPM of th_adjustment.  On a
1327          * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
1328          *
1329          * We happily sacrifice the lowest of the 64 bits of our result
1330          * to the goddess of code clarity.
1331          *
1332          */
1333         scale = (uint64_t)1 << 63;
1334         scale += (th->th_adjustment / 1024) * 2199;
1335         scale /= th->th_counter->tc_frequency;
1336         th->th_scale = scale * 2;
1337
1338         /*
1339          * Now that the struct timehands is again consistent, set the new
1340          * generation number, making sure to not make it zero.
1341          */
1342         if (++ogen == 0)
1343                 ogen = 1;
1344         th->th_generation = ogen;
1345
1346         /* Go live with the new struct timehands. */
1347 #ifdef FFCLOCK
1348         switch (sysclock_active) {
1349         case SYSCLOCK_FBCK:
1350 #endif
1351                 time_second = th->th_microtime.tv_sec;
1352                 time_uptime = th->th_offset.sec;
1353 #ifdef FFCLOCK
1354                 break;
1355         case SYSCLOCK_FFWD:
1356                 time_second = fftimehands->tick_time_lerp.sec;
1357                 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1358                 break;
1359         }
1360 #endif
1361
1362         timehands = th;
1363 }
1364
1365 /* Report or change the active timecounter hardware. */
1366 static int
1367 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1368 {
1369         char newname[32];
1370         struct timecounter *newtc, *tc;
1371         int error;
1372
1373         tc = timecounter;
1374         strlcpy(newname, tc->tc_name, sizeof(newname));
1375
1376         error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1377         if (error != 0 || req->newptr == NULL ||
1378             strcmp(newname, tc->tc_name) == 0)
1379                 return (error);
1380         for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1381                 if (strcmp(newname, newtc->tc_name) != 0)
1382                         continue;
1383
1384                 /* Warm up new timecounter. */
1385                 (void)newtc->tc_get_timecount(newtc);
1386                 (void)newtc->tc_get_timecount(newtc);
1387
1388                 timecounter = newtc;
1389                 return (0);
1390         }
1391         return (EINVAL);
1392 }
1393
1394 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1395     0, 0, sysctl_kern_timecounter_hardware, "A",
1396     "Timecounter hardware selected");
1397
1398
1399 /* Report or change the active timecounter hardware. */
1400 static int
1401 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1402 {
1403         char buf[32], *spc;
1404         struct timecounter *tc;
1405         int error;
1406
1407         spc = "";
1408         error = 0;
1409         for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
1410                 sprintf(buf, "%s%s(%d)",
1411                     spc, tc->tc_name, tc->tc_quality);
1412                 error = SYSCTL_OUT(req, buf, strlen(buf));
1413                 spc = " ";
1414         }
1415         return (error);
1416 }
1417
1418 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1419     0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1420
1421 /*
1422  * RFC 2783 PPS-API implementation.
1423  */
1424
1425 int
1426 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1427 {
1428         pps_params_t *app;
1429         struct pps_fetch_args *fapi;
1430 #ifdef FFCLOCK
1431         struct pps_fetch_ffc_args *fapi_ffc;
1432 #endif
1433 #ifdef PPS_SYNC
1434         struct pps_kcbind_args *kapi;
1435 #endif
1436
1437         KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1438         switch (cmd) {
1439         case PPS_IOC_CREATE:
1440                 return (0);
1441         case PPS_IOC_DESTROY:
1442                 return (0);
1443         case PPS_IOC_SETPARAMS:
1444                 app = (pps_params_t *)data;
1445                 if (app->mode & ~pps->ppscap)
1446                         return (EINVAL);
1447 #ifdef FFCLOCK
1448                 /* Ensure only a single clock is selected for ffc timestamp. */
1449                 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1450                         return (EINVAL);
1451 #endif
1452                 pps->ppsparam = *app;
1453                 return (0);
1454         case PPS_IOC_GETPARAMS:
1455                 app = (pps_params_t *)data;
1456                 *app = pps->ppsparam;
1457                 app->api_version = PPS_API_VERS_1;
1458                 return (0);
1459         case PPS_IOC_GETCAP:
1460                 *(int*)data = pps->ppscap;
1461                 return (0);
1462         case PPS_IOC_FETCH:
1463                 fapi = (struct pps_fetch_args *)data;
1464                 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1465                         return (EINVAL);
1466                 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1467                         return (EOPNOTSUPP);
1468                 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1469                 fapi->pps_info_buf = pps->ppsinfo;
1470                 return (0);
1471 #ifdef FFCLOCK
1472         case PPS_IOC_FETCH_FFCOUNTER:
1473                 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1474                 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1475                     PPS_TSFMT_TSPEC)
1476                         return (EINVAL);
1477                 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1478                         return (EOPNOTSUPP);
1479                 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1480                 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1481                 /* Overwrite timestamps if feedback clock selected. */
1482                 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1483                 case PPS_TSCLK_FBCK:
1484                         fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1485                             pps->ppsinfo.assert_timestamp;
1486                         fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1487                             pps->ppsinfo.clear_timestamp;
1488                         break;
1489                 case PPS_TSCLK_FFWD:
1490                         break;
1491                 default:
1492                         break;
1493                 }
1494                 return (0);
1495 #endif /* FFCLOCK */
1496         case PPS_IOC_KCBIND:
1497 #ifdef PPS_SYNC
1498                 kapi = (struct pps_kcbind_args *)data;
1499                 /* XXX Only root should be able to do this */
1500                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1501                         return (EINVAL);
1502                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1503                         return (EINVAL);
1504                 if (kapi->edge & ~pps->ppscap)
1505                         return (EINVAL);
1506                 pps->kcmode = kapi->edge;
1507                 return (0);
1508 #else
1509                 return (EOPNOTSUPP);
1510 #endif
1511         default:
1512                 return (ENOIOCTL);
1513         }
1514 }
1515
1516 void
1517 pps_init(struct pps_state *pps)
1518 {
1519         pps->ppscap |= PPS_TSFMT_TSPEC;
1520         if (pps->ppscap & PPS_CAPTUREASSERT)
1521                 pps->ppscap |= PPS_OFFSETASSERT;
1522         if (pps->ppscap & PPS_CAPTURECLEAR)
1523                 pps->ppscap |= PPS_OFFSETCLEAR;
1524 #ifdef FFCLOCK
1525         pps->ppscap |= PPS_TSCLK_MASK;
1526 #endif
1527 }
1528
1529 void
1530 pps_capture(struct pps_state *pps)
1531 {
1532         struct timehands *th;
1533
1534         KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1535         th = timehands;
1536         pps->capgen = th->th_generation;
1537         pps->capth = th;
1538 #ifdef FFCLOCK
1539         pps->capffth = fftimehands;
1540 #endif
1541         pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1542         if (pps->capgen != th->th_generation)
1543                 pps->capgen = 0;
1544 }
1545
1546 void
1547 pps_event(struct pps_state *pps, int event)
1548 {
1549         struct bintime bt;
1550         struct timespec ts, *tsp, *osp;
1551         u_int tcount, *pcount;
1552         int foff, fhard;
1553         pps_seq_t *pseq;
1554 #ifdef FFCLOCK
1555         struct timespec *tsp_ffc;
1556         pps_seq_t *pseq_ffc;
1557         ffcounter *ffcount;
1558 #endif
1559
1560         KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1561         /* If the timecounter was wound up underneath us, bail out. */
1562         if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
1563                 return;
1564
1565         /* Things would be easier with arrays. */
1566         if (event == PPS_CAPTUREASSERT) {
1567                 tsp = &pps->ppsinfo.assert_timestamp;
1568                 osp = &pps->ppsparam.assert_offset;
1569                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1570                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1571                 pcount = &pps->ppscount[0];
1572                 pseq = &pps->ppsinfo.assert_sequence;
1573 #ifdef FFCLOCK
1574                 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1575                 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1576                 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1577 #endif
1578         } else {
1579                 tsp = &pps->ppsinfo.clear_timestamp;
1580                 osp = &pps->ppsparam.clear_offset;
1581                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1582                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1583                 pcount = &pps->ppscount[1];
1584                 pseq = &pps->ppsinfo.clear_sequence;
1585 #ifdef FFCLOCK
1586                 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1587                 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1588                 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1589 #endif
1590         }
1591
1592         /*
1593          * If the timecounter changed, we cannot compare the count values, so
1594          * we have to drop the rest of the PPS-stuff until the next event.
1595          */
1596         if (pps->ppstc != pps->capth->th_counter) {
1597                 pps->ppstc = pps->capth->th_counter;
1598                 *pcount = pps->capcount;
1599                 pps->ppscount[2] = pps->capcount;
1600                 return;
1601         }
1602
1603         /* Convert the count to a timespec. */
1604         tcount = pps->capcount - pps->capth->th_offset_count;
1605         tcount &= pps->capth->th_counter->tc_counter_mask;
1606         bt = pps->capth->th_offset;
1607         bintime_addx(&bt, pps->capth->th_scale * tcount);
1608         bintime_add(&bt, &boottimebin);
1609         bintime2timespec(&bt, &ts);
1610
1611         /* If the timecounter was wound up underneath us, bail out. */
1612         if (pps->capgen != pps->capth->th_generation)
1613                 return;
1614
1615         *pcount = pps->capcount;
1616         (*pseq)++;
1617         *tsp = ts;
1618
1619         if (foff) {
1620                 timespecadd(tsp, osp);
1621                 if (tsp->tv_nsec < 0) {
1622                         tsp->tv_nsec += 1000000000;
1623                         tsp->tv_sec -= 1;
1624                 }
1625         }
1626
1627 #ifdef FFCLOCK
1628         *ffcount = pps->capffth->tick_ffcount + tcount;
1629         bt = pps->capffth->tick_time;
1630         ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1631         bintime_add(&bt, &pps->capffth->tick_time);
1632         bintime2timespec(&bt, &ts);
1633         (*pseq_ffc)++;
1634         *tsp_ffc = ts;
1635 #endif
1636
1637 #ifdef PPS_SYNC
1638         if (fhard) {
1639                 uint64_t scale;
1640
1641                 /*
1642                  * Feed the NTP PLL/FLL.
1643                  * The FLL wants to know how many (hardware) nanoseconds
1644                  * elapsed since the previous event.
1645                  */
1646                 tcount = pps->capcount - pps->ppscount[2];
1647                 pps->ppscount[2] = pps->capcount;
1648                 tcount &= pps->capth->th_counter->tc_counter_mask;
1649                 scale = (uint64_t)1 << 63;
1650                 scale /= pps->capth->th_counter->tc_frequency;
1651                 scale *= 2;
1652                 bt.sec = 0;
1653                 bt.frac = 0;
1654                 bintime_addx(&bt, scale * tcount);
1655                 bintime2timespec(&bt, &ts);
1656                 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1657         }
1658 #endif
1659 }
1660
1661 /*
1662  * Timecounters need to be updated every so often to prevent the hardware
1663  * counter from overflowing.  Updating also recalculates the cached values
1664  * used by the get*() family of functions, so their precision depends on
1665  * the update frequency.
1666  */
1667
1668 static int tc_tick;
1669 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1670     "Approximate number of hardclock ticks in a millisecond");
1671
1672 void
1673 tc_ticktock(int cnt)
1674 {
1675         static int count;
1676
1677         count += cnt;
1678         if (count < tc_tick)
1679                 return;
1680         count = 0;
1681         tc_windup();
1682 }
1683
1684 static void
1685 inittimecounter(void *dummy)
1686 {
1687         u_int p;
1688
1689         /*
1690          * Set the initial timeout to
1691          * max(1, <approx. number of hardclock ticks in a millisecond>).
1692          * People should probably not use the sysctl to set the timeout
1693          * to smaller than its inital value, since that value is the
1694          * smallest reasonable one.  If they want better timestamps they
1695          * should use the non-"get"* functions.
1696          */
1697         if (hz > 1000)
1698                 tc_tick = (hz + 500) / 1000;
1699         else
1700                 tc_tick = 1;
1701         p = (tc_tick * 1000000) / hz;
1702         printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1703
1704 #ifdef FFCLOCK
1705         ffclock_init();
1706 #endif
1707         /* warm up new timecounter (again) and get rolling. */
1708         (void)timecounter->tc_get_timecount(timecounter);
1709         (void)timecounter->tc_get_timecount(timecounter);
1710         tc_windup();
1711 }
1712
1713 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1714
1715 /* Cpu tick handling -------------------------------------------------*/
1716
1717 static int cpu_tick_variable;
1718 static uint64_t cpu_tick_frequency;
1719
1720 static uint64_t
1721 tc_cpu_ticks(void)
1722 {
1723         static uint64_t base;
1724         static unsigned last;
1725         unsigned u;
1726         struct timecounter *tc;
1727
1728         tc = timehands->th_counter;
1729         u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1730         if (u < last)
1731                 base += (uint64_t)tc->tc_counter_mask + 1;
1732         last = u;
1733         return (u + base);
1734 }
1735
1736 void
1737 cpu_tick_calibration(void)
1738 {
1739         static time_t last_calib;
1740
1741         if (time_uptime != last_calib && !(time_uptime & 0xf)) {
1742                 cpu_tick_calibrate(0);
1743                 last_calib = time_uptime;
1744         }
1745 }
1746
1747 /*
1748  * This function gets called every 16 seconds on only one designated
1749  * CPU in the system from hardclock() via cpu_tick_calibration()().
1750  *
1751  * Whenever the real time clock is stepped we get called with reset=1
1752  * to make sure we handle suspend/resume and similar events correctly.
1753  */
1754
1755 static void
1756 cpu_tick_calibrate(int reset)
1757 {
1758         static uint64_t c_last;
1759         uint64_t c_this, c_delta;
1760         static struct bintime  t_last;
1761         struct bintime t_this, t_delta;
1762         uint32_t divi;
1763
1764         if (reset) {
1765                 /* The clock was stepped, abort & reset */
1766                 t_last.sec = 0;
1767                 return;
1768         }
1769
1770         /* we don't calibrate fixed rate cputicks */
1771         if (!cpu_tick_variable)
1772                 return;
1773
1774         getbinuptime(&t_this);
1775         c_this = cpu_ticks();
1776         if (t_last.sec != 0) {
1777                 c_delta = c_this - c_last;
1778                 t_delta = t_this;
1779                 bintime_sub(&t_delta, &t_last);
1780                 /*
1781                  * Headroom:
1782                  *      2^(64-20) / 16[s] =
1783                  *      2^(44) / 16[s] =
1784                  *      17.592.186.044.416 / 16 =
1785                  *      1.099.511.627.776 [Hz]
1786                  */
1787                 divi = t_delta.sec << 20;
1788                 divi |= t_delta.frac >> (64 - 20);
1789                 c_delta <<= 20;
1790                 c_delta /= divi;
1791                 if (c_delta > cpu_tick_frequency) {
1792                         if (0 && bootverbose)
1793                                 printf("cpu_tick increased to %ju Hz\n",
1794                                     c_delta);
1795                         cpu_tick_frequency = c_delta;
1796                 }
1797         }
1798         c_last = c_this;
1799         t_last = t_this;
1800 }
1801
1802 void
1803 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
1804 {
1805
1806         if (func == NULL) {
1807                 cpu_ticks = tc_cpu_ticks;
1808         } else {
1809                 cpu_tick_frequency = freq;
1810                 cpu_tick_variable = var;
1811                 cpu_ticks = func;
1812         }
1813 }
1814
1815 uint64_t
1816 cpu_tickrate(void)
1817 {
1818
1819         if (cpu_ticks == tc_cpu_ticks) 
1820                 return (tc_getfrequency());
1821         return (cpu_tick_frequency);
1822 }
1823
1824 /*
1825  * We need to be slightly careful converting cputicks to microseconds.
1826  * There is plenty of margin in 64 bits of microseconds (half a million
1827  * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
1828  * before divide conversion (to retain precision) we find that the
1829  * margin shrinks to 1.5 hours (one millionth of 146y).
1830  * With a three prong approach we never lose significant bits, no
1831  * matter what the cputick rate and length of timeinterval is.
1832  */
1833
1834 uint64_t
1835 cputick2usec(uint64_t tick)
1836 {
1837
1838         if (tick > 18446744073709551LL)         /* floor(2^64 / 1000) */
1839                 return (tick / (cpu_tickrate() / 1000000LL));
1840         else if (tick > 18446744073709LL)       /* floor(2^64 / 1000000) */
1841                 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
1842         else
1843                 return ((tick * 1000000LL) / cpu_tickrate());
1844 }
1845
1846 cpu_tick_f      *cpu_ticks = tc_cpu_ticks;