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

5
Last change on this file since fce900b5 was 5f02a57, checked in by Sebastian Huber <sebastian.huber@…>, on 10/24/17 at 09:17:54

score: Change _Timecounter_Time_uptime to int32_t

Move basic timecounter API shared with BSD network stack to
<machine/_timecounter.h>.

Update #3185.

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