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

Last change on this file since c44ab898 was 198e926, checked in by Sebastian Huber <sebastian.huber@…>, on 01/28/21 at 10:40:10

kern_tc.c: Remove unused code

This fix relates to a Coverity issue (PW.DECLARED_BUT_NOT_REFERENCED).

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