source: rtems/cpukit/score/src/kern_tc.c @ b48aeaf

5
Last change on this file since b48aeaf was b48aeaf, checked in by Konstantin Belousov <kib@…>, on 07/27/16 at 11:49:41

timecounter: Merge FreeBSD change r303387

Prevent parallel tc_windup() calls, both parallel top-level calls from setclock() and from simultaneous top-level and interrupt. For this, tc_windup() is protected with a tc_setclock_mtx spinlock, in the try mode when called from hardclock interrupt. If spinlock cannot be obtained without spinning from the interrupt context, this means that top-level executes tc_windup() on other core and our try may be avoided.

The boottimebin and boottime variables should be adjusted from
tc_windup(). To be correct, they must be part of the timehands and
read using lockless protocol. Remove the globals and reimplement the
getboottime(9)/getboottimebin(9) KPI using the timehands read
protocol.

Tested by: pho (as part of the whole patch)
Reviewed by: jhb (same)
Discussed wit: bde
Sponsored by: The FreeBSD Foundation
MFC after: 1 month
X-Differential revision: https://reviews.freebsd.org/D7302

Update #3175.

  • Property mode set to 100644
File size: 60.6 KB
Line 
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#ifdef __rtems__
17#include <sys/lock.h>
18#define _KERNEL
19#define binuptime(_bt) _Timecounter_Binuptime(_bt)
20#define nanouptime(_tsp) _Timecounter_Nanouptime(_tsp)
21#define microuptime(_tvp) _Timecounter_Microuptime(_tvp)
22#define bintime(_bt) _Timecounter_Bintime(_bt)
23#define nanotime(_tsp) _Timecounter_Nanotime(_tsp)
24#define microtime(_tvp) _Timecounter_Microtime(_tvp)
25#define getbinuptime(_bt) _Timecounter_Getbinuptime(_bt)
26#define getnanouptime(_tsp) _Timecounter_Getnanouptime(_tsp)
27#define getmicrouptime(_tvp) _Timecounter_Getmicrouptime(_tvp)
28#define getbintime(_bt) _Timecounter_Getbintime(_bt)
29#define getnanotime(_tsp) _Timecounter_Getnanotime(_tsp)
30#define getmicrotime(_tvp) _Timecounter_Getmicrotime(_tvp)
31#define getboottime(_tvp) _Timecounter_Getboottime(_tvp)
32#define getboottimebin(_bt) _Timecounter_Getboottimebin(_bt)
33#define tc_init _Timecounter_Install
34#define timecounter _Timecounter
35#define time_second _Timecounter_Time_second
36#define time_uptime _Timecounter_Time_uptime
37#include <rtems/score/timecounterimpl.h>
38#include <rtems/score/atomic.h>
39#include <rtems/score/smp.h>
40#include <rtems/score/todimpl.h>
41#include <rtems/score/watchdogimpl.h>
42#endif /* __rtems__ */
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD r284178 2015-06-09T11:49:56Z$");
45
46#include "opt_compat.h"
47#include "opt_ntp.h"
48#include "opt_ffclock.h"
49
50#include <sys/param.h>
51#ifndef __rtems__
52#include <sys/kernel.h>
53#include <sys/limits.h>
54#include <sys/lock.h>
55#include <sys/mutex.h>
56#include <sys/sbuf.h>
57#include <sys/sysctl.h>
58#include <sys/syslog.h>
59#include <sys/systm.h>
60#endif /* __rtems__ */
61#include <sys/timeffc.h>
62#include <sys/timepps.h>
63#include <sys/timetc.h>
64#include <sys/timex.h>
65#ifndef __rtems__
66#include <sys/vdso.h>
67#endif /* __rtems__ */
68#ifdef __rtems__
69#include <limits.h>
70#include <string.h>
71#include <rtems.h>
72ISR_LOCK_DEFINE(, _Timecounter_Lock, "Timecounter")
73#define _Timecounter_Release(lock_context) \
74  _ISR_lock_Release_and_ISR_enable(&_Timecounter_Lock, lock_context)
75#define hz rtems_clock_get_ticks_per_second()
76#define printf(...)
77#define bcopy(x, y, z) memcpy(y, x, z);
78#define log(...)
79static inline int
80builtin_fls(int x)
81{
82        return x ? sizeof(x) * 8 - __builtin_clz(x) : 0;
83}
84#define fls(x) builtin_fls(x)
85/* FIXME: https://devel.rtems.org/ticket/2348 */
86#define ntp_update_second(a, b) do { (void) a; (void) b; } while (0)
87
88static inline void
89atomic_thread_fence_acq(void)
90{
91
92        _Atomic_Fence(ATOMIC_ORDER_ACQUIRE);
93}
94
95static inline void
96atomic_thread_fence_rel(void)
97{
98
99        _Atomic_Fence(ATOMIC_ORDER_RELEASE);
100}
101
102static inline u_int
103atomic_load_acq_int(Atomic_Uint *i)
104{
105
106        return (_Atomic_Load_uint(i, ATOMIC_ORDER_ACQUIRE));
107}
108
109static inline void
110atomic_store_rel_int(Atomic_Uint *i, u_int val)
111{
112
113        _Atomic_Store_uint(i, val, ATOMIC_ORDER_RELEASE);
114}
115#endif /* __rtems__ */
116
117/*
118 * A large step happens on boot.  This constant detects such steps.
119 * It is relatively small so that ntp_update_second gets called enough
120 * in the typical 'missed a couple of seconds' case, but doesn't loop
121 * forever when the time step is large.
122 */
123#define LARGE_STEP      200
124
125/*
126 * Implement a dummy timecounter which we can use until we get a real one
127 * in the air.  This allows the console and other early stuff to use
128 * time services.
129 */
130
131static uint32_t
132dummy_get_timecount(struct timecounter *tc)
133{
134#ifndef __rtems__
135        static uint32_t now;
136
137        return (++now);
138#else /* __rtems__ */
139        return 0;
140#endif /* __rtems__ */
141}
142
143static struct timecounter dummy_timecounter = {
144        dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
145};
146
147struct timehands {
148        /* These fields must be initialized by the driver. */
149        struct timecounter      *th_counter;
150        int64_t                 th_adjustment;
151        uint64_t                th_scale;
152        uint32_t                th_offset_count;
153        struct bintime          th_offset;
154        struct timeval          th_microtime;
155        struct timespec         th_nanotime;
156        struct bintime          th_boottime;
157        /* Fields not to be copied in tc_windup start with th_generation. */
158#ifndef __rtems__
159        u_int                   th_generation;
160#else /* __rtems__ */
161        Atomic_Uint             th_generation;
162#endif /* __rtems__ */
163        struct timehands        *th_next;
164};
165
166#if defined(RTEMS_SMP)
167static struct timehands th0;
168static struct timehands th1 = {
169        .th_next = &th0
170};
171#endif
172static struct timehands th0 = {
173        .th_counter = &dummy_timecounter,
174        .th_scale = (uint64_t)-1 / 1000000,
175        .th_offset = { .sec = 1 },
176        .th_generation = 1,
177#ifdef __rtems__
178        .th_microtime = { TOD_SECONDS_1970_THROUGH_1988, 0 },
179        .th_nanotime = { TOD_SECONDS_1970_THROUGH_1988, 0 },
180        .th_boottime = { .sec = TOD_SECONDS_1970_THROUGH_1988 - 1 },
181#endif /* __rtems__ */
182#if defined(RTEMS_SMP)
183        .th_next = &th1
184#else
185        .th_next = &th0
186#endif
187};
188
189static struct timehands *volatile timehands = &th0;
190struct timecounter *timecounter = &dummy_timecounter;
191static struct timecounter *timecounters = &dummy_timecounter;
192
193#ifndef __rtems__
194int tc_min_ticktock_freq = 1;
195#endif /* __rtems__ */
196
197#ifndef __rtems__
198volatile time_t time_second = 1;
199#else /* __rtems__ */
200volatile time_t time_second = TOD_SECONDS_1970_THROUGH_1988;
201#endif /* __rtems__ */
202volatile time_t time_uptime = 1;
203
204#ifndef __rtems__
205static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
206SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
207    NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
208
209SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
210static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
211
212static int timestepwarnings;
213SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
214    &timestepwarnings, 0, "Log time steps");
215
216struct bintime bt_timethreshold;
217struct bintime bt_tickthreshold;
218sbintime_t sbt_timethreshold;
219sbintime_t sbt_tickthreshold;
220struct bintime tc_tick_bt;
221sbintime_t tc_tick_sbt;
222int tc_precexp;
223int tc_timepercentage = TC_DEFAULTPERC;
224static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
225SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
226    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
227    sysctl_kern_timecounter_adjprecision, "I",
228    "Allowed time interval deviation in percents");
229
230static int tc_chosen;   /* Non-zero if a specific tc was chosen via sysctl. */
231#endif /* __rtems__ */
232
233static void tc_windup(struct bintime *new_boottimebin);
234#ifndef __rtems__
235static void cpu_tick_calibrate(int);
236#else /* __rtems__ */
237static void _Timecounter_Windup(struct bintime *new_boottimebin,
238    ISR_lock_Context *lock_context);
239#endif /* __rtems__ */
240
241void dtrace_getnanotime(struct timespec *tsp);
242
243#ifndef __rtems__
244static int
245sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
246{
247        struct timeval boottime;
248
249        getboottime(&boottime);
250
251#ifndef __mips__
252#ifdef SCTL_MASK32
253        int tv[2];
254
255        if (req->flags & SCTL_MASK32) {
256                tv[0] = boottime.tv_sec;
257                tv[1] = boottime.tv_usec;
258                return (SYSCTL_OUT(req, tv, sizeof(tv)));
259        }
260#endif
261#endif
262        return (SYSCTL_OUT(req, &boottime, sizeof(boottime)));
263}
264
265static int
266sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
267{
268        uint32_t ncount;
269        struct timecounter *tc = arg1;
270
271        ncount = tc->tc_get_timecount(tc);
272        return (sysctl_handle_int(oidp, &ncount, 0, req));
273}
274
275static int
276sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
277{
278        uint64_t freq;
279        struct timecounter *tc = arg1;
280
281        freq = tc->tc_frequency;
282        return (sysctl_handle_64(oidp, &freq, 0, req));
283}
284#endif /* __rtems__ */
285
286/*
287 * Return the difference between the timehands' counter value now and what
288 * was when we copied it to the timehands' offset_count.
289 */
290static __inline uint32_t
291tc_delta(struct timehands *th)
292{
293        struct timecounter *tc;
294
295        tc = th->th_counter;
296        return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
297            tc->tc_counter_mask);
298}
299
300/*
301 * Functions for reading the time.  We have to loop until we are sure that
302 * the timehands that we operated on was not updated under our feet.  See
303 * the comment in <sys/time.h> for a description of these 12 functions.
304 */
305
306#ifdef FFCLOCK
307void
308fbclock_binuptime(struct bintime *bt)
309{
310        struct timehands *th;
311        unsigned int gen;
312
313        do {
314                th = timehands;
315                gen = atomic_load_acq_int(&th->th_generation);
316                *bt = th->th_offset;
317                bintime_addx(bt, th->th_scale * tc_delta(th));
318                atomic_thread_fence_acq();
319        } while (gen == 0 || gen != th->th_generation);
320}
321
322void
323fbclock_nanouptime(struct timespec *tsp)
324{
325        struct bintime bt;
326
327        fbclock_binuptime(&bt);
328        bintime2timespec(&bt, tsp);
329}
330
331void
332fbclock_microuptime(struct timeval *tvp)
333{
334        struct bintime bt;
335
336        fbclock_binuptime(&bt);
337        bintime2timeval(&bt, tvp);
338}
339
340void
341fbclock_bintime(struct bintime *bt)
342{
343        struct timehands *th;
344        unsigned int gen;
345
346        do {
347                th = timehands;
348                gen = atomic_load_acq_int(&th->th_generation);
349                *bt = th->th_offset;
350                bintime_addx(bt, th->th_scale * tc_delta(th));
351                bintime_add(bt, &th->th_boottime);
352                atomic_thread_fence_acq();
353        } while (gen == 0 || gen != th->th_generation);
354}
355
356void
357fbclock_nanotime(struct timespec *tsp)
358{
359        struct bintime bt;
360
361        fbclock_bintime(&bt);
362        bintime2timespec(&bt, tsp);
363}
364
365void
366fbclock_microtime(struct timeval *tvp)
367{
368        struct bintime bt;
369
370        fbclock_bintime(&bt);
371        bintime2timeval(&bt, tvp);
372}
373
374void
375fbclock_getbinuptime(struct bintime *bt)
376{
377        struct timehands *th;
378        unsigned int gen;
379
380        do {
381                th = timehands;
382                gen = atomic_load_acq_int(&th->th_generation);
383                *bt = th->th_offset;
384                atomic_thread_fence_acq();
385        } while (gen == 0 || gen != th->th_generation);
386}
387
388void
389fbclock_getnanouptime(struct timespec *tsp)
390{
391        struct timehands *th;
392        unsigned int gen;
393
394        do {
395                th = timehands;
396                gen = atomic_load_acq_int(&th->th_generation);
397                bintime2timespec(&th->th_offset, tsp);
398                atomic_thread_fence_acq();
399        } while (gen == 0 || gen != th->th_generation);
400}
401
402void
403fbclock_getmicrouptime(struct timeval *tvp)
404{
405        struct timehands *th;
406        unsigned int gen;
407
408        do {
409                th = timehands;
410                gen = atomic_load_acq_int(&th->th_generation);
411                bintime2timeval(&th->th_offset, tvp);
412                atomic_thread_fence_acq();
413        } while (gen == 0 || gen != th->th_generation);
414}
415
416void
417fbclock_getbintime(struct bintime *bt)
418{
419        struct timehands *th;
420        unsigned int gen;
421
422        do {
423                th = timehands;
424                gen = atomic_load_acq_int(&th->th_generation);
425                *bt = th->th_offset;
426                bintime_add(bt, &th->th_boottime);
427                atomic_thread_fence_acq();
428        } while (gen == 0 || gen != th->th_generation);
429}
430
431void
432fbclock_getnanotime(struct timespec *tsp)
433{
434        struct timehands *th;
435        unsigned int gen;
436
437        do {
438                th = timehands;
439                gen = atomic_load_acq_int(&th->th_generation);
440                *tsp = th->th_nanotime;
441                atomic_thread_fence_acq();
442        } while (gen == 0 || gen != th->th_generation);
443}
444
445void
446fbclock_getmicrotime(struct timeval *tvp)
447{
448        struct timehands *th;
449        unsigned int gen;
450
451        do {
452                th = timehands;
453                gen = atomic_load_acq_int(&th->th_generation);
454                *tvp = th->th_microtime;
455                atomic_thread_fence_acq();
456        } while (gen == 0 || gen != th->th_generation);
457}
458#else /* !FFCLOCK */
459void
460binuptime(struct bintime *bt)
461{
462        struct timehands *th;
463        uint32_t gen;
464
465        do {
466                th = timehands;
467                gen = atomic_load_acq_int(&th->th_generation);
468                *bt = th->th_offset;
469                bintime_addx(bt, th->th_scale * tc_delta(th));
470                atomic_thread_fence_acq();
471        } while (gen == 0 || gen != th->th_generation);
472}
473#ifdef __rtems__
474sbintime_t
475_Timecounter_Sbinuptime(void)
476{
477        struct timehands *th;
478        uint32_t gen;
479        sbintime_t sbt;
480
481        do {
482                th = timehands;
483                gen = atomic_load_acq_int(&th->th_generation);
484                sbt = bttosbt(th->th_offset);
485                sbt += (th->th_scale * tc_delta(th)) >> 32;
486                atomic_thread_fence_acq();
487        } while (gen == 0 || gen != th->th_generation);
488
489        return (sbt);
490}
491#endif /* __rtems__ */
492
493void
494nanouptime(struct timespec *tsp)
495{
496        struct bintime bt;
497
498        binuptime(&bt);
499        bintime2timespec(&bt, tsp);
500}
501
502void
503microuptime(struct timeval *tvp)
504{
505        struct bintime bt;
506
507        binuptime(&bt);
508        bintime2timeval(&bt, tvp);
509}
510
511void
512bintime(struct bintime *bt)
513{
514        struct timehands *th;
515        u_int gen;
516
517        do {
518                th = timehands;
519                gen = atomic_load_acq_int(&th->th_generation);
520                *bt = th->th_offset;
521                bintime_addx(bt, th->th_scale * tc_delta(th));
522                bintime_add(bt, &th->th_boottime);
523                atomic_thread_fence_acq();
524        } while (gen == 0 || gen != th->th_generation);
525}
526
527void
528nanotime(struct timespec *tsp)
529{
530        struct bintime bt;
531
532        bintime(&bt);
533        bintime2timespec(&bt, tsp);
534}
535
536void
537microtime(struct timeval *tvp)
538{
539        struct bintime bt;
540
541        bintime(&bt);
542        bintime2timeval(&bt, tvp);
543}
544
545void
546getbinuptime(struct bintime *bt)
547{
548        struct timehands *th;
549        uint32_t gen;
550
551        do {
552                th = timehands;
553                gen = atomic_load_acq_int(&th->th_generation);
554                *bt = th->th_offset;
555                atomic_thread_fence_acq();
556        } while (gen == 0 || gen != th->th_generation);
557}
558
559void
560getnanouptime(struct timespec *tsp)
561{
562        struct timehands *th;
563        uint32_t gen;
564
565        do {
566                th = timehands;
567                gen = atomic_load_acq_int(&th->th_generation);
568                bintime2timespec(&th->th_offset, tsp);
569                atomic_thread_fence_acq();
570        } while (gen == 0 || gen != th->th_generation);
571}
572
573void
574getmicrouptime(struct timeval *tvp)
575{
576        struct timehands *th;
577        uint32_t gen;
578
579        do {
580                th = timehands;
581                gen = atomic_load_acq_int(&th->th_generation);
582                bintime2timeval(&th->th_offset, tvp);
583                atomic_thread_fence_acq();
584        } while (gen == 0 || gen != th->th_generation);
585}
586
587void
588getbintime(struct bintime *bt)
589{
590        struct timehands *th;
591        uint32_t gen;
592
593        do {
594                th = timehands;
595                gen = atomic_load_acq_int(&th->th_generation);
596                *bt = th->th_offset;
597                bintime_add(bt, &th->th_boottime);
598                atomic_thread_fence_acq();
599        } while (gen == 0 || gen != th->th_generation);
600}
601
602void
603getnanotime(struct timespec *tsp)
604{
605        struct timehands *th;
606        uint32_t gen;
607
608        do {
609                th = timehands;
610                gen = atomic_load_acq_int(&th->th_generation);
611                *tsp = th->th_nanotime;
612                atomic_thread_fence_acq();
613        } while (gen == 0 || gen != th->th_generation);
614}
615
616void
617getmicrotime(struct timeval *tvp)
618{
619        struct timehands *th;
620        uint32_t gen;
621
622        do {
623                th = timehands;
624                gen = atomic_load_acq_int(&th->th_generation);
625                *tvp = th->th_microtime;
626                atomic_thread_fence_acq();
627        } while (gen == 0 || gen != th->th_generation);
628}
629#endif /* FFCLOCK */
630
631void
632getboottime(struct timeval *boottime)
633{
634        struct bintime boottimebin;
635
636        getboottimebin(&boottimebin);
637        bintime2timeval(&boottimebin, boottime);
638}
639
640void
641getboottimebin(struct bintime *boottimebin)
642{
643        struct timehands *th;
644        u_int gen;
645
646        do {
647                th = timehands;
648                gen = atomic_load_acq_int(&th->th_generation);
649                *boottimebin = th->th_boottime;
650                atomic_thread_fence_acq();
651        } while (gen == 0 || gen != th->th_generation);
652}
653
654#ifdef FFCLOCK
655/*
656 * Support for feed-forward synchronization algorithms. This is heavily inspired
657 * by the timehands mechanism but kept independent from it. *_windup() functions
658 * have some connection to avoid accessing the timecounter hardware more than
659 * necessary.
660 */
661
662/* Feed-forward clock estimates kept updated by the synchronization daemon. */
663struct ffclock_estimate ffclock_estimate;
664struct bintime ffclock_boottime;        /* Feed-forward boot time estimate. */
665uint32_t ffclock_status;                /* Feed-forward clock status. */
666int8_t ffclock_updated;                 /* New estimates are available. */
667struct mtx ffclock_mtx;                 /* Mutex on ffclock_estimate. */
668
669struct fftimehands {
670        struct ffclock_estimate cest;
671        struct bintime          tick_time;
672        struct bintime          tick_time_lerp;
673        ffcounter               tick_ffcount;
674        uint64_t                period_lerp;
675        volatile uint8_t        gen;
676        struct fftimehands      *next;
677};
678
679#define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
680
681static struct fftimehands ffth[10];
682static struct fftimehands *volatile fftimehands = ffth;
683
684static void
685ffclock_init(void)
686{
687        struct fftimehands *cur;
688        struct fftimehands *last;
689
690        memset(ffth, 0, sizeof(ffth));
691
692        last = ffth + NUM_ELEMENTS(ffth) - 1;
693        for (cur = ffth; cur < last; cur++)
694                cur->next = cur + 1;
695        last->next = ffth;
696
697        ffclock_updated = 0;
698        ffclock_status = FFCLOCK_STA_UNSYNC;
699        mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
700}
701
702/*
703 * Reset the feed-forward clock estimates. Called from inittodr() to get things
704 * kick started and uses the timecounter nominal frequency as a first period
705 * estimate. Note: this function may be called several time just after boot.
706 * Note: this is the only function that sets the value of boot time for the
707 * monotonic (i.e. uptime) version of the feed-forward clock.
708 */
709void
710ffclock_reset_clock(struct timespec *ts)
711{
712        struct timecounter *tc;
713        struct ffclock_estimate cest;
714
715        tc = timehands->th_counter;
716        memset(&cest, 0, sizeof(struct ffclock_estimate));
717
718        timespec2bintime(ts, &ffclock_boottime);
719        timespec2bintime(ts, &(cest.update_time));
720        ffclock_read_counter(&cest.update_ffcount);
721        cest.leapsec_next = 0;
722        cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
723        cest.errb_abs = 0;
724        cest.errb_rate = 0;
725        cest.status = FFCLOCK_STA_UNSYNC;
726        cest.leapsec_total = 0;
727        cest.leapsec = 0;
728
729        mtx_lock(&ffclock_mtx);
730        bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
731        ffclock_updated = INT8_MAX;
732        mtx_unlock(&ffclock_mtx);
733
734        printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
735            (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
736            (unsigned long)ts->tv_nsec);
737}
738
739/*
740 * Sub-routine to convert a time interval measured in RAW counter units to time
741 * in seconds stored in bintime format.
742 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
743 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
744 * extra cycles.
745 */
746static void
747ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
748{
749        struct bintime bt2;
750        ffcounter delta, delta_max;
751
752        delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
753        bintime_clear(bt);
754        do {
755                if (ffdelta > delta_max)
756                        delta = delta_max;
757                else
758                        delta = ffdelta;
759                bt2.sec = 0;
760                bt2.frac = period;
761                bintime_mul(&bt2, (unsigned int)delta);
762                bintime_add(bt, &bt2);
763                ffdelta -= delta;
764        } while (ffdelta > 0);
765}
766
767/*
768 * Update the fftimehands.
769 * Push the tick ffcount and time(s) forward based on current clock estimate.
770 * The conversion from ffcounter to bintime relies on the difference clock
771 * principle, whose accuracy relies on computing small time intervals. If a new
772 * clock estimate has been passed by the synchronisation daemon, make it
773 * current, and compute the linear interpolation for monotonic time if needed.
774 */
775static void
776ffclock_windup(unsigned int delta)
777{
778        struct ffclock_estimate *cest;
779        struct fftimehands *ffth;
780        struct bintime bt, gap_lerp;
781        ffcounter ffdelta;
782        uint64_t frac;
783        unsigned int polling;
784        uint8_t forward_jump, ogen;
785
786        /*
787         * Pick the next timehand, copy current ffclock estimates and move tick
788         * times and counter forward.
789         */
790        forward_jump = 0;
791        ffth = fftimehands->next;
792        ogen = ffth->gen;
793        ffth->gen = 0;
794        cest = &ffth->cest;
795        bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
796        ffdelta = (ffcounter)delta;
797        ffth->period_lerp = fftimehands->period_lerp;
798
799        ffth->tick_time = fftimehands->tick_time;
800        ffclock_convert_delta(ffdelta, cest->period, &bt);
801        bintime_add(&ffth->tick_time, &bt);
802
803        ffth->tick_time_lerp = fftimehands->tick_time_lerp;
804        ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
805        bintime_add(&ffth->tick_time_lerp, &bt);
806
807        ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
808
809        /*
810         * Assess the status of the clock, if the last update is too old, it is
811         * likely the synchronisation daemon is dead and the clock is free
812         * running.
813         */
814        if (ffclock_updated == 0) {
815                ffdelta = ffth->tick_ffcount - cest->update_ffcount;
816                ffclock_convert_delta(ffdelta, cest->period, &bt);
817                if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
818                        ffclock_status |= FFCLOCK_STA_UNSYNC;
819        }
820
821        /*
822         * If available, grab updated clock estimates and make them current.
823         * Recompute time at this tick using the updated estimates. The clock
824         * estimates passed the feed-forward synchronisation daemon may result
825         * in time conversion that is not monotonically increasing (just after
826         * the update). time_lerp is a particular linear interpolation over the
827         * synchronisation algo polling period that ensures monotonicity for the
828         * clock ids requesting it.
829         */
830        if (ffclock_updated > 0) {
831                bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
832                ffdelta = ffth->tick_ffcount - cest->update_ffcount;
833                ffth->tick_time = cest->update_time;
834                ffclock_convert_delta(ffdelta, cest->period, &bt);
835                bintime_add(&ffth->tick_time, &bt);
836
837                /* ffclock_reset sets ffclock_updated to INT8_MAX */
838                if (ffclock_updated == INT8_MAX)
839                        ffth->tick_time_lerp = ffth->tick_time;
840
841                if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
842                        forward_jump = 1;
843                else
844                        forward_jump = 0;
845
846                bintime_clear(&gap_lerp);
847                if (forward_jump) {
848                        gap_lerp = ffth->tick_time;
849                        bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
850                } else {
851                        gap_lerp = ffth->tick_time_lerp;
852                        bintime_sub(&gap_lerp, &ffth->tick_time);
853                }
854
855                /*
856                 * The reset from the RTC clock may be far from accurate, and
857                 * reducing the gap between real time and interpolated time
858                 * could take a very long time if the interpolated clock insists
859                 * on strict monotonicity. The clock is reset under very strict
860                 * conditions (kernel time is known to be wrong and
861                 * synchronization daemon has been restarted recently.
862                 * ffclock_boottime absorbs the jump to ensure boot time is
863                 * correct and uptime functions stay consistent.
864                 */
865                if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
866                    ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
867                    ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
868                        if (forward_jump)
869                                bintime_add(&ffclock_boottime, &gap_lerp);
870                        else
871                                bintime_sub(&ffclock_boottime, &gap_lerp);
872                        ffth->tick_time_lerp = ffth->tick_time;
873                        bintime_clear(&gap_lerp);
874                }
875
876                ffclock_status = cest->status;
877                ffth->period_lerp = cest->period;
878
879                /*
880                 * Compute corrected period used for the linear interpolation of
881                 * time. The rate of linear interpolation is capped to 5000PPM
882                 * (5ms/s).
883                 */
884                if (bintime_isset(&gap_lerp)) {
885                        ffdelta = cest->update_ffcount;
886                        ffdelta -= fftimehands->cest.update_ffcount;
887                        ffclock_convert_delta(ffdelta, cest->period, &bt);
888                        polling = bt.sec;
889                        bt.sec = 0;
890                        bt.frac = 5000000 * (uint64_t)18446744073LL;
891                        bintime_mul(&bt, polling);
892                        if (bintime_cmp(&gap_lerp, &bt, >))
893                                gap_lerp = bt;
894
895                        /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
896                        frac = 0;
897                        if (gap_lerp.sec > 0) {
898                                frac -= 1;
899                                frac /= ffdelta / gap_lerp.sec;
900                        }
901                        frac += gap_lerp.frac / ffdelta;
902
903                        if (forward_jump)
904                                ffth->period_lerp += frac;
905                        else
906                                ffth->period_lerp -= frac;
907                }
908
909                ffclock_updated = 0;
910        }
911        if (++ogen == 0)
912                ogen = 1;
913        ffth->gen = ogen;
914        fftimehands = ffth;
915}
916
917/*
918 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
919 * the old and new hardware counter cannot be read simultaneously. tc_windup()
920 * does read the two counters 'back to back', but a few cycles are effectively
921 * lost, and not accumulated in tick_ffcount. This is a fairly radical
922 * operation for a feed-forward synchronization daemon, and it is its job to not
923 * pushing irrelevant data to the kernel. Because there is no locking here,
924 * simply force to ignore pending or next update to give daemon a chance to
925 * realize the counter has changed.
926 */
927static void
928ffclock_change_tc(struct timehands *th)
929{
930        struct fftimehands *ffth;
931        struct ffclock_estimate *cest;
932        struct timecounter *tc;
933        uint8_t ogen;
934
935        tc = th->th_counter;
936        ffth = fftimehands->next;
937        ogen = ffth->gen;
938        ffth->gen = 0;
939
940        cest = &ffth->cest;
941        bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
942        cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
943        cest->errb_abs = 0;
944        cest->errb_rate = 0;
945        cest->status |= FFCLOCK_STA_UNSYNC;
946
947        ffth->tick_ffcount = fftimehands->tick_ffcount;
948        ffth->tick_time_lerp = fftimehands->tick_time_lerp;
949        ffth->tick_time = fftimehands->tick_time;
950        ffth->period_lerp = cest->period;
951
952        /* Do not lock but ignore next update from synchronization daemon. */
953        ffclock_updated--;
954
955        if (++ogen == 0)
956                ogen = 1;
957        ffth->gen = ogen;
958        fftimehands = ffth;
959}
960
961/*
962 * Retrieve feed-forward counter and time of last kernel tick.
963 */
964void
965ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
966{
967        struct fftimehands *ffth;
968        uint8_t gen;
969
970        /*
971         * No locking but check generation has not changed. Also need to make
972         * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
973         */
974        do {
975                ffth = fftimehands;
976                gen = ffth->gen;
977                if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
978                        *bt = ffth->tick_time_lerp;
979                else
980                        *bt = ffth->tick_time;
981                *ffcount = ffth->tick_ffcount;
982        } while (gen == 0 || gen != ffth->gen);
983}
984
985/*
986 * Absolute clock conversion. Low level function to convert ffcounter to
987 * bintime. The ffcounter is converted using the current ffclock period estimate
988 * or the "interpolated period" to ensure monotonicity.
989 * NOTE: this conversion may have been deferred, and the clock updated since the
990 * hardware counter has been read.
991 */
992void
993ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
994{
995        struct fftimehands *ffth;
996        struct bintime bt2;
997        ffcounter ffdelta;
998        uint8_t gen;
999
1000        /*
1001         * No locking but check generation has not changed. Also need to make
1002         * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
1003         */
1004        do {
1005                ffth = fftimehands;
1006                gen = ffth->gen;
1007                if (ffcount > ffth->tick_ffcount)
1008                        ffdelta = ffcount - ffth->tick_ffcount;
1009                else
1010                        ffdelta = ffth->tick_ffcount - ffcount;
1011
1012                if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
1013                        *bt = ffth->tick_time_lerp;
1014                        ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
1015                } else {
1016                        *bt = ffth->tick_time;
1017                        ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
1018                }
1019
1020                if (ffcount > ffth->tick_ffcount)
1021                        bintime_add(bt, &bt2);
1022                else
1023                        bintime_sub(bt, &bt2);
1024        } while (gen == 0 || gen != ffth->gen);
1025}
1026
1027/*
1028 * Difference clock conversion.
1029 * Low level function to Convert a time interval measured in RAW counter units
1030 * into bintime. The difference clock allows measuring small intervals much more
1031 * reliably than the absolute clock.
1032 */
1033void
1034ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
1035{
1036        struct fftimehands *ffth;
1037        uint8_t gen;
1038
1039        /* No locking but check generation has not changed. */
1040        do {
1041                ffth = fftimehands;
1042                gen = ffth->gen;
1043                ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
1044        } while (gen == 0 || gen != ffth->gen);
1045}
1046
1047/*
1048 * Access to current ffcounter value.
1049 */
1050void
1051ffclock_read_counter(ffcounter *ffcount)
1052{
1053        struct timehands *th;
1054        struct fftimehands *ffth;
1055        unsigned int gen, delta;
1056
1057        /*
1058         * ffclock_windup() called from tc_windup(), safe to rely on
1059         * th->th_generation only, for correct delta and ffcounter.
1060         */
1061        do {
1062                th = timehands;
1063                gen = atomic_load_acq_int(&th->th_generation);
1064                ffth = fftimehands;
1065                delta = tc_delta(th);
1066                *ffcount = ffth->tick_ffcount;
1067                atomic_thread_fence_acq();
1068        } while (gen == 0 || gen != th->th_generation);
1069
1070        *ffcount += delta;
1071}
1072
1073void
1074binuptime(struct bintime *bt)
1075{
1076
1077        binuptime_fromclock(bt, sysclock_active);
1078}
1079
1080void
1081nanouptime(struct timespec *tsp)
1082{
1083
1084        nanouptime_fromclock(tsp, sysclock_active);
1085}
1086
1087void
1088microuptime(struct timeval *tvp)
1089{
1090
1091        microuptime_fromclock(tvp, sysclock_active);
1092}
1093
1094void
1095bintime(struct bintime *bt)
1096{
1097
1098        bintime_fromclock(bt, sysclock_active);
1099}
1100
1101void
1102nanotime(struct timespec *tsp)
1103{
1104
1105        nanotime_fromclock(tsp, sysclock_active);
1106}
1107
1108void
1109microtime(struct timeval *tvp)
1110{
1111
1112        microtime_fromclock(tvp, sysclock_active);
1113}
1114
1115void
1116getbinuptime(struct bintime *bt)
1117{
1118
1119        getbinuptime_fromclock(bt, sysclock_active);
1120}
1121
1122void
1123getnanouptime(struct timespec *tsp)
1124{
1125
1126        getnanouptime_fromclock(tsp, sysclock_active);
1127}
1128
1129void
1130getmicrouptime(struct timeval *tvp)
1131{
1132
1133        getmicrouptime_fromclock(tvp, sysclock_active);
1134}
1135
1136void
1137getbintime(struct bintime *bt)
1138{
1139
1140        getbintime_fromclock(bt, sysclock_active);
1141}
1142
1143void
1144getnanotime(struct timespec *tsp)
1145{
1146
1147        getnanotime_fromclock(tsp, sysclock_active);
1148}
1149
1150void
1151getmicrotime(struct timeval *tvp)
1152{
1153
1154        getmicrouptime_fromclock(tvp, sysclock_active);
1155}
1156
1157#endif /* FFCLOCK */
1158
1159#ifndef __rtems__
1160/*
1161 * This is a clone of getnanotime and used for walltimestamps.
1162 * The dtrace_ prefix prevents fbt from creating probes for
1163 * it so walltimestamp can be safely used in all fbt probes.
1164 */
1165void
1166dtrace_getnanotime(struct timespec *tsp)
1167{
1168        struct timehands *th;
1169        uint32_t gen;
1170
1171        do {
1172                th = timehands;
1173                gen = atomic_load_acq_int(&th->th_generation);
1174                *tsp = th->th_nanotime;
1175                atomic_thread_fence_acq();
1176        } while (gen == 0 || gen != th->th_generation);
1177}
1178#endif /* __rtems__ */
1179
1180#ifdef FFCLOCK
1181/*
1182 * System clock currently providing time to the system. Modifiable via sysctl
1183 * when the FFCLOCK option is defined.
1184 */
1185int sysclock_active = SYSCLOCK_FBCK;
1186#endif
1187
1188/* Internal NTP status and error estimates. */
1189extern int time_status;
1190extern long time_esterror;
1191
1192#ifndef __rtems__
1193/*
1194 * Take a snapshot of sysclock data which can be used to compare system clocks
1195 * and generate timestamps after the fact.
1196 */
1197void
1198sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1199{
1200        struct fbclock_info *fbi;
1201        struct timehands *th;
1202        struct bintime bt;
1203        unsigned int delta, gen;
1204#ifdef FFCLOCK
1205        ffcounter ffcount;
1206        struct fftimehands *ffth;
1207        struct ffclock_info *ffi;
1208        struct ffclock_estimate cest;
1209
1210        ffi = &clock_snap->ff_info;
1211#endif
1212
1213        fbi = &clock_snap->fb_info;
1214        delta = 0;
1215
1216        do {
1217                th = timehands;
1218                gen = atomic_load_acq_int(&th->th_generation);
1219                fbi->th_scale = th->th_scale;
1220                fbi->tick_time = th->th_offset;
1221#ifdef FFCLOCK
1222                ffth = fftimehands;
1223                ffi->tick_time = ffth->tick_time_lerp;
1224                ffi->tick_time_lerp = ffth->tick_time_lerp;
1225                ffi->period = ffth->cest.period;
1226                ffi->period_lerp = ffth->period_lerp;
1227                clock_snap->ffcount = ffth->tick_ffcount;
1228                cest = ffth->cest;
1229#endif
1230                if (!fast)
1231                        delta = tc_delta(th);
1232                atomic_thread_fence_acq();
1233        } while (gen == 0 || gen != th->th_generation);
1234
1235        clock_snap->delta = delta;
1236#ifdef FFCLOCK
1237        clock_snap->sysclock_active = sysclock_active;
1238#endif
1239
1240        /* Record feedback clock status and error. */
1241        clock_snap->fb_info.status = time_status;
1242        /* XXX: Very crude estimate of feedback clock error. */
1243        bt.sec = time_esterror / 1000000;
1244        bt.frac = ((time_esterror - bt.sec) * 1000000) *
1245            (uint64_t)18446744073709ULL;
1246        clock_snap->fb_info.error = bt;
1247
1248#ifdef FFCLOCK
1249        if (!fast)
1250                clock_snap->ffcount += delta;
1251
1252        /* Record feed-forward clock leap second adjustment. */
1253        ffi->leapsec_adjustment = cest.leapsec_total;
1254        if (clock_snap->ffcount > cest.leapsec_next)
1255                ffi->leapsec_adjustment -= cest.leapsec;
1256
1257        /* Record feed-forward clock status and error. */
1258        clock_snap->ff_info.status = cest.status;
1259        ffcount = clock_snap->ffcount - cest.update_ffcount;
1260        ffclock_convert_delta(ffcount, cest.period, &bt);
1261        /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1262        bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1263        /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1264        bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1265        clock_snap->ff_info.error = bt;
1266#endif
1267}
1268
1269/*
1270 * Convert a sysclock snapshot into a struct bintime based on the specified
1271 * clock source and flags.
1272 */
1273int
1274sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1275    int whichclock, uint32_t flags)
1276{
1277        struct bintime boottimebin;
1278#ifdef FFCLOCK
1279        struct bintime bt2;
1280        uint64_t period;
1281#endif
1282
1283        switch (whichclock) {
1284        case SYSCLOCK_FBCK:
1285                *bt = cs->fb_info.tick_time;
1286
1287                /* If snapshot was created with !fast, delta will be >0. */
1288                if (cs->delta > 0)
1289                        bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1290
1291                if ((flags & FBCLOCK_UPTIME) == 0) {
1292                        getboottimebin(&boottimebin);
1293                        bintime_add(bt, &boottimebin);
1294                }
1295                break;
1296#ifdef FFCLOCK
1297        case SYSCLOCK_FFWD:
1298                if (flags & FFCLOCK_LERP) {
1299                        *bt = cs->ff_info.tick_time_lerp;
1300                        period = cs->ff_info.period_lerp;
1301                } else {
1302                        *bt = cs->ff_info.tick_time;
1303                        period = cs->ff_info.period;
1304                }
1305
1306                /* If snapshot was created with !fast, delta will be >0. */
1307                if (cs->delta > 0) {
1308                        ffclock_convert_delta(cs->delta, period, &bt2);
1309                        bintime_add(bt, &bt2);
1310                }
1311
1312                /* Leap second adjustment. */
1313                if (flags & FFCLOCK_LEAPSEC)
1314                        bt->sec -= cs->ff_info.leapsec_adjustment;
1315
1316                /* Boot time adjustment, for uptime/monotonic clocks. */
1317                if (flags & FFCLOCK_UPTIME)
1318                        bintime_sub(bt, &ffclock_boottime);
1319                break;
1320#endif
1321        default:
1322                return (EINVAL);
1323                break;
1324        }
1325
1326        return (0);
1327}
1328#endif /* __rtems__ */
1329
1330/*
1331 * Initialize a new timecounter and possibly use it.
1332 */
1333void
1334tc_init(struct timecounter *tc)
1335{
1336#ifndef __rtems__
1337        uint32_t u;
1338        struct sysctl_oid *tc_root;
1339
1340        u = tc->tc_frequency / tc->tc_counter_mask;
1341        /* XXX: We need some margin here, 10% is a guess */
1342        u *= 11;
1343        u /= 10;
1344        if (u > hz && tc->tc_quality >= 0) {
1345                tc->tc_quality = -2000;
1346                if (bootverbose) {
1347                        printf("Timecounter \"%s\" frequency %ju Hz",
1348                            tc->tc_name, (uintmax_t)tc->tc_frequency);
1349                        printf(" -- Insufficient hz, needs at least %u\n", u);
1350                }
1351        } else if (tc->tc_quality >= 0 || bootverbose) {
1352                printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1353                    tc->tc_name, (uintmax_t)tc->tc_frequency,
1354                    tc->tc_quality);
1355        }
1356#endif /* __rtems__ */
1357
1358        tc->tc_next = timecounters;
1359        timecounters = tc;
1360#ifndef __rtems__
1361        /*
1362         * Set up sysctl tree for this counter.
1363         */
1364        tc_root = SYSCTL_ADD_NODE(NULL,
1365            SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1366            CTLFLAG_RW, 0, "timecounter description");
1367        SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1368            "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1369            "mask for implemented bits");
1370        SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1371            "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1372            sysctl_kern_timecounter_get, "IU", "current timecounter value");
1373        SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1374            "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1375             sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1376        SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1377            "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1378            "goodness of time counter");
1379        /*
1380         * Do not automatically switch if the current tc was specifically
1381         * chosen.  Never automatically use a timecounter with negative quality.
1382         * Even though we run on the dummy counter, switching here may be
1383         * worse since this timecounter may not be monotonic.
1384         */
1385        if (tc_chosen)
1386                return;
1387        if (tc->tc_quality < 0)
1388                return;
1389        if (tc->tc_quality < timecounter->tc_quality)
1390                return;
1391        if (tc->tc_quality == timecounter->tc_quality &&
1392            tc->tc_frequency < timecounter->tc_frequency)
1393                return;
1394#endif /* __rtems__ */
1395        (void)tc->tc_get_timecount(tc);
1396        (void)tc->tc_get_timecount(tc);
1397        timecounter = tc;
1398#ifdef __rtems__
1399        tc_windup(NULL);
1400#endif /* __rtems__ */
1401}
1402
1403#ifndef __rtems__
1404/* Report the frequency of the current timecounter. */
1405uint64_t
1406tc_getfrequency(void)
1407{
1408
1409        return (timehands->th_counter->tc_frequency);
1410}
1411
1412static struct mtx tc_setclock_mtx;
1413MTX_SYSINIT(tc_setclock_init, &tc_setclock_mtx, "tcsetc", MTX_SPIN);
1414#endif /* __rtems__ */
1415
1416/*
1417 * Step our concept of UTC.  This is done by modifying our estimate of
1418 * when we booted.
1419 */
1420void
1421#ifndef __rtems__
1422tc_setclock(struct timespec *ts)
1423#else /* __rtems__ */
1424_Timecounter_Set_clock(const struct bintime *_bt,
1425    ISR_lock_Context *lock_context)
1426#endif /* __rtems__ */
1427{
1428#ifndef __rtems__
1429        struct timespec tbef, taft;
1430#endif /* __rtems__ */
1431        struct bintime bt, bt2;
1432
1433#ifndef __rtems__
1434        timespec2bintime(ts, &bt);
1435        nanotime(&tbef);
1436        mtx_lock_spin(&tc_setclock_mtx);
1437        cpu_tick_calibrate(1);
1438#else /* __rtems__ */
1439        bt = *_bt;
1440#endif /* __rtems__ */
1441        binuptime(&bt2);
1442        bintime_sub(&bt, &bt2);
1443
1444        /* XXX fiddle all the little crinkly bits around the fiords... */
1445#ifndef __rtems__
1446        tc_windup(&bt);
1447        mtx_unlock_spin(&tc_setclock_mtx);
1448        if (timestepwarnings) {
1449                nanotime(&taft);
1450                log(LOG_INFO,
1451                    "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1452                    (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1453                    (intmax_t)taft.tv_sec, taft.tv_nsec,
1454                    (intmax_t)ts->tv_sec, ts->tv_nsec);
1455        }
1456#else /* __rtems__ */
1457        _Timecounter_Windup(&bt, lock_context);
1458#endif /* __rtems__ */
1459}
1460
1461/*
1462 * Initialize the next struct timehands in the ring and make
1463 * it the active timehands.  Along the way we might switch to a different
1464 * timecounter and/or do seconds processing in NTP.  Slightly magic.
1465 */
1466static void
1467tc_windup(struct bintime *new_boottimebin)
1468#ifdef __rtems__
1469{
1470        ISR_lock_Context lock_context;
1471
1472        _Timecounter_Acquire(&lock_context);
1473        _Timecounter_Windup(new_boottimebin, &lock_context);
1474}
1475
1476static void
1477_Timecounter_Windup(struct bintime *new_boottimebin,
1478    ISR_lock_Context *lock_context)
1479#endif /* __rtems__ */
1480{
1481        struct bintime bt;
1482        struct timehands *th, *tho;
1483        uint64_t scale;
1484        uint32_t delta, ncount, ogen;
1485        int i;
1486        time_t t;
1487
1488        /*
1489         * Make the next timehands a copy of the current one, but do
1490         * not overwrite the generation or next pointer.  While we
1491         * update the contents, the generation must be zero.  We need
1492         * to ensure that the zero generation is visible before the
1493         * data updates become visible, which requires release fence.
1494         * For similar reasons, re-reading of the generation after the
1495         * data is read should use acquire fence.
1496         */
1497        tho = timehands;
1498#if defined(RTEMS_SMP)
1499        th = tho->th_next;
1500#else
1501        th = tho;
1502#endif
1503        ogen = th->th_generation;
1504        th->th_generation = 0;
1505        atomic_thread_fence_rel();
1506#if defined(RTEMS_SMP)
1507        bcopy(tho, th, offsetof(struct timehands, th_generation));
1508#endif
1509        if (new_boottimebin != NULL)
1510                th->th_boottime = *new_boottimebin;
1511
1512        /*
1513         * Capture a timecounter delta on the current timecounter and if
1514         * changing timecounters, a counter value from the new timecounter.
1515         * Update the offset fields accordingly.
1516         */
1517        delta = tc_delta(th);
1518        if (th->th_counter != timecounter)
1519                ncount = timecounter->tc_get_timecount(timecounter);
1520        else
1521                ncount = 0;
1522#ifdef FFCLOCK
1523        ffclock_windup(delta);
1524#endif
1525        th->th_offset_count += delta;
1526        th->th_offset_count &= th->th_counter->tc_counter_mask;
1527        while (delta > th->th_counter->tc_frequency) {
1528                /* Eat complete unadjusted seconds. */
1529                delta -= th->th_counter->tc_frequency;
1530                th->th_offset.sec++;
1531        }
1532        if ((delta > th->th_counter->tc_frequency / 2) &&
1533            (th->th_scale * delta < ((uint64_t)1 << 63))) {
1534                /* The product th_scale * delta just barely overflows. */
1535                th->th_offset.sec++;
1536        }
1537        bintime_addx(&th->th_offset, th->th_scale * delta);
1538
1539        /*
1540         * Hardware latching timecounters may not generate interrupts on
1541         * PPS events, so instead we poll them.  There is a finite risk that
1542         * the hardware might capture a count which is later than the one we
1543         * got above, and therefore possibly in the next NTP second which might
1544         * have a different rate than the current NTP second.  It doesn't
1545         * matter in practice.
1546         */
1547        if (tho->th_counter->tc_poll_pps)
1548                tho->th_counter->tc_poll_pps(tho->th_counter);
1549
1550        /*
1551         * Deal with NTP second processing.  The for loop normally
1552         * iterates at most once, but in extreme situations it might
1553         * keep NTP sane if timeouts are not run for several seconds.
1554         * At boot, the time step can be large when the TOD hardware
1555         * has been read, so on really large steps, we call
1556         * ntp_update_second only twice.  We need to call it twice in
1557         * case we missed a leap second.
1558         */
1559        bt = th->th_offset;
1560        bintime_add(&bt, &th->th_boottime);
1561        i = bt.sec - tho->th_microtime.tv_sec;
1562        if (i > LARGE_STEP)
1563                i = 2;
1564        for (; i > 0; i--) {
1565                t = bt.sec;
1566                ntp_update_second(&th->th_adjustment, &bt.sec);
1567                if (bt.sec != t)
1568                        th->th_boottime.sec += bt.sec - t;
1569        }
1570        /* Update the UTC timestamps used by the get*() functions. */
1571        /* XXX shouldn't do this here.  Should force non-`get' versions. */
1572        bintime2timeval(&bt, &th->th_microtime);
1573        bintime2timespec(&bt, &th->th_nanotime);
1574
1575        /* Now is a good time to change timecounters. */
1576        if (th->th_counter != timecounter) {
1577#ifndef __rtems__
1578#ifndef __arm__
1579                if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
1580                        cpu_disable_c2_sleep++;
1581                if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1582                        cpu_disable_c2_sleep--;
1583#endif
1584#endif /* __rtems__ */
1585                th->th_counter = timecounter;
1586                th->th_offset_count = ncount;
1587#ifndef __rtems__
1588                tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1589                    (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1590#endif /* __rtems__ */
1591#ifdef FFCLOCK
1592                ffclock_change_tc(th);
1593#endif
1594        }
1595
1596        /*-
1597         * Recalculate the scaling factor.  We want the number of 1/2^64
1598         * fractions of a second per period of the hardware counter, taking
1599         * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1600         * processing provides us with.
1601         *
1602         * The th_adjustment is nanoseconds per second with 32 bit binary
1603         * fraction and we want 64 bit binary fraction of second:
1604         *
1605         *       x = a * 2^32 / 10^9 = a * 4.294967296
1606         *
1607         * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1608         * we can only multiply by about 850 without overflowing, that
1609         * leaves no suitably precise fractions for multiply before divide.
1610         *
1611         * Divide before multiply with a fraction of 2199/512 results in a
1612         * systematic undercompensation of 10PPM of th_adjustment.  On a
1613         * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
1614         *
1615         * We happily sacrifice the lowest of the 64 bits of our result
1616         * to the goddess of code clarity.
1617         *
1618         */
1619        scale = (uint64_t)1 << 63;
1620        scale += (th->th_adjustment / 1024) * 2199;
1621        scale /= th->th_counter->tc_frequency;
1622        th->th_scale = scale * 2;
1623
1624        /*
1625         * Now that the struct timehands is again consistent, set the new
1626         * generation number, making sure to not make it zero.
1627         */
1628        if (++ogen == 0)
1629                ogen = 1;
1630        atomic_store_rel_int(&th->th_generation, ogen);
1631
1632        /* Go live with the new struct timehands. */
1633#ifdef FFCLOCK
1634        switch (sysclock_active) {
1635        case SYSCLOCK_FBCK:
1636#endif
1637                time_second = th->th_microtime.tv_sec;
1638                time_uptime = th->th_offset.sec;
1639#ifdef FFCLOCK
1640                break;
1641        case SYSCLOCK_FFWD:
1642                time_second = fftimehands->tick_time_lerp.sec;
1643                time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1644                break;
1645        }
1646#endif
1647
1648#if defined(RTEMS_SMP)
1649        timehands = th;
1650#endif
1651#ifndef __rtems__
1652        timekeep_push_vdso();
1653#endif /* __rtems__ */
1654#ifdef __rtems__
1655        _Timecounter_Release(lock_context);
1656#endif /* __rtems__ */
1657}
1658
1659#ifndef __rtems__
1660/* Report or change the active timecounter hardware. */
1661static int
1662sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1663{
1664        char newname[32];
1665        struct timecounter *newtc, *tc;
1666        int error;
1667
1668        tc = timecounter;
1669        strlcpy(newname, tc->tc_name, sizeof(newname));
1670
1671        error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1672        if (error != 0 || req->newptr == NULL)
1673                return (error);
1674        /* Record that the tc in use now was specifically chosen. */
1675        tc_chosen = 1;
1676        if (strcmp(newname, tc->tc_name) == 0)
1677                return (0);
1678        for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1679                if (strcmp(newname, newtc->tc_name) != 0)
1680                        continue;
1681
1682                /* Warm up new timecounter. */
1683                (void)newtc->tc_get_timecount(newtc);
1684                (void)newtc->tc_get_timecount(newtc);
1685
1686                timecounter = newtc;
1687
1688                /*
1689                 * The vdso timehands update is deferred until the next
1690                 * 'tc_windup()'.
1691                 *
1692                 * This is prudent given that 'timekeep_push_vdso()' does not
1693                 * use any locking and that it can be called in hard interrupt
1694                 * context via 'tc_windup()'.
1695                 */
1696                return (0);
1697        }
1698        return (EINVAL);
1699}
1700
1701SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1702    0, 0, sysctl_kern_timecounter_hardware, "A",
1703    "Timecounter hardware selected");
1704
1705
1706/* Report the available timecounter hardware. */
1707static int
1708sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1709{
1710        struct sbuf sb;
1711        struct timecounter *tc;
1712        int error;
1713
1714        sbuf_new_for_sysctl(&sb, NULL, 0, req);
1715        for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
1716                if (tc != timecounters)
1717                        sbuf_putc(&sb, ' ');
1718                sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
1719        }
1720        error = sbuf_finish(&sb);
1721        sbuf_delete(&sb);
1722        return (error);
1723}
1724
1725SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1726    0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1727#endif /* __rtems__ */
1728
1729#ifndef __rtems__
1730/*
1731 * RFC 2783 PPS-API implementation.
1732 */
1733
1734/*
1735 *  Return true if the driver is aware of the abi version extensions in the
1736 *  pps_state structure, and it supports at least the given abi version number.
1737 */
1738static inline int
1739abi_aware(struct pps_state *pps, int vers)
1740{
1741
1742        return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1743}
1744
1745static int
1746pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1747{
1748        int err, timo;
1749        pps_seq_t aseq, cseq;
1750        struct timeval tv;
1751
1752        if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1753                return (EINVAL);
1754
1755        /*
1756         * If no timeout is requested, immediately return whatever values were
1757         * most recently captured.  If timeout seconds is -1, that's a request
1758         * to block without a timeout.  WITNESS won't let us sleep forever
1759         * without a lock (we really don't need a lock), so just repeatedly
1760         * sleep a long time.
1761         */
1762        if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1763                if (fapi->timeout.tv_sec == -1)
1764                        timo = 0x7fffffff;
1765                else {
1766                        tv.tv_sec = fapi->timeout.tv_sec;
1767                        tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1768                        timo = tvtohz(&tv);
1769                }
1770                aseq = pps->ppsinfo.assert_sequence;
1771                cseq = pps->ppsinfo.clear_sequence;
1772                while (aseq == pps->ppsinfo.assert_sequence &&
1773                    cseq == pps->ppsinfo.clear_sequence) {
1774                        if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1775                                if (pps->flags & PPSFLAG_MTX_SPIN) {
1776                                        err = msleep_spin(pps, pps->driver_mtx,
1777                                            "ppsfch", timo);
1778                                } else {
1779                                        err = msleep(pps, pps->driver_mtx, PCATCH,
1780                                            "ppsfch", timo);
1781                                }
1782                        } else {
1783                                err = tsleep(pps, PCATCH, "ppsfch", timo);
1784                        }
1785                        if (err == EWOULDBLOCK) {
1786                                if (fapi->timeout.tv_sec == -1) {
1787                                        continue;
1788                                } else {
1789                                        return (ETIMEDOUT);
1790                                }
1791                        } else if (err != 0) {
1792                                return (err);
1793                        }
1794                }
1795        }
1796
1797        pps->ppsinfo.current_mode = pps->ppsparam.mode;
1798        fapi->pps_info_buf = pps->ppsinfo;
1799
1800        return (0);
1801}
1802
1803int
1804pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1805{
1806        pps_params_t *app;
1807        struct pps_fetch_args *fapi;
1808#ifdef FFCLOCK
1809        struct pps_fetch_ffc_args *fapi_ffc;
1810#endif
1811#ifdef PPS_SYNC
1812        struct pps_kcbind_args *kapi;
1813#endif
1814
1815        KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1816        switch (cmd) {
1817        case PPS_IOC_CREATE:
1818                return (0);
1819        case PPS_IOC_DESTROY:
1820                return (0);
1821        case PPS_IOC_SETPARAMS:
1822                app = (pps_params_t *)data;
1823                if (app->mode & ~pps->ppscap)
1824                        return (EINVAL);
1825#ifdef FFCLOCK
1826                /* Ensure only a single clock is selected for ffc timestamp. */
1827                if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1828                        return (EINVAL);
1829#endif
1830                pps->ppsparam = *app;
1831                return (0);
1832        case PPS_IOC_GETPARAMS:
1833                app = (pps_params_t *)data;
1834                *app = pps->ppsparam;
1835                app->api_version = PPS_API_VERS_1;
1836                return (0);
1837        case PPS_IOC_GETCAP:
1838                *(int*)data = pps->ppscap;
1839                return (0);
1840        case PPS_IOC_FETCH:
1841                fapi = (struct pps_fetch_args *)data;
1842                return (pps_fetch(fapi, pps));
1843#ifdef FFCLOCK
1844        case PPS_IOC_FETCH_FFCOUNTER:
1845                fapi_ffc = (struct pps_fetch_ffc_args *)data;
1846                if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1847                    PPS_TSFMT_TSPEC)
1848                        return (EINVAL);
1849                if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1850                        return (EOPNOTSUPP);
1851                pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1852                fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1853                /* Overwrite timestamps if feedback clock selected. */
1854                switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1855                case PPS_TSCLK_FBCK:
1856                        fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1857                            pps->ppsinfo.assert_timestamp;
1858                        fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1859                            pps->ppsinfo.clear_timestamp;
1860                        break;
1861                case PPS_TSCLK_FFWD:
1862                        break;
1863                default:
1864                        break;
1865                }
1866                return (0);
1867#endif /* FFCLOCK */
1868        case PPS_IOC_KCBIND:
1869#ifdef PPS_SYNC
1870                kapi = (struct pps_kcbind_args *)data;
1871                /* XXX Only root should be able to do this */
1872                if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1873                        return (EINVAL);
1874                if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1875                        return (EINVAL);
1876                if (kapi->edge & ~pps->ppscap)
1877                        return (EINVAL);
1878                pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1879                    (pps->kcmode & KCMODE_ABIFLAG);
1880                return (0);
1881#else
1882                return (EOPNOTSUPP);
1883#endif
1884        default:
1885                return (ENOIOCTL);
1886        }
1887}
1888
1889void
1890pps_init(struct pps_state *pps)
1891{
1892        pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1893        if (pps->ppscap & PPS_CAPTUREASSERT)
1894                pps->ppscap |= PPS_OFFSETASSERT;
1895        if (pps->ppscap & PPS_CAPTURECLEAR)
1896                pps->ppscap |= PPS_OFFSETCLEAR;
1897#ifdef FFCLOCK
1898        pps->ppscap |= PPS_TSCLK_MASK;
1899#endif
1900        pps->kcmode &= ~KCMODE_ABIFLAG;
1901}
1902
1903void
1904pps_init_abi(struct pps_state *pps)
1905{
1906
1907        pps_init(pps);
1908        if (pps->driver_abi > 0) {
1909                pps->kcmode |= KCMODE_ABIFLAG;
1910                pps->kernel_abi = PPS_ABI_VERSION;
1911        }
1912}
1913
1914void
1915pps_capture(struct pps_state *pps)
1916{
1917        struct timehands *th;
1918
1919        KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1920        th = timehands;
1921        pps->capgen = atomic_load_acq_int(&th->th_generation);
1922        pps->capth = th;
1923#ifdef FFCLOCK
1924        pps->capffth = fftimehands;
1925#endif
1926        pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1927        atomic_thread_fence_acq();
1928        if (pps->capgen != th->th_generation)
1929                pps->capgen = 0;
1930}
1931
1932void
1933pps_event(struct pps_state *pps, int event)
1934{
1935        struct bintime bt;
1936        struct timespec ts, *tsp, *osp;
1937        uint32_t tcount, *pcount;
1938        int foff;
1939        pps_seq_t *pseq;
1940#ifdef FFCLOCK
1941        struct timespec *tsp_ffc;
1942        pps_seq_t *pseq_ffc;
1943        ffcounter *ffcount;
1944#endif
1945#ifdef PPS_SYNC
1946        int fhard;
1947#endif
1948
1949        KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1950        /* Nothing to do if not currently set to capture this event type. */
1951        if ((event & pps->ppsparam.mode) == 0)
1952                return;
1953        /* If the timecounter was wound up underneath us, bail out. */
1954        if (pps->capgen == 0 || pps->capgen !=
1955            atomic_load_acq_int(&pps->capth->th_generation))
1956                return;
1957
1958        /* Things would be easier with arrays. */
1959        if (event == PPS_CAPTUREASSERT) {
1960                tsp = &pps->ppsinfo.assert_timestamp;
1961                osp = &pps->ppsparam.assert_offset;
1962                foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1963#ifdef PPS_SYNC
1964                fhard = pps->kcmode & PPS_CAPTUREASSERT;
1965#endif
1966                pcount = &pps->ppscount[0];
1967                pseq = &pps->ppsinfo.assert_sequence;
1968#ifdef FFCLOCK
1969                ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1970                tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1971                pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1972#endif
1973        } else {
1974                tsp = &pps->ppsinfo.clear_timestamp;
1975                osp = &pps->ppsparam.clear_offset;
1976                foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1977#ifdef PPS_SYNC
1978                fhard = pps->kcmode & PPS_CAPTURECLEAR;
1979#endif
1980                pcount = &pps->ppscount[1];
1981                pseq = &pps->ppsinfo.clear_sequence;
1982#ifdef FFCLOCK
1983                ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1984                tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1985                pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1986#endif
1987        }
1988
1989        /*
1990         * If the timecounter changed, we cannot compare the count values, so
1991         * we have to drop the rest of the PPS-stuff until the next event.
1992         */
1993        if (pps->ppstc != pps->capth->th_counter) {
1994                pps->ppstc = pps->capth->th_counter;
1995                *pcount = pps->capcount;
1996                pps->ppscount[2] = pps->capcount;
1997                return;
1998        }
1999
2000        /* Convert the count to a timespec. */
2001        tcount = pps->capcount - pps->capth->th_offset_count;
2002        tcount &= pps->capth->th_counter->tc_counter_mask;
2003        bt = pps->capth->th_offset;
2004        bintime_addx(&bt, pps->capth->th_scale * tcount);
2005        bintime_add(&bt, &pps->capth->th_boottime);
2006        bintime2timespec(&bt, &ts);
2007
2008        /* If the timecounter was wound up underneath us, bail out. */
2009        atomic_thread_fence_acq();
2010        if (pps->capgen != pps->capth->th_generation)
2011                return;
2012
2013        *pcount = pps->capcount;
2014        (*pseq)++;
2015        *tsp = ts;
2016
2017        if (foff) {
2018                timespecadd(tsp, osp);
2019                if (tsp->tv_nsec < 0) {
2020                        tsp->tv_nsec += 1000000000;
2021                        tsp->tv_sec -= 1;
2022                }
2023        }
2024
2025#ifdef FFCLOCK
2026        *ffcount = pps->capffth->tick_ffcount + tcount;
2027        bt = pps->capffth->tick_time;
2028        ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
2029        bintime_add(&bt, &pps->capffth->tick_time);
2030        bintime2timespec(&bt, &ts);
2031        (*pseq_ffc)++;
2032        *tsp_ffc = ts;
2033#endif
2034
2035#ifdef PPS_SYNC
2036        if (fhard) {
2037                uint64_t scale;
2038
2039                /*
2040                 * Feed the NTP PLL/FLL.
2041                 * The FLL wants to know how many (hardware) nanoseconds
2042                 * elapsed since the previous event.
2043                 */
2044                tcount = pps->capcount - pps->ppscount[2];
2045                pps->ppscount[2] = pps->capcount;
2046                tcount &= pps->capth->th_counter->tc_counter_mask;
2047                scale = (uint64_t)1 << 63;
2048                scale /= pps->capth->th_counter->tc_frequency;
2049                scale *= 2;
2050                bt.sec = 0;
2051                bt.frac = 0;
2052                bintime_addx(&bt, scale * tcount);
2053                bintime2timespec(&bt, &ts);
2054                hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
2055        }
2056#endif
2057
2058        /* Wakeup anyone sleeping in pps_fetch().  */
2059        wakeup(pps);
2060}
2061#else /* __rtems__ */
2062/* FIXME: https://devel.rtems.org/ticket/2349 */
2063#endif /* __rtems__ */
2064
2065/*
2066 * Timecounters need to be updated every so often to prevent the hardware
2067 * counter from overflowing.  Updating also recalculates the cached values
2068 * used by the get*() family of functions, so their precision depends on
2069 * the update frequency.
2070 */
2071
2072#ifndef __rtems__
2073static int tc_tick;
2074SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
2075    "Approximate number of hardclock ticks in a millisecond");
2076#endif /* __rtems__ */
2077
2078#ifndef __rtems__
2079void
2080tc_ticktock(int cnt)
2081{
2082        static int count;
2083
2084        if (mtx_trylock_spin(&tc_setclock_mtx)) {
2085                count += cnt;
2086                if (count >= tc_tick) {
2087                        count = 0;
2088                        tc_windup(NULL);
2089                }
2090                mtx_unlock_spin(&tc_setclock_mtx);
2091        }
2092}
2093#else /* __rtems__ */
2094void
2095_Timecounter_Tick(void)
2096{
2097        Per_CPU_Control *cpu_self = _Per_CPU_Get();
2098
2099        if (_Per_CPU_Is_boot_processor(cpu_self)) {
2100                tc_windup(NULL);
2101        }
2102
2103        _Watchdog_Tick(cpu_self);
2104}
2105
2106void
2107_Timecounter_Tick_simple(uint32_t delta, uint32_t offset,
2108    ISR_lock_Context *lock_context)
2109{
2110        struct bintime bt;
2111        struct timehands *th;
2112        uint32_t ogen;
2113
2114        th = timehands;
2115        ogen = th->th_generation;
2116        th->th_offset_count = offset;
2117        bintime_addx(&th->th_offset, th->th_scale * delta);
2118
2119        bt = th->th_offset;
2120        th->th_bintime = bt;
2121        bintime_add(&th->th_bintime, &th->th_boottime);
2122        /* Update the UTC timestamps used by the get*() functions. */
2123        /* XXX shouldn't do this here.  Should force non-`get' versions. */
2124        bintime2timeval(&bt, &th->th_microtime);
2125        bintime2timespec(&bt, &th->th_nanotime);
2126
2127        /*
2128         * Now that the struct timehands is again consistent, set the new
2129         * generation number, making sure to not make it zero.
2130         */
2131        if (++ogen == 0)
2132                ogen = 1;
2133        th->th_generation = ogen;
2134
2135        /* Go live with the new struct timehands. */
2136        time_second = th->th_microtime.tv_sec;
2137        time_uptime = th->th_offset.sec;
2138
2139        _Timecounter_Release(lock_context);
2140
2141        _Watchdog_Tick(_Per_CPU_Get_snapshot());
2142}
2143#endif /* __rtems__ */
2144
2145#ifndef __rtems__
2146static void __inline
2147tc_adjprecision(void)
2148{
2149        int t;
2150
2151        if (tc_timepercentage > 0) {
2152                t = (99 + tc_timepercentage) / tc_timepercentage;
2153                tc_precexp = fls(t + (t >> 1)) - 1;
2154                FREQ2BT(hz / tc_tick, &bt_timethreshold);
2155                FREQ2BT(hz, &bt_tickthreshold);
2156                bintime_shift(&bt_timethreshold, tc_precexp);
2157                bintime_shift(&bt_tickthreshold, tc_precexp);
2158        } else {
2159                tc_precexp = 31;
2160                bt_timethreshold.sec = INT_MAX;
2161                bt_timethreshold.frac = ~(uint64_t)0;
2162                bt_tickthreshold = bt_timethreshold;
2163        }
2164        sbt_timethreshold = bttosbt(bt_timethreshold);
2165        sbt_tickthreshold = bttosbt(bt_tickthreshold);
2166}
2167#endif /* __rtems__ */
2168
2169#ifndef __rtems__
2170static int
2171sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
2172{
2173        int error, val;
2174
2175        val = tc_timepercentage;
2176        error = sysctl_handle_int(oidp, &val, 0, req);
2177        if (error != 0 || req->newptr == NULL)
2178                return (error);
2179        tc_timepercentage = val;
2180        if (cold)
2181                goto done;
2182        tc_adjprecision();
2183done:
2184        return (0);
2185}
2186
2187static void
2188inittimecounter(void *dummy)
2189{
2190        u_int p;
2191        int tick_rate;
2192
2193        /*
2194         * Set the initial timeout to
2195         * max(1, <approx. number of hardclock ticks in a millisecond>).
2196         * People should probably not use the sysctl to set the timeout
2197         * to smaller than its initial value, since that value is the
2198         * smallest reasonable one.  If they want better timestamps they
2199         * should use the non-"get"* functions.
2200         */
2201        if (hz > 1000)
2202                tc_tick = (hz + 500) / 1000;
2203        else
2204                tc_tick = 1;
2205        tc_adjprecision();
2206        FREQ2BT(hz, &tick_bt);
2207        tick_sbt = bttosbt(tick_bt);
2208        tick_rate = hz / tc_tick;
2209        FREQ2BT(tick_rate, &tc_tick_bt);
2210        tc_tick_sbt = bttosbt(tc_tick_bt);
2211        p = (tc_tick * 1000000) / hz;
2212        printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
2213
2214#ifdef FFCLOCK
2215        ffclock_init();
2216#endif
2217        /* warm up new timecounter (again) and get rolling. */
2218        (void)timecounter->tc_get_timecount(timecounter);
2219        (void)timecounter->tc_get_timecount(timecounter);
2220        mtx_lock_spin(&tc_setclock_mtx);
2221        tc_windup(NULL);
2222        mtx_unlock_spin(&tc_setclock_mtx);
2223}
2224
2225SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
2226
2227/* Cpu tick handling -------------------------------------------------*/
2228
2229static int cpu_tick_variable;
2230static uint64_t cpu_tick_frequency;
2231
2232static DPCPU_DEFINE(uint64_t, tc_cpu_ticks_base);
2233static DPCPU_DEFINE(unsigned, tc_cpu_ticks_last);
2234
2235static uint64_t
2236tc_cpu_ticks(void)
2237{
2238        struct timecounter *tc;
2239        uint64_t res, *base;
2240        unsigned u, *last;
2241
2242        critical_enter();
2243        base = DPCPU_PTR(tc_cpu_ticks_base);
2244        last = DPCPU_PTR(tc_cpu_ticks_last);
2245        tc = timehands->th_counter;
2246        u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
2247        if (u < *last)
2248                *base += (uint64_t)tc->tc_counter_mask + 1;
2249        *last = u;
2250        res = u + *base;
2251        critical_exit();
2252        return (res);
2253}
2254
2255void
2256cpu_tick_calibration(void)
2257{
2258        static time_t last_calib;
2259
2260        if (time_uptime != last_calib && !(time_uptime & 0xf)) {
2261                cpu_tick_calibrate(0);
2262                last_calib = time_uptime;
2263        }
2264}
2265
2266/*
2267 * This function gets called every 16 seconds on only one designated
2268 * CPU in the system from hardclock() via cpu_tick_calibration()().
2269 *
2270 * Whenever the real time clock is stepped we get called with reset=1
2271 * to make sure we handle suspend/resume and similar events correctly.
2272 */
2273
2274static void
2275cpu_tick_calibrate(int reset)
2276{
2277        static uint64_t c_last;
2278        uint64_t c_this, c_delta;
2279        static struct bintime  t_last;
2280        struct bintime t_this, t_delta;
2281        uint32_t divi;
2282
2283        if (reset) {
2284                /* The clock was stepped, abort & reset */
2285                t_last.sec = 0;
2286                return;
2287        }
2288
2289        /* we don't calibrate fixed rate cputicks */
2290        if (!cpu_tick_variable)
2291                return;
2292
2293        getbinuptime(&t_this);
2294        c_this = cpu_ticks();
2295        if (t_last.sec != 0) {
2296                c_delta = c_this - c_last;
2297                t_delta = t_this;
2298                bintime_sub(&t_delta, &t_last);
2299                /*
2300                 * Headroom:
2301                 *      2^(64-20) / 16[s] =
2302                 *      2^(44) / 16[s] =
2303                 *      17.592.186.044.416 / 16 =
2304                 *      1.099.511.627.776 [Hz]
2305                 */
2306                divi = t_delta.sec << 20;
2307                divi |= t_delta.frac >> (64 - 20);
2308                c_delta <<= 20;
2309                c_delta /= divi;
2310                if (c_delta > cpu_tick_frequency) {
2311                        if (0 && bootverbose)
2312                                printf("cpu_tick increased to %ju Hz\n",
2313                                    c_delta);
2314                        cpu_tick_frequency = c_delta;
2315                }
2316        }
2317        c_last = c_this;
2318        t_last = t_this;
2319}
2320
2321void
2322set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
2323{
2324
2325        if (func == NULL) {
2326                cpu_ticks = tc_cpu_ticks;
2327        } else {
2328                cpu_tick_frequency = freq;
2329                cpu_tick_variable = var;
2330                cpu_ticks = func;
2331        }
2332}
2333
2334uint64_t
2335cpu_tickrate(void)
2336{
2337
2338        if (cpu_ticks == tc_cpu_ticks)
2339                return (tc_getfrequency());
2340        return (cpu_tick_frequency);
2341}
2342
2343/*
2344 * We need to be slightly careful converting cputicks to microseconds.
2345 * There is plenty of margin in 64 bits of microseconds (half a million
2346 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2347 * before divide conversion (to retain precision) we find that the
2348 * margin shrinks to 1.5 hours (one millionth of 146y).
2349 * With a three prong approach we never lose significant bits, no
2350 * matter what the cputick rate and length of timeinterval is.
2351 */
2352
2353uint64_t
2354cputick2usec(uint64_t tick)
2355{
2356
2357        if (tick > 18446744073709551LL)         /* floor(2^64 / 1000) */
2358                return (tick / (cpu_tickrate() / 1000000LL));
2359        else if (tick > 18446744073709LL)       /* floor(2^64 / 1000000) */
2360                return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2361        else
2362                return ((tick * 1000000LL) / cpu_tickrate());
2363}
2364
2365cpu_tick_f      *cpu_ticks = tc_cpu_ticks;
2366#endif /* __rtems__ */
2367
2368#ifndef __rtems__
2369static int vdso_th_enable = 1;
2370static int
2371sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2372{
2373        int old_vdso_th_enable, error;
2374
2375        old_vdso_th_enable = vdso_th_enable;
2376        error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2377        if (error != 0)
2378                return (error);
2379        vdso_th_enable = old_vdso_th_enable;
2380        return (0);
2381}
2382SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2383    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2384    NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2385
2386uint32_t
2387tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2388{
2389        struct timehands *th;
2390        uint32_t enabled;
2391
2392        th = timehands;
2393        vdso_th->th_algo = VDSO_TH_ALGO_1;
2394        vdso_th->th_scale = th->th_scale;
2395        vdso_th->th_offset_count = th->th_offset_count;
2396        vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2397        vdso_th->th_offset = th->th_offset;
2398        vdso_th->th_boottime = th->th_boottime;
2399        enabled = cpu_fill_vdso_timehands(vdso_th, th->th_counter);
2400        if (!vdso_th_enable)
2401                enabled = 0;
2402        return (enabled);
2403}
2404#endif /* __rtems__ */
2405
2406#ifdef COMPAT_FREEBSD32
2407uint32_t
2408tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2409{
2410        struct timehands *th;
2411        uint32_t enabled;
2412
2413        th = timehands;
2414        vdso_th32->th_algo = VDSO_TH_ALGO_1;
2415        *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2416        vdso_th32->th_offset_count = th->th_offset_count;
2417        vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2418        vdso_th32->th_offset.sec = th->th_offset.sec;
2419        *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2420        vdso_th32->th_boottime.sec = th->th_boottime.sec;
2421        *(uint64_t *)&vdso_th32->th_boottime.frac[0] = th->th_boottime.frac;
2422        enabled = cpu_fill_vdso_timehands32(vdso_th32, th->th_counter);
2423        if (!vdso_th_enable)
2424                enabled = 0;
2425        return (enabled);
2426}
2427#endif
Note: See TracBrowser for help on using the repository browser.