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

Last change on this file since c830bc64 was c830bc64, checked in by Sebastian Huber <sebastian.huber@…>, on 10/09/21 at 19:23:16

score: Remove FreeBSD identifier

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