source: rtems/cpukit/score/src/kern_tc.c @ 47e5c1d

5
Last change on this file since 47e5c1d was 47e5c1d, checked in by Sebastian Huber <sebastian.huber@…>, on 10/01/19 at 11:04:29

score: Remove strange timecounter init step

The double call of the timecounter get method was added to FreeBSD in
2002 without a comment. It is not clear why this is needed.

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