source: rtems/cpukit/score/src/kern_tc.c @ 4d0ade9

5
Last change on this file since 4d0ade9 was 4d0ade9, checked in by Konstantin Belousov <kib@…>, on 06/11/15 at 04:41:54

timecounter: Merge FreeBSD change r284256

Tweaks for r284178:

Do not include machine/atomic.h explicitely, the header is already included
by sys/systm.h.

Force inlining of tc_getgen() and tc_setgen(). The functions are used
more than once, which causes compilers with non-aggressive inlining
policies to generate calls.

Suggested by: bde
Sponsored by: The FreeBSD Foundation
MFC after: 1 week

Update #3175.

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