Home | History | Annotate | Line # | Download | only in kern
kern_tc.c revision 1.56
      1  1.56       rin /* $NetBSD: kern_tc.c,v 1.56 2020/05/27 08:47:15 rin Exp $ */
      2  1.33        ad 
      3  1.33        ad /*-
      4  1.39        ad  * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
      5  1.33        ad  * All rights reserved.
      6  1.33        ad  *
      7  1.39        ad  * This code is derived from software contributed to The NetBSD Foundation
      8  1.39        ad  * by Andrew Doran.
      9  1.39        ad  *
     10  1.33        ad  * Redistribution and use in source and binary forms, with or without
     11  1.33        ad  * modification, are permitted provided that the following conditions
     12  1.33        ad  * are met:
     13  1.33        ad  * 1. Redistributions of source code must retain the above copyright
     14  1.33        ad  *    notice, this list of conditions and the following disclaimer.
     15  1.33        ad  * 2. Redistributions in binary form must reproduce the above copyright
     16  1.33        ad  *    notice, this list of conditions and the following disclaimer in the
     17  1.33        ad  *    documentation and/or other materials provided with the distribution.
     18  1.33        ad  *
     19  1.33        ad  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  1.33        ad  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  1.33        ad  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  1.33        ad  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  1.33        ad  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  1.33        ad  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  1.33        ad  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  1.33        ad  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  1.33        ad  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  1.33        ad  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  1.33        ad  * POSSIBILITY OF SUCH DAMAGE.
     30  1.33        ad  */
     31   1.2    kardel 
     32   1.1    simonb /*-
     33   1.1    simonb  * ----------------------------------------------------------------------------
     34   1.1    simonb  * "THE BEER-WARE LICENSE" (Revision 42):
     35   1.1    simonb  * <phk (at) FreeBSD.ORG> wrote this file.  As long as you retain this notice you
     36   1.1    simonb  * can do whatever you want with this stuff. If we meet some day, and you think
     37   1.1    simonb  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
     38   1.2    kardel  * ---------------------------------------------------------------------------
     39   1.1    simonb  */
     40   1.1    simonb 
     41   1.1    simonb #include <sys/cdefs.h>
     42   1.2    kardel /* __FBSDID("$FreeBSD: src/sys/kern/kern_tc.c,v 1.166 2005/09/19 22:16:31 andre Exp $"); */
     43  1.56       rin __KERNEL_RCSID(0, "$NetBSD: kern_tc.c,v 1.56 2020/05/27 08:47:15 rin Exp $");
     44   1.1    simonb 
     45  1.42     pooka #ifdef _KERNEL_OPT
     46   1.1    simonb #include "opt_ntp.h"
     47  1.42     pooka #endif
     48   1.1    simonb 
     49   1.1    simonb #include <sys/param.h>
     50   1.1    simonb #include <sys/kernel.h>
     51   1.2    kardel #include <sys/reboot.h>	/* XXX just to get AB_VERBOSE */
     52   1.1    simonb #include <sys/sysctl.h>
     53   1.1    simonb #include <sys/syslog.h>
     54   1.1    simonb #include <sys/systm.h>
     55   1.1    simonb #include <sys/timepps.h>
     56   1.1    simonb #include <sys/timetc.h>
     57   1.1    simonb #include <sys/timex.h>
     58   1.2    kardel #include <sys/evcnt.h>
     59   1.2    kardel #include <sys/kauth.h>
     60  1.25        ad #include <sys/mutex.h>
     61  1.27        ad #include <sys/atomic.h>
     62  1.39        ad #include <sys/xcall.h>
     63   1.2    kardel 
     64   1.2    kardel /*
     65   1.1    simonb  * A large step happens on boot.  This constant detects such steps.
     66   1.1    simonb  * It is relatively small so that ntp_update_second gets called enough
     67   1.1    simonb  * in the typical 'missed a couple of seconds' case, but doesn't loop
     68   1.1    simonb  * forever when the time step is large.
     69   1.1    simonb  */
     70   1.1    simonb #define LARGE_STEP	200
     71   1.1    simonb 
     72   1.1    simonb /*
     73   1.1    simonb  * Implement a dummy timecounter which we can use until we get a real one
     74   1.1    simonb  * in the air.  This allows the console and other early stuff to use
     75   1.1    simonb  * time services.
     76   1.1    simonb  */
     77   1.1    simonb 
     78   1.1    simonb static u_int
     79  1.16      yamt dummy_get_timecount(struct timecounter *tc)
     80   1.1    simonb {
     81   1.1    simonb 	static u_int now;
     82   1.1    simonb 
     83   1.1    simonb 	return (++now);
     84   1.1    simonb }
     85   1.1    simonb 
     86   1.1    simonb static struct timecounter dummy_timecounter = {
     87  1.48  riastrad 	.tc_get_timecount	= dummy_get_timecount,
     88  1.48  riastrad 	.tc_counter_mask	= ~0u,
     89  1.48  riastrad 	.tc_frequency		= 1000000,
     90  1.48  riastrad 	.tc_name		= "dummy",
     91  1.48  riastrad 	.tc_quality		= -1000000,
     92  1.48  riastrad 	.tc_priv		= NULL,
     93   1.1    simonb };
     94   1.1    simonb 
     95   1.1    simonb struct timehands {
     96   1.1    simonb 	/* These fields must be initialized by the driver. */
     97  1.40    kardel 	struct timecounter	*th_counter;     /* active timecounter */
     98  1.40    kardel 	int64_t			th_adjustment;   /* frequency adjustment */
     99  1.40    kardel 						 /* (NTP/adjtime) */
    100  1.40    kardel 	u_int64_t		th_scale;        /* scale factor (counter */
    101  1.40    kardel 						 /* tick->time) */
    102  1.40    kardel 	u_int64_t 		th_offset_count; /* offset at last time */
    103  1.40    kardel 						 /* update (tc_windup()) */
    104  1.40    kardel 	struct bintime		th_offset;       /* bin (up)time at windup */
    105  1.40    kardel 	struct timeval		th_microtime;    /* cached microtime */
    106  1.40    kardel 	struct timespec		th_nanotime;     /* cached nanotime */
    107   1.1    simonb 	/* Fields not to be copied in tc_windup start with th_generation. */
    108  1.40    kardel 	volatile u_int		th_generation;   /* current genration */
    109  1.40    kardel 	struct timehands	*th_next;        /* next timehand */
    110   1.1    simonb };
    111   1.1    simonb 
    112   1.1    simonb static struct timehands th0;
    113  1.10  christos static struct timehands th9 = { .th_next = &th0, };
    114  1.10  christos static struct timehands th8 = { .th_next = &th9, };
    115  1.10  christos static struct timehands th7 = { .th_next = &th8, };
    116  1.10  christos static struct timehands th6 = { .th_next = &th7, };
    117  1.10  christos static struct timehands th5 = { .th_next = &th6, };
    118  1.10  christos static struct timehands th4 = { .th_next = &th5, };
    119  1.10  christos static struct timehands th3 = { .th_next = &th4, };
    120  1.10  christos static struct timehands th2 = { .th_next = &th3, };
    121  1.10  christos static struct timehands th1 = { .th_next = &th2, };
    122   1.1    simonb static struct timehands th0 = {
    123  1.10  christos 	.th_counter = &dummy_timecounter,
    124  1.10  christos 	.th_scale = (uint64_t)-1 / 1000000,
    125  1.10  christos 	.th_offset = { .sec = 1, .frac = 0 },
    126  1.10  christos 	.th_generation = 1,
    127  1.10  christos 	.th_next = &th1,
    128   1.1    simonb };
    129   1.1    simonb 
    130   1.1    simonb static struct timehands *volatile timehands = &th0;
    131   1.1    simonb struct timecounter *timecounter = &dummy_timecounter;
    132   1.1    simonb static struct timecounter *timecounters = &dummy_timecounter;
    133   1.1    simonb 
    134  1.49      maxv volatile time_t time_second __cacheline_aligned = 1;
    135  1.49      maxv volatile time_t time_uptime __cacheline_aligned = 1;
    136   1.1    simonb 
    137   1.4    kardel static struct bintime timebasebin;
    138   1.1    simonb 
    139   1.1    simonb static int timestepwarnings;
    140   1.2    kardel 
    141  1.33        ad kmutex_t timecounter_lock;
    142  1.35        ad static u_int timecounter_mods;
    143  1.39        ad static volatile int timecounter_removals = 1;
    144  1.35        ad static u_int timecounter_bad;
    145  1.25        ad 
    146   1.2    kardel #ifdef __FreeBSD__
    147   1.1    simonb SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
    148   1.1    simonb     &timestepwarnings, 0, "");
    149   1.2    kardel #endif /* __FreeBSD__ */
    150   1.2    kardel 
    151   1.2    kardel /*
    152  1.28      yamt  * sysctl helper routine for kern.timercounter.hardware
    153   1.2    kardel  */
    154   1.2    kardel static int
    155   1.2    kardel sysctl_kern_timecounter_hardware(SYSCTLFN_ARGS)
    156   1.2    kardel {
    157   1.2    kardel 	struct sysctlnode node;
    158   1.2    kardel 	int error;
    159   1.2    kardel 	char newname[MAX_TCNAMELEN];
    160   1.2    kardel 	struct timecounter *newtc, *tc;
    161   1.2    kardel 
    162   1.2    kardel 	tc = timecounter;
    163   1.2    kardel 
    164   1.2    kardel 	strlcpy(newname, tc->tc_name, sizeof(newname));
    165   1.2    kardel 
    166   1.2    kardel 	node = *rnode;
    167   1.2    kardel 	node.sysctl_data = newname;
    168   1.2    kardel 	node.sysctl_size = sizeof(newname);
    169   1.2    kardel 
    170   1.2    kardel 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    171   1.2    kardel 
    172   1.2    kardel 	if (error ||
    173   1.2    kardel 	    newp == NULL ||
    174   1.2    kardel 	    strncmp(newname, tc->tc_name, sizeof(newname)) == 0)
    175   1.2    kardel 		return error;
    176   1.1    simonb 
    177  1.26      elad 	if (l != NULL && (error = kauth_authorize_system(l->l_cred,
    178  1.26      elad 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_TIMECOUNTERS, newname,
    179  1.26      elad 	    NULL, NULL)) != 0)
    180   1.2    kardel 		return (error);
    181   1.2    kardel 
    182  1.22        ad 	if (!cold)
    183  1.35        ad 		mutex_spin_enter(&timecounter_lock);
    184  1.23        ad 	error = EINVAL;
    185   1.2    kardel 	for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
    186   1.2    kardel 		if (strcmp(newname, newtc->tc_name) != 0)
    187   1.2    kardel 			continue;
    188   1.2    kardel 		/* Warm up new timecounter. */
    189   1.2    kardel 		(void)newtc->tc_get_timecount(newtc);
    190   1.2    kardel 		(void)newtc->tc_get_timecount(newtc);
    191   1.2    kardel 		timecounter = newtc;
    192  1.22        ad 		error = 0;
    193  1.23        ad 		break;
    194  1.23        ad 	}
    195  1.22        ad 	if (!cold)
    196  1.35        ad 		mutex_spin_exit(&timecounter_lock);
    197  1.22        ad 	return error;
    198   1.2    kardel }
    199   1.2    kardel 
    200   1.2    kardel static int
    201   1.2    kardel sysctl_kern_timecounter_choice(SYSCTLFN_ARGS)
    202   1.2    kardel {
    203   1.9    kardel 	char buf[MAX_TCNAMELEN+48];
    204  1.35        ad 	char *where;
    205   1.2    kardel 	const char *spc;
    206   1.2    kardel 	struct timecounter *tc;
    207   1.2    kardel 	size_t needed, left, slen;
    208  1.35        ad 	int error, mods;
    209   1.2    kardel 
    210   1.2    kardel 	if (newp != NULL)
    211   1.2    kardel 		return (EPERM);
    212   1.2    kardel 	if (namelen != 0)
    213   1.2    kardel 		return (EINVAL);
    214   1.2    kardel 
    215  1.35        ad 	mutex_spin_enter(&timecounter_lock);
    216  1.35        ad  retry:
    217   1.2    kardel 	spc = "";
    218   1.2    kardel 	error = 0;
    219   1.2    kardel 	needed = 0;
    220   1.2    kardel 	left = *oldlenp;
    221  1.35        ad 	where = oldp;
    222   1.2    kardel 	for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
    223   1.2    kardel 		if (where == NULL) {
    224   1.2    kardel 			needed += sizeof(buf);  /* be conservative */
    225   1.2    kardel 		} else {
    226   1.2    kardel 			slen = snprintf(buf, sizeof(buf), "%s%s(q=%d, f=%" PRId64
    227   1.2    kardel 					" Hz)", spc, tc->tc_name, tc->tc_quality,
    228   1.2    kardel 					tc->tc_frequency);
    229   1.2    kardel 			if (left < slen + 1)
    230   1.2    kardel 				break;
    231  1.35        ad 		 	mods = timecounter_mods;
    232  1.35        ad 			mutex_spin_exit(&timecounter_lock);
    233   1.2    kardel 			error = copyout(buf, where, slen + 1);
    234  1.35        ad 			mutex_spin_enter(&timecounter_lock);
    235  1.35        ad 			if (mods != timecounter_mods) {
    236  1.35        ad 				goto retry;
    237  1.35        ad 			}
    238   1.2    kardel 			spc = " ";
    239   1.2    kardel 			where += slen;
    240   1.2    kardel 			needed += slen;
    241   1.2    kardel 			left -= slen;
    242   1.2    kardel 		}
    243   1.2    kardel 	}
    244  1.35        ad 	mutex_spin_exit(&timecounter_lock);
    245   1.2    kardel 
    246   1.2    kardel 	*oldlenp = needed;
    247   1.2    kardel 	return (error);
    248   1.2    kardel }
    249   1.2    kardel 
    250   1.2    kardel SYSCTL_SETUP(sysctl_timecounter_setup, "sysctl timecounter setup")
    251   1.2    kardel {
    252   1.2    kardel 	const struct sysctlnode *node;
    253   1.2    kardel 
    254   1.2    kardel 	sysctl_createv(clog, 0, NULL, &node,
    255   1.2    kardel 		       CTLFLAG_PERMANENT,
    256   1.2    kardel 		       CTLTYPE_NODE, "timecounter",
    257   1.2    kardel 		       SYSCTL_DESCR("time counter information"),
    258   1.2    kardel 		       NULL, 0, NULL, 0,
    259   1.2    kardel 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    260   1.2    kardel 
    261   1.2    kardel 	if (node != NULL) {
    262   1.2    kardel 		sysctl_createv(clog, 0, NULL, NULL,
    263   1.2    kardel 			       CTLFLAG_PERMANENT,
    264   1.2    kardel 			       CTLTYPE_STRING, "choice",
    265   1.2    kardel 			       SYSCTL_DESCR("available counters"),
    266   1.2    kardel 			       sysctl_kern_timecounter_choice, 0, NULL, 0,
    267   1.2    kardel 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    268   1.2    kardel 
    269   1.2    kardel 		sysctl_createv(clog, 0, NULL, NULL,
    270   1.2    kardel 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    271   1.2    kardel 			       CTLTYPE_STRING, "hardware",
    272   1.2    kardel 			       SYSCTL_DESCR("currently active time counter"),
    273   1.2    kardel 			       sysctl_kern_timecounter_hardware, 0, NULL, MAX_TCNAMELEN,
    274   1.2    kardel 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    275   1.2    kardel 
    276   1.2    kardel 		sysctl_createv(clog, 0, NULL, NULL,
    277   1.2    kardel 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    278   1.2    kardel 			       CTLTYPE_INT, "timestepwarnings",
    279   1.2    kardel 			       SYSCTL_DESCR("log time steps"),
    280   1.2    kardel 			       NULL, 0, &timestepwarnings, 0,
    281   1.2    kardel 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    282   1.2    kardel 	}
    283   1.2    kardel }
    284   1.2    kardel 
    285  1.32        ad #ifdef TC_COUNTERS
    286   1.2    kardel #define	TC_STATS(name)							\
    287   1.2    kardel static struct evcnt n##name =						\
    288   1.2    kardel     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "timecounter", #name);	\
    289   1.2    kardel EVCNT_ATTACH_STATIC(n##name)
    290   1.2    kardel TC_STATS(binuptime);    TC_STATS(nanouptime);    TC_STATS(microuptime);
    291   1.2    kardel TC_STATS(bintime);      TC_STATS(nanotime);      TC_STATS(microtime);
    292   1.2    kardel TC_STATS(getbinuptime); TC_STATS(getnanouptime); TC_STATS(getmicrouptime);
    293   1.2    kardel TC_STATS(getbintime);   TC_STATS(getnanotime);   TC_STATS(getmicrotime);
    294   1.2    kardel TC_STATS(setclock);
    295  1.32        ad #define	TC_COUNT(var)	var.ev_count++
    296   1.1    simonb #undef TC_STATS
    297  1.32        ad #else
    298  1.32        ad #define	TC_COUNT(var)	/* nothing */
    299  1.32        ad #endif	/* TC_COUNTERS */
    300   1.1    simonb 
    301   1.1    simonb static void tc_windup(void);
    302   1.1    simonb 
    303   1.1    simonb /*
    304   1.1    simonb  * Return the difference between the timehands' counter value now and what
    305   1.1    simonb  * was when we copied it to the timehands' offset_count.
    306   1.1    simonb  */
    307  1.41  uebayasi static inline u_int
    308   1.1    simonb tc_delta(struct timehands *th)
    309   1.1    simonb {
    310   1.1    simonb 	struct timecounter *tc;
    311   1.1    simonb 
    312   1.1    simonb 	tc = th->th_counter;
    313   1.2    kardel 	return ((tc->tc_get_timecount(tc) -
    314   1.2    kardel 		 th->th_offset_count) & tc->tc_counter_mask);
    315   1.1    simonb }
    316   1.1    simonb 
    317   1.1    simonb /*
    318   1.1    simonb  * Functions for reading the time.  We have to loop until we are sure that
    319   1.1    simonb  * the timehands that we operated on was not updated under our feet.  See
    320  1.21    simonb  * the comment in <sys/timevar.h> for a description of these 12 functions.
    321   1.1    simonb  */
    322   1.1    simonb 
    323   1.1    simonb void
    324   1.1    simonb binuptime(struct bintime *bt)
    325   1.1    simonb {
    326   1.1    simonb 	struct timehands *th;
    327  1.39        ad 	lwp_t *l;
    328  1.39        ad 	u_int lgen, gen;
    329   1.1    simonb 
    330  1.32        ad 	TC_COUNT(nbinuptime);
    331  1.39        ad 
    332  1.39        ad 	/*
    333  1.39        ad 	 * Provide exclusion against tc_detach().
    334  1.39        ad 	 *
    335  1.39        ad 	 * We record the number of timecounter removals before accessing
    336  1.39        ad 	 * timecounter state.  Note that the LWP can be using multiple
    337  1.39        ad 	 * "generations" at once, due to interrupts (interrupted while in
    338  1.39        ad 	 * this function).  Hardware interrupts will borrow the interrupted
    339  1.39        ad 	 * LWP's l_tcgen value for this purpose, and can themselves be
    340  1.39        ad 	 * interrupted by higher priority interrupts.  In this case we need
    341  1.39        ad 	 * to ensure that the oldest generation in use is recorded.
    342  1.39        ad 	 *
    343  1.39        ad 	 * splsched() is too expensive to use, so we take care to structure
    344  1.39        ad 	 * this code in such a way that it is not required.  Likewise, we
    345  1.39        ad 	 * do not disable preemption.
    346  1.39        ad 	 *
    347  1.39        ad 	 * Memory barriers are also too expensive to use for such a
    348  1.39        ad 	 * performance critical function.  The good news is that we do not
    349  1.39        ad 	 * need memory barriers for this type of exclusion, as the thread
    350  1.39        ad 	 * updating timecounter_removals will issue a broadcast cross call
    351  1.39        ad 	 * before inspecting our l_tcgen value (this elides memory ordering
    352  1.39        ad 	 * issues).
    353  1.39        ad 	 */
    354  1.39        ad 	l = curlwp;
    355  1.39        ad 	lgen = l->l_tcgen;
    356  1.39        ad 	if (__predict_true(lgen == 0)) {
    357  1.39        ad 		l->l_tcgen = timecounter_removals;
    358  1.39        ad 	}
    359  1.39        ad 	__insn_barrier();
    360  1.39        ad 
    361   1.1    simonb 	do {
    362   1.1    simonb 		th = timehands;
    363   1.1    simonb 		gen = th->th_generation;
    364   1.1    simonb 		*bt = th->th_offset;
    365   1.1    simonb 		bintime_addx(bt, th->th_scale * tc_delta(th));
    366   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    367  1.39        ad 
    368  1.39        ad 	__insn_barrier();
    369  1.39        ad 	l->l_tcgen = lgen;
    370   1.1    simonb }
    371   1.1    simonb 
    372   1.1    simonb void
    373   1.1    simonb nanouptime(struct timespec *tsp)
    374   1.1    simonb {
    375   1.1    simonb 	struct bintime bt;
    376   1.1    simonb 
    377  1.32        ad 	TC_COUNT(nnanouptime);
    378   1.1    simonb 	binuptime(&bt);
    379   1.1    simonb 	bintime2timespec(&bt, tsp);
    380   1.1    simonb }
    381   1.1    simonb 
    382   1.1    simonb void
    383   1.1    simonb microuptime(struct timeval *tvp)
    384   1.1    simonb {
    385   1.1    simonb 	struct bintime bt;
    386   1.1    simonb 
    387  1.32        ad 	TC_COUNT(nmicrouptime);
    388   1.1    simonb 	binuptime(&bt);
    389   1.1    simonb 	bintime2timeval(&bt, tvp);
    390   1.1    simonb }
    391   1.1    simonb 
    392   1.1    simonb void
    393   1.1    simonb bintime(struct bintime *bt)
    394   1.1    simonb {
    395   1.1    simonb 
    396  1.32        ad 	TC_COUNT(nbintime);
    397   1.1    simonb 	binuptime(bt);
    398   1.4    kardel 	bintime_add(bt, &timebasebin);
    399   1.1    simonb }
    400   1.1    simonb 
    401   1.1    simonb void
    402   1.1    simonb nanotime(struct timespec *tsp)
    403   1.1    simonb {
    404   1.1    simonb 	struct bintime bt;
    405   1.1    simonb 
    406  1.32        ad 	TC_COUNT(nnanotime);
    407   1.1    simonb 	bintime(&bt);
    408   1.1    simonb 	bintime2timespec(&bt, tsp);
    409   1.1    simonb }
    410   1.1    simonb 
    411   1.1    simonb void
    412   1.1    simonb microtime(struct timeval *tvp)
    413   1.1    simonb {
    414   1.1    simonb 	struct bintime bt;
    415   1.1    simonb 
    416  1.32        ad 	TC_COUNT(nmicrotime);
    417   1.1    simonb 	bintime(&bt);
    418   1.1    simonb 	bintime2timeval(&bt, tvp);
    419   1.1    simonb }
    420   1.1    simonb 
    421   1.1    simonb void
    422   1.1    simonb getbinuptime(struct bintime *bt)
    423   1.1    simonb {
    424   1.1    simonb 	struct timehands *th;
    425   1.1    simonb 	u_int gen;
    426   1.1    simonb 
    427  1.32        ad 	TC_COUNT(ngetbinuptime);
    428   1.1    simonb 	do {
    429   1.1    simonb 		th = timehands;
    430   1.1    simonb 		gen = th->th_generation;
    431   1.1    simonb 		*bt = th->th_offset;
    432   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    433   1.1    simonb }
    434   1.1    simonb 
    435   1.1    simonb void
    436   1.1    simonb getnanouptime(struct timespec *tsp)
    437   1.1    simonb {
    438   1.1    simonb 	struct timehands *th;
    439   1.1    simonb 	u_int gen;
    440   1.1    simonb 
    441  1.32        ad 	TC_COUNT(ngetnanouptime);
    442   1.1    simonb 	do {
    443   1.1    simonb 		th = timehands;
    444   1.1    simonb 		gen = th->th_generation;
    445   1.1    simonb 		bintime2timespec(&th->th_offset, tsp);
    446   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    447   1.1    simonb }
    448   1.1    simonb 
    449   1.1    simonb void
    450   1.1    simonb getmicrouptime(struct timeval *tvp)
    451   1.1    simonb {
    452   1.1    simonb 	struct timehands *th;
    453   1.1    simonb 	u_int gen;
    454   1.1    simonb 
    455  1.32        ad 	TC_COUNT(ngetmicrouptime);
    456   1.1    simonb 	do {
    457   1.1    simonb 		th = timehands;
    458   1.1    simonb 		gen = th->th_generation;
    459   1.1    simonb 		bintime2timeval(&th->th_offset, tvp);
    460   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    461   1.1    simonb }
    462   1.1    simonb 
    463   1.1    simonb void
    464   1.1    simonb getbintime(struct bintime *bt)
    465   1.1    simonb {
    466   1.1    simonb 	struct timehands *th;
    467   1.1    simonb 	u_int gen;
    468   1.1    simonb 
    469  1.32        ad 	TC_COUNT(ngetbintime);
    470   1.1    simonb 	do {
    471   1.1    simonb 		th = timehands;
    472   1.1    simonb 		gen = th->th_generation;
    473   1.1    simonb 		*bt = th->th_offset;
    474   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    475   1.4    kardel 	bintime_add(bt, &timebasebin);
    476   1.1    simonb }
    477   1.1    simonb 
    478  1.47       chs static inline void
    479  1.47       chs dogetnanotime(struct timespec *tsp)
    480   1.1    simonb {
    481   1.1    simonb 	struct timehands *th;
    482   1.1    simonb 	u_int gen;
    483   1.1    simonb 
    484  1.32        ad 	TC_COUNT(ngetnanotime);
    485   1.1    simonb 	do {
    486   1.1    simonb 		th = timehands;
    487   1.1    simonb 		gen = th->th_generation;
    488   1.1    simonb 		*tsp = th->th_nanotime;
    489   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    490   1.1    simonb }
    491   1.1    simonb 
    492   1.1    simonb void
    493  1.47       chs getnanotime(struct timespec *tsp)
    494  1.47       chs {
    495  1.47       chs 
    496  1.47       chs 	dogetnanotime(tsp);
    497  1.47       chs }
    498  1.47       chs 
    499  1.47       chs void dtrace_getnanotime(struct timespec *tsp);
    500  1.47       chs 
    501  1.47       chs void
    502  1.47       chs dtrace_getnanotime(struct timespec *tsp)
    503  1.47       chs {
    504  1.47       chs 
    505  1.47       chs 	dogetnanotime(tsp);
    506  1.47       chs }
    507  1.47       chs 
    508  1.47       chs void
    509   1.1    simonb getmicrotime(struct timeval *tvp)
    510   1.1    simonb {
    511   1.1    simonb 	struct timehands *th;
    512   1.1    simonb 	u_int gen;
    513   1.1    simonb 
    514  1.32        ad 	TC_COUNT(ngetmicrotime);
    515   1.1    simonb 	do {
    516   1.1    simonb 		th = timehands;
    517   1.1    simonb 		gen = th->th_generation;
    518   1.1    simonb 		*tvp = th->th_microtime;
    519   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    520   1.1    simonb }
    521   1.1    simonb 
    522  1.54   thorpej void
    523  1.54   thorpej getnanoboottime(struct timespec *tsp)
    524  1.54   thorpej {
    525  1.54   thorpej 	struct bintime bt;
    526  1.54   thorpej 
    527  1.54   thorpej 	getbinboottime(&bt);
    528  1.54   thorpej 	bintime2timespec(&bt, tsp);
    529  1.54   thorpej }
    530  1.54   thorpej 
    531  1.54   thorpej void
    532  1.54   thorpej getmicroboottime(struct timeval *tvp)
    533  1.54   thorpej {
    534  1.54   thorpej 	struct bintime bt;
    535  1.54   thorpej 
    536  1.54   thorpej 	getbinboottime(&bt);
    537  1.54   thorpej 	bintime2timeval(&bt, tvp);
    538  1.54   thorpej }
    539  1.54   thorpej 
    540  1.54   thorpej void
    541  1.54   thorpej getbinboottime(struct bintime *bt)
    542  1.54   thorpej {
    543  1.54   thorpej 
    544  1.54   thorpej 	/*
    545  1.54   thorpej 	 * XXX Need lockless read synchronization around timebasebin
    546  1.54   thorpej 	 * (and not just here).
    547  1.54   thorpej 	 */
    548  1.54   thorpej 	*bt = timebasebin;
    549  1.54   thorpej }
    550  1.54   thorpej 
    551   1.1    simonb /*
    552   1.1    simonb  * Initialize a new timecounter and possibly use it.
    553   1.1    simonb  */
    554   1.1    simonb void
    555   1.1    simonb tc_init(struct timecounter *tc)
    556   1.1    simonb {
    557   1.1    simonb 	u_int u;
    558   1.1    simonb 
    559   1.1    simonb 	u = tc->tc_frequency / tc->tc_counter_mask;
    560   1.1    simonb 	/* XXX: We need some margin here, 10% is a guess */
    561   1.1    simonb 	u *= 11;
    562   1.1    simonb 	u /= 10;
    563   1.1    simonb 	if (u > hz && tc->tc_quality >= 0) {
    564   1.1    simonb 		tc->tc_quality = -2000;
    565  1.18        ad 		aprint_verbose(
    566  1.18        ad 		    "timecounter: Timecounter \"%s\" frequency %ju Hz",
    567   1.7     bjh21 			    tc->tc_name, (uintmax_t)tc->tc_frequency);
    568  1.18        ad 		aprint_verbose(" -- Insufficient hz, needs at least %u\n", u);
    569   1.1    simonb 	} else if (tc->tc_quality >= 0 || bootverbose) {
    570  1.18        ad 		aprint_verbose(
    571  1.18        ad 		    "timecounter: Timecounter \"%s\" frequency %ju Hz "
    572  1.18        ad 		    "quality %d\n", tc->tc_name, (uintmax_t)tc->tc_frequency,
    573   1.7     bjh21 		    tc->tc_quality);
    574   1.1    simonb 	}
    575   1.1    simonb 
    576  1.33        ad 	mutex_spin_enter(&timecounter_lock);
    577   1.1    simonb 	tc->tc_next = timecounters;
    578   1.1    simonb 	timecounters = tc;
    579  1.35        ad 	timecounter_mods++;
    580   1.1    simonb 	/*
    581   1.1    simonb 	 * Never automatically use a timecounter with negative quality.
    582   1.1    simonb 	 * Even though we run on the dummy counter, switching here may be
    583   1.1    simonb 	 * worse since this timecounter may not be monotonous.
    584   1.1    simonb 	 */
    585  1.22        ad 	if (tc->tc_quality >= 0 && (tc->tc_quality > timecounter->tc_quality ||
    586  1.24        ad 	    (tc->tc_quality == timecounter->tc_quality &&
    587  1.24        ad 	    tc->tc_frequency > timecounter->tc_frequency))) {
    588  1.22        ad 		(void)tc->tc_get_timecount(tc);
    589  1.22        ad 		(void)tc->tc_get_timecount(tc);
    590  1.22        ad 		timecounter = tc;
    591  1.22        ad 		tc_windup();
    592  1.22        ad 	}
    593  1.33        ad 	mutex_spin_exit(&timecounter_lock);
    594  1.35        ad }
    595  1.35        ad 
    596  1.35        ad /*
    597  1.35        ad  * Pick a new timecounter due to the existing counter going bad.
    598  1.35        ad  */
    599  1.35        ad static void
    600  1.35        ad tc_pick(void)
    601  1.35        ad {
    602  1.35        ad 	struct timecounter *best, *tc;
    603  1.35        ad 
    604  1.51  riastrad 	KASSERT(mutex_owned(&timecounter_lock));
    605  1.35        ad 
    606  1.35        ad 	for (best = tc = timecounters; tc != NULL; tc = tc->tc_next) {
    607  1.35        ad 		if (tc->tc_quality > best->tc_quality)
    608  1.35        ad 			best = tc;
    609  1.35        ad 		else if (tc->tc_quality < best->tc_quality)
    610  1.35        ad 			continue;
    611  1.35        ad 		else if (tc->tc_frequency > best->tc_frequency)
    612  1.35        ad 			best = tc;
    613  1.35        ad 	}
    614  1.35        ad 	(void)best->tc_get_timecount(best);
    615  1.35        ad 	(void)best->tc_get_timecount(best);
    616  1.35        ad 	timecounter = best;
    617  1.35        ad }
    618  1.35        ad 
    619  1.35        ad /*
    620  1.35        ad  * A timecounter has gone bad, arrange to pick a new one at the next
    621  1.35        ad  * clock tick.
    622  1.35        ad  */
    623  1.35        ad void
    624  1.35        ad tc_gonebad(struct timecounter *tc)
    625  1.35        ad {
    626  1.35        ad 
    627  1.35        ad 	tc->tc_quality = -100;
    628  1.35        ad 	membar_producer();
    629  1.35        ad 	atomic_inc_uint(&timecounter_bad);
    630   1.1    simonb }
    631   1.1    simonb 
    632  1.29    dyoung /*
    633  1.29    dyoung  * Stop using a timecounter and remove it from the timecounters list.
    634  1.29    dyoung  */
    635  1.29    dyoung int
    636  1.29    dyoung tc_detach(struct timecounter *target)
    637  1.29    dyoung {
    638  1.35        ad 	struct timecounter *tc;
    639  1.29    dyoung 	struct timecounter **tcp = NULL;
    640  1.39        ad 	int removals;
    641  1.39        ad 	lwp_t *l;
    642  1.29    dyoung 
    643  1.39        ad 	/* First, find the timecounter. */
    644  1.35        ad 	mutex_spin_enter(&timecounter_lock);
    645  1.29    dyoung 	for (tcp = &timecounters, tc = timecounters;
    646  1.29    dyoung 	     tc != NULL;
    647  1.29    dyoung 	     tcp = &tc->tc_next, tc = tc->tc_next) {
    648  1.29    dyoung 		if (tc == target)
    649  1.29    dyoung 			break;
    650  1.29    dyoung 	}
    651  1.29    dyoung 	if (tc == NULL) {
    652  1.39        ad 		mutex_spin_exit(&timecounter_lock);
    653  1.39        ad 		return ESRCH;
    654  1.39        ad 	}
    655  1.39        ad 
    656  1.39        ad 	/* And now, remove it. */
    657  1.39        ad 	*tcp = tc->tc_next;
    658  1.39        ad 	if (timecounter == target) {
    659  1.39        ad 		tc_pick();
    660  1.39        ad 		tc_windup();
    661  1.39        ad 	}
    662  1.39        ad 	timecounter_mods++;
    663  1.39        ad 	removals = timecounter_removals++;
    664  1.39        ad 	mutex_spin_exit(&timecounter_lock);
    665  1.39        ad 
    666  1.39        ad 	/*
    667  1.39        ad 	 * We now have to determine if any threads in the system are still
    668  1.39        ad 	 * making use of this timecounter.
    669  1.39        ad 	 *
    670  1.39        ad 	 * We issue a broadcast cross call to elide memory ordering issues,
    671  1.39        ad 	 * then scan all LWPs in the system looking at each's timecounter
    672  1.39        ad 	 * generation number.  We need to see a value of zero (not actively
    673  1.39        ad 	 * using a timecounter) or a value greater than our removal value.
    674  1.39        ad 	 *
    675  1.39        ad 	 * We may race with threads that read `timecounter_removals' and
    676  1.39        ad 	 * and then get preempted before updating `l_tcgen'.  This is not
    677  1.39        ad 	 * a problem, since it means that these threads have not yet started
    678  1.39        ad 	 * accessing timecounter state.  All we do need is one clean
    679  1.39        ad 	 * snapshot of the system where every thread appears not to be using
    680  1.39        ad 	 * old timecounter state.
    681  1.39        ad 	 */
    682  1.39        ad 	for (;;) {
    683  1.52       uwe 		xc_barrier(0);
    684  1.39        ad 
    685  1.55        ad 		mutex_enter(&proc_lock);
    686  1.39        ad 		LIST_FOREACH(l, &alllwp, l_list) {
    687  1.39        ad 			if (l->l_tcgen == 0 || l->l_tcgen > removals) {
    688  1.39        ad 				/*
    689  1.39        ad 				 * Not using timecounter or old timecounter
    690  1.39        ad 				 * state at time of our xcall or later.
    691  1.39        ad 				 */
    692  1.39        ad 				continue;
    693  1.39        ad 			}
    694  1.39        ad 			break;
    695  1.39        ad 		}
    696  1.55        ad 		mutex_exit(&proc_lock);
    697  1.39        ad 
    698  1.39        ad 		/*
    699  1.39        ad 		 * If the timecounter is still in use, wait at least 10ms
    700  1.39        ad 		 * before retrying.
    701  1.39        ad 		 */
    702  1.39        ad 		if (l == NULL) {
    703  1.39        ad 			return 0;
    704  1.35        ad 		}
    705  1.39        ad 		(void)kpause("tcdetach", false, mstohz(10), NULL);
    706  1.29    dyoung 	}
    707  1.29    dyoung }
    708  1.29    dyoung 
    709   1.1    simonb /* Report the frequency of the current timecounter. */
    710   1.1    simonb u_int64_t
    711   1.1    simonb tc_getfrequency(void)
    712   1.1    simonb {
    713   1.1    simonb 
    714   1.1    simonb 	return (timehands->th_counter->tc_frequency);
    715   1.1    simonb }
    716   1.1    simonb 
    717   1.1    simonb /*
    718   1.1    simonb  * Step our concept of UTC.  This is done by modifying our estimate of
    719   1.1    simonb  * when we booted.
    720   1.1    simonb  */
    721   1.1    simonb void
    722  1.38  christos tc_setclock(const struct timespec *ts)
    723   1.1    simonb {
    724   1.1    simonb 	struct timespec ts2;
    725   1.1    simonb 	struct bintime bt, bt2;
    726   1.1    simonb 
    727  1.33        ad 	mutex_spin_enter(&timecounter_lock);
    728  1.32        ad 	TC_COUNT(nsetclock);
    729   1.1    simonb 	binuptime(&bt2);
    730   1.1    simonb 	timespec2bintime(ts, &bt);
    731   1.1    simonb 	bintime_sub(&bt, &bt2);
    732   1.4    kardel 	bintime_add(&bt2, &timebasebin);
    733   1.4    kardel 	timebasebin = bt;
    734  1.30        ad 	tc_windup();
    735  1.33        ad 	mutex_spin_exit(&timecounter_lock);
    736   1.1    simonb 
    737   1.1    simonb 	if (timestepwarnings) {
    738   1.1    simonb 		bintime2timespec(&bt2, &ts2);
    739  1.45    kardel 		log(LOG_INFO,
    740  1.45    kardel 		    "Time stepped from %lld.%09ld to %lld.%09ld\n",
    741  1.38  christos 		    (long long)ts2.tv_sec, ts2.tv_nsec,
    742  1.38  christos 		    (long long)ts->tv_sec, ts->tv_nsec);
    743   1.1    simonb 	}
    744   1.1    simonb }
    745   1.1    simonb 
    746   1.1    simonb /*
    747   1.1    simonb  * Initialize the next struct timehands in the ring and make
    748   1.1    simonb  * it the active timehands.  Along the way we might switch to a different
    749   1.1    simonb  * timecounter and/or do seconds processing in NTP.  Slightly magic.
    750   1.1    simonb  */
    751   1.1    simonb static void
    752   1.1    simonb tc_windup(void)
    753   1.1    simonb {
    754   1.1    simonb 	struct bintime bt;
    755   1.1    simonb 	struct timehands *th, *tho;
    756   1.1    simonb 	u_int64_t scale;
    757   1.1    simonb 	u_int delta, ncount, ogen;
    758  1.13    kardel 	int i, s_update;
    759   1.1    simonb 	time_t t;
    760   1.1    simonb 
    761  1.51  riastrad 	KASSERT(mutex_owned(&timecounter_lock));
    762  1.30        ad 
    763  1.13    kardel 	s_update = 0;
    764  1.20        ad 
    765   1.1    simonb 	/*
    766   1.1    simonb 	 * Make the next timehands a copy of the current one, but do not
    767   1.1    simonb 	 * overwrite the generation or next pointer.  While we update
    768  1.20        ad 	 * the contents, the generation must be zero.  Ensure global
    769  1.20        ad 	 * visibility of the generation before proceeding.
    770   1.1    simonb 	 */
    771   1.1    simonb 	tho = timehands;
    772   1.1    simonb 	th = tho->th_next;
    773   1.1    simonb 	ogen = th->th_generation;
    774   1.1    simonb 	th->th_generation = 0;
    775  1.27        ad 	membar_producer();
    776   1.1    simonb 	bcopy(tho, th, offsetof(struct timehands, th_generation));
    777   1.1    simonb 
    778   1.1    simonb 	/*
    779   1.1    simonb 	 * Capture a timecounter delta on the current timecounter and if
    780   1.1    simonb 	 * changing timecounters, a counter value from the new timecounter.
    781   1.1    simonb 	 * Update the offset fields accordingly.
    782   1.1    simonb 	 */
    783   1.1    simonb 	delta = tc_delta(th);
    784   1.1    simonb 	if (th->th_counter != timecounter)
    785   1.1    simonb 		ncount = timecounter->tc_get_timecount(timecounter);
    786   1.1    simonb 	else
    787   1.1    simonb 		ncount = 0;
    788   1.1    simonb 	th->th_offset_count += delta;
    789   1.1    simonb 	bintime_addx(&th->th_offset, th->th_scale * delta);
    790   1.1    simonb 
    791   1.1    simonb 	/*
    792   1.1    simonb 	 * Hardware latching timecounters may not generate interrupts on
    793   1.1    simonb 	 * PPS events, so instead we poll them.  There is a finite risk that
    794   1.1    simonb 	 * the hardware might capture a count which is later than the one we
    795   1.1    simonb 	 * got above, and therefore possibly in the next NTP second which might
    796   1.1    simonb 	 * have a different rate than the current NTP second.  It doesn't
    797   1.1    simonb 	 * matter in practice.
    798   1.1    simonb 	 */
    799   1.1    simonb 	if (tho->th_counter->tc_poll_pps)
    800   1.1    simonb 		tho->th_counter->tc_poll_pps(tho->th_counter);
    801   1.1    simonb 
    802   1.1    simonb 	/*
    803   1.1    simonb 	 * Deal with NTP second processing.  The for loop normally
    804   1.1    simonb 	 * iterates at most once, but in extreme situations it might
    805   1.1    simonb 	 * keep NTP sane if timeouts are not run for several seconds.
    806   1.1    simonb 	 * At boot, the time step can be large when the TOD hardware
    807   1.1    simonb 	 * has been read, so on really large steps, we call
    808   1.1    simonb 	 * ntp_update_second only twice.  We need to call it twice in
    809   1.1    simonb 	 * case we missed a leap second.
    810   1.2    kardel 	 * If NTP is not compiled in ntp_update_second still calculates
    811   1.2    kardel 	 * the adjustment resulting from adjtime() calls.
    812   1.1    simonb 	 */
    813   1.1    simonb 	bt = th->th_offset;
    814   1.4    kardel 	bintime_add(&bt, &timebasebin);
    815   1.1    simonb 	i = bt.sec - tho->th_microtime.tv_sec;
    816   1.1    simonb 	if (i > LARGE_STEP)
    817   1.1    simonb 		i = 2;
    818   1.1    simonb 	for (; i > 0; i--) {
    819   1.1    simonb 		t = bt.sec;
    820   1.1    simonb 		ntp_update_second(&th->th_adjustment, &bt.sec);
    821  1.13    kardel 		s_update = 1;
    822   1.1    simonb 		if (bt.sec != t)
    823   1.4    kardel 			timebasebin.sec += bt.sec - t;
    824   1.1    simonb 	}
    825   1.2    kardel 
    826   1.1    simonb 	/* Update the UTC timestamps used by the get*() functions. */
    827   1.1    simonb 	/* XXX shouldn't do this here.  Should force non-`get' versions. */
    828   1.1    simonb 	bintime2timeval(&bt, &th->th_microtime);
    829   1.1    simonb 	bintime2timespec(&bt, &th->th_nanotime);
    830   1.1    simonb 	/* Now is a good time to change timecounters. */
    831   1.1    simonb 	if (th->th_counter != timecounter) {
    832   1.1    simonb 		th->th_counter = timecounter;
    833   1.1    simonb 		th->th_offset_count = ncount;
    834  1.13    kardel 		s_update = 1;
    835   1.1    simonb 	}
    836   1.1    simonb 
    837   1.1    simonb 	/*-
    838   1.1    simonb 	 * Recalculate the scaling factor.  We want the number of 1/2^64
    839   1.1    simonb 	 * fractions of a second per period of the hardware counter, taking
    840   1.1    simonb 	 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
    841   1.1    simonb 	 * processing provides us with.
    842   1.1    simonb 	 *
    843   1.1    simonb 	 * The th_adjustment is nanoseconds per second with 32 bit binary
    844   1.1    simonb 	 * fraction and we want 64 bit binary fraction of second:
    845   1.1    simonb 	 *
    846   1.1    simonb 	 *	 x = a * 2^32 / 10^9 = a * 4.294967296
    847   1.1    simonb 	 *
    848   1.1    simonb 	 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
    849   1.1    simonb 	 * we can only multiply by about 850 without overflowing, but that
    850   1.1    simonb 	 * leaves suitably precise fractions for multiply before divide.
    851   1.1    simonb 	 *
    852   1.1    simonb 	 * Divide before multiply with a fraction of 2199/512 results in a
    853   1.1    simonb 	 * systematic undercompensation of 10PPM of th_adjustment.  On a
    854   1.1    simonb 	 * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
    855   1.1    simonb  	 *
    856   1.1    simonb 	 * We happily sacrifice the lowest of the 64 bits of our result
    857   1.1    simonb 	 * to the goddess of code clarity.
    858   1.1    simonb 	 *
    859   1.1    simonb 	 */
    860  1.13    kardel 	if (s_update) {
    861  1.13    kardel 		scale = (u_int64_t)1 << 63;
    862  1.13    kardel 		scale += (th->th_adjustment / 1024) * 2199;
    863  1.13    kardel 		scale /= th->th_counter->tc_frequency;
    864  1.13    kardel 		th->th_scale = scale * 2;
    865  1.13    kardel 	}
    866   1.1    simonb 	/*
    867   1.1    simonb 	 * Now that the struct timehands is again consistent, set the new
    868  1.20        ad 	 * generation number, making sure to not make it zero.  Ensure
    869  1.20        ad 	 * changes are globally visible before changing.
    870   1.1    simonb 	 */
    871   1.1    simonb 	if (++ogen == 0)
    872   1.1    simonb 		ogen = 1;
    873  1.27        ad 	membar_producer();
    874   1.1    simonb 	th->th_generation = ogen;
    875   1.1    simonb 
    876  1.20        ad 	/*
    877  1.20        ad 	 * Go live with the new struct timehands.  Ensure changes are
    878  1.20        ad 	 * globally visible before changing.
    879  1.20        ad 	 */
    880   1.1    simonb 	time_second = th->th_microtime.tv_sec;
    881   1.1    simonb 	time_uptime = th->th_offset.sec;
    882  1.27        ad 	membar_producer();
    883   1.1    simonb 	timehands = th;
    884  1.24        ad 
    885  1.24        ad 	/*
    886  1.24        ad 	 * Force users of the old timehand to move on.  This is
    887  1.24        ad 	 * necessary for MP systems; we need to ensure that the
    888  1.24        ad 	 * consumers will move away from the old timehand before
    889  1.24        ad 	 * we begin updating it again when we eventually wrap
    890  1.24        ad 	 * around.
    891  1.24        ad 	 */
    892  1.24        ad 	if (++tho->th_generation == 0)
    893  1.24        ad 		tho->th_generation = 1;
    894   1.1    simonb }
    895   1.1    simonb 
    896   1.1    simonb /*
    897   1.1    simonb  * RFC 2783 PPS-API implementation.
    898   1.1    simonb  */
    899   1.1    simonb 
    900   1.1    simonb int
    901  1.19  christos pps_ioctl(u_long cmd, void *data, struct pps_state *pps)
    902   1.1    simonb {
    903   1.1    simonb 	pps_params_t *app;
    904   1.2    kardel 	pps_info_t *pipi;
    905   1.1    simonb #ifdef PPS_SYNC
    906   1.2    kardel 	int *epi;
    907   1.1    simonb #endif
    908   1.1    simonb 
    909  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    910  1.33        ad 
    911  1.45    kardel 	KASSERT(pps != NULL);
    912  1.45    kardel 
    913   1.1    simonb 	switch (cmd) {
    914   1.1    simonb 	case PPS_IOC_CREATE:
    915   1.1    simonb 		return (0);
    916   1.1    simonb 	case PPS_IOC_DESTROY:
    917   1.1    simonb 		return (0);
    918   1.1    simonb 	case PPS_IOC_SETPARAMS:
    919   1.1    simonb 		app = (pps_params_t *)data;
    920   1.1    simonb 		if (app->mode & ~pps->ppscap)
    921   1.1    simonb 			return (EINVAL);
    922   1.1    simonb 		pps->ppsparam = *app;
    923   1.1    simonb 		return (0);
    924   1.1    simonb 	case PPS_IOC_GETPARAMS:
    925   1.1    simonb 		app = (pps_params_t *)data;
    926   1.1    simonb 		*app = pps->ppsparam;
    927   1.1    simonb 		app->api_version = PPS_API_VERS_1;
    928   1.1    simonb 		return (0);
    929   1.1    simonb 	case PPS_IOC_GETCAP:
    930   1.1    simonb 		*(int*)data = pps->ppscap;
    931   1.1    simonb 		return (0);
    932   1.1    simonb 	case PPS_IOC_FETCH:
    933   1.2    kardel 		pipi = (pps_info_t *)data;
    934   1.1    simonb 		pps->ppsinfo.current_mode = pps->ppsparam.mode;
    935   1.2    kardel 		*pipi = pps->ppsinfo;
    936   1.1    simonb 		return (0);
    937   1.1    simonb 	case PPS_IOC_KCBIND:
    938   1.1    simonb #ifdef PPS_SYNC
    939   1.2    kardel 		epi = (int *)data;
    940   1.1    simonb 		/* XXX Only root should be able to do this */
    941   1.2    kardel 		if (*epi & ~pps->ppscap)
    942   1.1    simonb 			return (EINVAL);
    943   1.2    kardel 		pps->kcmode = *epi;
    944   1.1    simonb 		return (0);
    945   1.1    simonb #else
    946   1.1    simonb 		return (EOPNOTSUPP);
    947   1.1    simonb #endif
    948   1.1    simonb 	default:
    949   1.2    kardel 		return (EPASSTHROUGH);
    950   1.1    simonb 	}
    951   1.1    simonb }
    952   1.1    simonb 
    953   1.1    simonb void
    954   1.1    simonb pps_init(struct pps_state *pps)
    955   1.1    simonb {
    956  1.33        ad 
    957  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    958  1.33        ad 
    959   1.1    simonb 	pps->ppscap |= PPS_TSFMT_TSPEC;
    960   1.1    simonb 	if (pps->ppscap & PPS_CAPTUREASSERT)
    961   1.1    simonb 		pps->ppscap |= PPS_OFFSETASSERT;
    962   1.1    simonb 	if (pps->ppscap & PPS_CAPTURECLEAR)
    963   1.1    simonb 		pps->ppscap |= PPS_OFFSETCLEAR;
    964   1.1    simonb }
    965   1.1    simonb 
    966  1.45    kardel /*
    967  1.45    kardel  * capture a timetamp in the pps structure
    968  1.45    kardel  */
    969   1.1    simonb void
    970   1.1    simonb pps_capture(struct pps_state *pps)
    971   1.1    simonb {
    972   1.1    simonb 	struct timehands *th;
    973   1.1    simonb 
    974  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    975  1.33        ad 	KASSERT(pps != NULL);
    976  1.33        ad 
    977   1.1    simonb 	th = timehands;
    978   1.1    simonb 	pps->capgen = th->th_generation;
    979   1.1    simonb 	pps->capth = th;
    980  1.40    kardel 	pps->capcount = (u_int64_t)tc_delta(th) + th->th_offset_count;
    981   1.1    simonb 	if (pps->capgen != th->th_generation)
    982   1.1    simonb 		pps->capgen = 0;
    983   1.1    simonb }
    984   1.1    simonb 
    985  1.45    kardel #ifdef PPS_DEBUG
    986  1.45    kardel int ppsdebug = 0;
    987  1.45    kardel #endif
    988  1.45    kardel 
    989  1.45    kardel /*
    990  1.45    kardel  * process a pps_capture()ed event
    991  1.45    kardel  */
    992   1.1    simonb void
    993   1.1    simonb pps_event(struct pps_state *pps, int event)
    994   1.1    simonb {
    995  1.45    kardel 	pps_ref_event(pps, event, NULL, PPS_REFEVNT_PPS|PPS_REFEVNT_CAPTURE);
    996  1.45    kardel }
    997  1.45    kardel 
    998  1.45    kardel /*
    999  1.45    kardel  * extended pps api /  kernel pll/fll entry point
   1000  1.45    kardel  *
   1001  1.45    kardel  * feed reference time stamps to PPS engine
   1002  1.45    kardel  *
   1003  1.45    kardel  * will simulate a PPS event and feed
   1004  1.45    kardel  * the NTP PLL/FLL if requested.
   1005  1.45    kardel  *
   1006  1.45    kardel  * the ref time stamps should be roughly once
   1007  1.45    kardel  * a second but do not need to be exactly in phase
   1008  1.45    kardel  * with the UTC second but should be close to it.
   1009  1.45    kardel  * this relaxation of requirements allows callout
   1010  1.45    kardel  * driven timestamping mechanisms to feed to pps
   1011  1.45    kardel  * capture/kernel pll logic.
   1012  1.45    kardel  *
   1013  1.45    kardel  * calling pattern is:
   1014  1.45    kardel  *  pps_capture() (for PPS_REFEVNT_{CAPTURE|CAPCUR})
   1015  1.45    kardel  *  read timestamp from reference source
   1016  1.45    kardel  *  pps_ref_event()
   1017  1.45    kardel  *
   1018  1.45    kardel  * supported refmodes:
   1019  1.45    kardel  *  PPS_REFEVNT_CAPTURE
   1020  1.45    kardel  *    use system timestamp of pps_capture()
   1021  1.45    kardel  *  PPS_REFEVNT_CURRENT
   1022  1.45    kardel  *    use system timestamp of this call
   1023  1.45    kardel  *  PPS_REFEVNT_CAPCUR
   1024  1.45    kardel  *    use average of read capture and current system time stamp
   1025  1.45    kardel  *  PPS_REFEVNT_PPS
   1026  1.45    kardel  *    assume timestamp on second mark - ref_ts is ignored
   1027  1.45    kardel  *
   1028  1.45    kardel  */
   1029  1.45    kardel 
   1030  1.45    kardel void
   1031  1.45    kardel pps_ref_event(struct pps_state *pps,
   1032  1.45    kardel 	      int event,
   1033  1.45    kardel 	      struct bintime *ref_ts,
   1034  1.45    kardel 	      int refmode
   1035  1.45    kardel 	)
   1036  1.45    kardel {
   1037  1.45    kardel 	struct bintime bt;	/* current time */
   1038  1.45    kardel 	struct bintime btd;	/* time difference */
   1039  1.45    kardel 	struct bintime bt_ref;	/* reference time */
   1040   1.1    simonb 	struct timespec ts, *tsp, *osp;
   1041  1.45    kardel 	struct timehands *th;
   1042  1.45    kardel 	u_int64_t tcount, acount, dcount, *pcount;
   1043  1.46    martin 	int foff, gen;
   1044  1.46    martin #ifdef PPS_SYNC
   1045  1.46    martin 	int fhard;
   1046  1.46    martin #endif
   1047   1.1    simonb 	pps_seq_t *pseq;
   1048   1.1    simonb 
   1049  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
   1050  1.33        ad 
   1051  1.45    kardel 	KASSERT(pps != NULL);
   1052  1.45    kardel 
   1053  1.45    kardel         /* pick up current time stamp if needed */
   1054  1.45    kardel 	if (refmode & (PPS_REFEVNT_CURRENT|PPS_REFEVNT_CAPCUR)) {
   1055  1.45    kardel 		/* pick up current time stamp */
   1056  1.45    kardel 		th = timehands;
   1057  1.45    kardel 		gen = th->th_generation;
   1058  1.45    kardel 		tcount = (u_int64_t)tc_delta(th) + th->th_offset_count;
   1059  1.45    kardel 		if (gen != th->th_generation)
   1060  1.45    kardel 			gen = 0;
   1061  1.45    kardel 
   1062  1.45    kardel 		/* If the timecounter was wound up underneath us, bail out. */
   1063  1.45    kardel 		if (pps->capgen == 0 ||
   1064  1.45    kardel 		    pps->capgen != pps->capth->th_generation ||
   1065  1.45    kardel 		    gen == 0 ||
   1066  1.45    kardel 		    gen != pps->capgen) {
   1067  1.45    kardel #ifdef PPS_DEBUG
   1068  1.45    kardel 			if (ppsdebug & 0x1) {
   1069  1.45    kardel 				log(LOG_DEBUG,
   1070  1.45    kardel 				    "pps_ref_event(pps=%p, event=%d, ...): DROP (wind-up)\n",
   1071  1.45    kardel 				    pps, event);
   1072  1.45    kardel 			}
   1073  1.45    kardel #endif
   1074  1.45    kardel 			return;
   1075  1.45    kardel 		}
   1076  1.45    kardel 	} else {
   1077  1.45    kardel 		tcount = 0;	/* keep GCC happy */
   1078  1.45    kardel 	}
   1079  1.45    kardel 
   1080  1.45    kardel #ifdef PPS_DEBUG
   1081  1.45    kardel 	if (ppsdebug & 0x1) {
   1082  1.45    kardel 		struct timespec tmsp;
   1083  1.45    kardel 
   1084  1.45    kardel 		if (ref_ts == NULL) {
   1085  1.45    kardel 			tmsp.tv_sec = 0;
   1086  1.45    kardel 			tmsp.tv_nsec = 0;
   1087  1.45    kardel 		} else {
   1088  1.45    kardel 			bintime2timespec(ref_ts, &tmsp);
   1089  1.45    kardel 		}
   1090  1.45    kardel 
   1091  1.45    kardel 		log(LOG_DEBUG,
   1092  1.45    kardel 		    "pps_ref_event(pps=%p, event=%d, ref_ts=%"PRIi64
   1093  1.45    kardel 		    ".%09"PRIi32", refmode=0x%1x)\n",
   1094  1.45    kardel 		    pps, event, tmsp.tv_sec, (int32_t)tmsp.tv_nsec, refmode);
   1095  1.45    kardel 	}
   1096  1.45    kardel #endif
   1097   1.1    simonb 
   1098  1.45    kardel 	/* setup correct event references */
   1099   1.1    simonb 	if (event == PPS_CAPTUREASSERT) {
   1100   1.1    simonb 		tsp = &pps->ppsinfo.assert_timestamp;
   1101   1.1    simonb 		osp = &pps->ppsparam.assert_offset;
   1102   1.1    simonb 		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
   1103  1.46    martin #ifdef PPS_SYNC
   1104   1.1    simonb 		fhard = pps->kcmode & PPS_CAPTUREASSERT;
   1105  1.46    martin #endif
   1106   1.1    simonb 		pcount = &pps->ppscount[0];
   1107   1.1    simonb 		pseq = &pps->ppsinfo.assert_sequence;
   1108   1.1    simonb 	} else {
   1109   1.1    simonb 		tsp = &pps->ppsinfo.clear_timestamp;
   1110   1.1    simonb 		osp = &pps->ppsparam.clear_offset;
   1111   1.1    simonb 		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
   1112  1.46    martin #ifdef PPS_SYNC
   1113   1.1    simonb 		fhard = pps->kcmode & PPS_CAPTURECLEAR;
   1114  1.46    martin #endif
   1115   1.1    simonb 		pcount = &pps->ppscount[1];
   1116   1.1    simonb 		pseq = &pps->ppsinfo.clear_sequence;
   1117   1.1    simonb 	}
   1118   1.1    simonb 
   1119  1.45    kardel 	/* determine system time stamp according to refmode */
   1120  1.45    kardel 	dcount = 0;		/* keep GCC happy */
   1121  1.45    kardel 	switch (refmode & PPS_REFEVNT_RMASK) {
   1122  1.45    kardel 	case PPS_REFEVNT_CAPTURE:
   1123  1.45    kardel 		acount = pps->capcount;	/* use capture timestamp */
   1124  1.45    kardel 		break;
   1125  1.45    kardel 
   1126  1.45    kardel 	case PPS_REFEVNT_CURRENT:
   1127  1.45    kardel 		acount = tcount; /* use current timestamp */
   1128  1.45    kardel 		break;
   1129  1.45    kardel 
   1130  1.45    kardel 	case PPS_REFEVNT_CAPCUR:
   1131  1.45    kardel 		/*
   1132  1.45    kardel 		 * calculate counter value between pps_capture() and
   1133  1.45    kardel 		 * pps_ref_event()
   1134  1.45    kardel 		 */
   1135  1.45    kardel 		dcount = tcount - pps->capcount;
   1136  1.45    kardel 		acount = (dcount / 2) + pps->capcount;
   1137  1.45    kardel 		break;
   1138  1.45    kardel 
   1139  1.45    kardel 	default:		/* ignore call error silently */
   1140  1.45    kardel 		return;
   1141  1.45    kardel 	}
   1142  1.45    kardel 
   1143   1.1    simonb 	/*
   1144   1.1    simonb 	 * If the timecounter changed, we cannot compare the count values, so
   1145   1.1    simonb 	 * we have to drop the rest of the PPS-stuff until the next event.
   1146   1.1    simonb 	 */
   1147   1.1    simonb 	if (pps->ppstc != pps->capth->th_counter) {
   1148   1.1    simonb 		pps->ppstc = pps->capth->th_counter;
   1149  1.45    kardel 		pps->capcount = acount;
   1150  1.45    kardel 		*pcount = acount;
   1151  1.45    kardel 		pps->ppscount[2] = acount;
   1152  1.45    kardel #ifdef PPS_DEBUG
   1153  1.45    kardel 		if (ppsdebug & 0x1) {
   1154  1.45    kardel 			log(LOG_DEBUG,
   1155  1.45    kardel 			    "pps_ref_event(pps=%p, event=%d, ...): DROP (time-counter change)\n",
   1156  1.45    kardel 			    pps, event);
   1157  1.45    kardel 		}
   1158  1.45    kardel #endif
   1159   1.1    simonb 		return;
   1160   1.1    simonb 	}
   1161   1.1    simonb 
   1162  1.45    kardel 	pps->capcount = acount;
   1163  1.45    kardel 
   1164  1.45    kardel 	/* Convert the count to a bintime. */
   1165   1.1    simonb 	bt = pps->capth->th_offset;
   1166  1.45    kardel 	bintime_addx(&bt, pps->capth->th_scale * (acount - pps->capth->th_offset_count));
   1167   1.4    kardel 	bintime_add(&bt, &timebasebin);
   1168  1.45    kardel 
   1169  1.45    kardel 	if ((refmode & PPS_REFEVNT_PPS) == 0) {
   1170  1.45    kardel 		/* determine difference to reference time stamp */
   1171  1.45    kardel 		bt_ref = *ref_ts;
   1172  1.45    kardel 
   1173  1.45    kardel 		btd = bt;
   1174  1.45    kardel 		bintime_sub(&btd, &bt_ref);
   1175  1.45    kardel 
   1176  1.45    kardel 		/*
   1177  1.45    kardel 		 * simulate a PPS timestamp by dropping the fraction
   1178  1.45    kardel 		 * and applying the offset
   1179  1.45    kardel 		 */
   1180  1.45    kardel 		if (bt.frac >= (uint64_t)1<<63)	/* skip to nearest second */
   1181  1.45    kardel 			bt.sec++;
   1182  1.45    kardel 		bt.frac = 0;
   1183  1.45    kardel 		bintime_add(&bt, &btd);
   1184  1.45    kardel 	} else {
   1185  1.45    kardel 		/*
   1186  1.45    kardel 		 * create ref_ts from current time -
   1187  1.45    kardel 		 * we are supposed to be called on
   1188  1.45    kardel 		 * the second mark
   1189  1.45    kardel 		 */
   1190  1.45    kardel 		bt_ref = bt;
   1191  1.45    kardel 		if (bt_ref.frac >= (uint64_t)1<<63)	/* skip to nearest second */
   1192  1.45    kardel 			bt_ref.sec++;
   1193  1.45    kardel 		bt_ref.frac = 0;
   1194  1.45    kardel 	}
   1195  1.45    kardel 
   1196  1.45    kardel 	/* convert bintime to timestamp */
   1197   1.1    simonb 	bintime2timespec(&bt, &ts);
   1198   1.1    simonb 
   1199   1.1    simonb 	/* If the timecounter was wound up underneath us, bail out. */
   1200   1.1    simonb 	if (pps->capgen != pps->capth->th_generation)
   1201   1.1    simonb 		return;
   1202   1.1    simonb 
   1203  1.45    kardel 	/* store time stamp */
   1204   1.1    simonb 	*pcount = pps->capcount;
   1205   1.1    simonb 	(*pseq)++;
   1206   1.1    simonb 	*tsp = ts;
   1207   1.1    simonb 
   1208  1.45    kardel 	/* add offset correction */
   1209   1.1    simonb 	if (foff) {
   1210   1.2    kardel 		timespecadd(tsp, osp, tsp);
   1211   1.1    simonb 		if (tsp->tv_nsec < 0) {
   1212   1.1    simonb 			tsp->tv_nsec += 1000000000;
   1213   1.1    simonb 			tsp->tv_sec -= 1;
   1214   1.1    simonb 		}
   1215   1.1    simonb 	}
   1216  1.45    kardel 
   1217  1.45    kardel #ifdef PPS_DEBUG
   1218  1.45    kardel 	if (ppsdebug & 0x2) {
   1219  1.45    kardel 		struct timespec ts2;
   1220  1.45    kardel 		struct timespec ts3;
   1221  1.45    kardel 
   1222  1.45    kardel 		bintime2timespec(&bt_ref, &ts2);
   1223  1.45    kardel 
   1224  1.45    kardel 		bt.sec = 0;
   1225  1.45    kardel 		bt.frac = 0;
   1226  1.45    kardel 
   1227  1.45    kardel 		if (refmode & PPS_REFEVNT_CAPCUR) {
   1228  1.45    kardel 			    bintime_addx(&bt, pps->capth->th_scale * dcount);
   1229  1.45    kardel 		}
   1230  1.45    kardel 		bintime2timespec(&bt, &ts3);
   1231  1.45    kardel 
   1232  1.45    kardel 		log(LOG_DEBUG, "ref_ts=%"PRIi64".%09"PRIi32
   1233  1.45    kardel 		    ", ts=%"PRIi64".%09"PRIi32", read latency=%"PRIi64" ns\n",
   1234  1.45    kardel 		    ts2.tv_sec, (int32_t)ts2.tv_nsec,
   1235  1.45    kardel 		    tsp->tv_sec, (int32_t)tsp->tv_nsec,
   1236  1.45    kardel 		    timespec2ns(&ts3));
   1237  1.45    kardel 	}
   1238  1.45    kardel #endif
   1239  1.45    kardel 
   1240   1.1    simonb #ifdef PPS_SYNC
   1241   1.1    simonb 	if (fhard) {
   1242  1.45    kardel 		uint64_t scale;
   1243  1.45    kardel 		uint64_t div;
   1244   1.1    simonb 
   1245   1.1    simonb 		/*
   1246   1.1    simonb 		 * Feed the NTP PLL/FLL.
   1247   1.1    simonb 		 * The FLL wants to know how many (hardware) nanoseconds
   1248  1.45    kardel 		 * elapsed since the previous event (mod 1 second) thus
   1249  1.45    kardel 		 * we are actually looking at the frequency difference scaled
   1250  1.45    kardel 		 * in nsec.
   1251  1.45    kardel 		 * As the counter time stamps are not truly at 1Hz
   1252  1.45    kardel 		 * we need to scale the count by the elapsed
   1253  1.45    kardel 		 * reference time.
   1254  1.45    kardel 		 * valid sampling interval: [0.5..2[ sec
   1255   1.1    simonb 		 */
   1256  1.45    kardel 
   1257  1.45    kardel 		/* calculate elapsed raw count */
   1258   1.1    simonb 		tcount = pps->capcount - pps->ppscount[2];
   1259   1.1    simonb 		pps->ppscount[2] = pps->capcount;
   1260   1.1    simonb 		tcount &= pps->capth->th_counter->tc_counter_mask;
   1261  1.45    kardel 
   1262  1.45    kardel 		/* calculate elapsed ref time */
   1263  1.45    kardel 		btd = bt_ref;
   1264  1.45    kardel 		bintime_sub(&btd, &pps->ref_time);
   1265  1.45    kardel 		pps->ref_time = bt_ref;
   1266  1.45    kardel 
   1267  1.45    kardel 		/* check that we stay below 2 sec */
   1268  1.45    kardel 		if (btd.sec < 0 || btd.sec > 1)
   1269  1.45    kardel 			return;
   1270  1.45    kardel 
   1271  1.45    kardel 		/* we want at least 0.5 sec between samples */
   1272  1.45    kardel 		if (btd.sec == 0 && btd.frac < (uint64_t)1<<63)
   1273  1.45    kardel 			return;
   1274  1.45    kardel 
   1275  1.45    kardel 		/*
   1276  1.45    kardel 		 * calculate cycles per period by multiplying
   1277  1.45    kardel 		 * the frequency with the elapsed period
   1278  1.45    kardel 		 * we pick a fraction of 30 bits
   1279  1.45    kardel 		 * ~1ns resolution for elapsed time
   1280  1.45    kardel 		 */
   1281  1.45    kardel 		div   = (uint64_t)btd.sec << 30;
   1282  1.45    kardel 		div  |= (btd.frac >> 34) & (((uint64_t)1 << 30) - 1);
   1283  1.45    kardel 		div  *= pps->capth->th_counter->tc_frequency;
   1284  1.45    kardel 		div >>= 30;
   1285  1.45    kardel 
   1286  1.45    kardel 		if (div == 0)	/* safeguard */
   1287  1.45    kardel 			return;
   1288  1.45    kardel 
   1289  1.45    kardel 		scale = (uint64_t)1 << 63;
   1290  1.45    kardel 		scale /= div;
   1291   1.1    simonb 		scale *= 2;
   1292  1.45    kardel 
   1293   1.1    simonb 		bt.sec = 0;
   1294   1.1    simonb 		bt.frac = 0;
   1295   1.1    simonb 		bintime_addx(&bt, scale * tcount);
   1296   1.1    simonb 		bintime2timespec(&bt, &ts);
   1297  1.45    kardel 
   1298  1.45    kardel #ifdef PPS_DEBUG
   1299  1.45    kardel 		if (ppsdebug & 0x4) {
   1300  1.45    kardel 			struct timespec ts2;
   1301  1.45    kardel 			int64_t df;
   1302  1.45    kardel 
   1303  1.45    kardel 			bintime2timespec(&bt_ref, &ts2);
   1304  1.45    kardel 			df = timespec2ns(&ts);
   1305  1.45    kardel 			if (df > 500000000)
   1306  1.45    kardel 				df -= 1000000000;
   1307  1.45    kardel 			log(LOG_DEBUG, "hardpps: ref_ts=%"PRIi64
   1308  1.45    kardel 			    ".%09"PRIi32", ts=%"PRIi64".%09"PRIi32
   1309  1.45    kardel 			    ", freqdiff=%"PRIi64" ns/s\n",
   1310  1.45    kardel 			    ts2.tv_sec, (int32_t)ts2.tv_nsec,
   1311  1.45    kardel 			    tsp->tv_sec, (int32_t)tsp->tv_nsec,
   1312  1.45    kardel 			    df);
   1313  1.45    kardel 		}
   1314  1.45    kardel #endif
   1315  1.45    kardel 
   1316  1.45    kardel 		hardpps(tsp, timespec2ns(&ts));
   1317   1.1    simonb 	}
   1318   1.1    simonb #endif
   1319   1.1    simonb }
   1320   1.1    simonb 
   1321   1.1    simonb /*
   1322   1.1    simonb  * Timecounters need to be updated every so often to prevent the hardware
   1323   1.1    simonb  * counter from overflowing.  Updating also recalculates the cached values
   1324   1.1    simonb  * used by the get*() family of functions, so their precision depends on
   1325   1.1    simonb  * the update frequency.
   1326   1.1    simonb  */
   1327   1.1    simonb 
   1328   1.1    simonb static int tc_tick;
   1329   1.1    simonb 
   1330   1.1    simonb void
   1331   1.1    simonb tc_ticktock(void)
   1332   1.1    simonb {
   1333   1.1    simonb 	static int count;
   1334   1.1    simonb 
   1335   1.1    simonb 	if (++count < tc_tick)
   1336   1.1    simonb 		return;
   1337   1.1    simonb 	count = 0;
   1338  1.51  riastrad 	mutex_spin_enter(&timecounter_lock);
   1339  1.56       rin 	if (__predict_false(timecounter_bad != 0)) {
   1340  1.35        ad 		/* An existing timecounter has gone bad, pick a new one. */
   1341  1.35        ad 		(void)atomic_swap_uint(&timecounter_bad, 0);
   1342  1.35        ad 		if (timecounter->tc_quality < 0) {
   1343  1.35        ad 			tc_pick();
   1344  1.35        ad 		}
   1345  1.35        ad 	}
   1346   1.1    simonb 	tc_windup();
   1347  1.51  riastrad 	mutex_spin_exit(&timecounter_lock);
   1348   1.1    simonb }
   1349   1.1    simonb 
   1350   1.2    kardel void
   1351   1.2    kardel inittimecounter(void)
   1352   1.1    simonb {
   1353   1.1    simonb 	u_int p;
   1354   1.1    simonb 
   1355  1.37    kardel 	mutex_init(&timecounter_lock, MUTEX_DEFAULT, IPL_HIGH);
   1356  1.30        ad 
   1357   1.1    simonb 	/*
   1358   1.1    simonb 	 * Set the initial timeout to
   1359   1.1    simonb 	 * max(1, <approx. number of hardclock ticks in a millisecond>).
   1360   1.1    simonb 	 * People should probably not use the sysctl to set the timeout
   1361  1.53   msaitoh 	 * to smaller than its initial value, since that value is the
   1362   1.1    simonb 	 * smallest reasonable one.  If they want better timestamps they
   1363   1.1    simonb 	 * should use the non-"get"* functions.
   1364   1.1    simonb 	 */
   1365   1.1    simonb 	if (hz > 1000)
   1366   1.1    simonb 		tc_tick = (hz + 500) / 1000;
   1367   1.1    simonb 	else
   1368   1.1    simonb 		tc_tick = 1;
   1369   1.1    simonb 	p = (tc_tick * 1000000) / hz;
   1370  1.18        ad 	aprint_verbose("timecounter: Timecounters tick every %d.%03u msec\n",
   1371  1.18        ad 	    p / 1000, p % 1000);
   1372   1.1    simonb 
   1373   1.1    simonb 	/* warm up new timecounter (again) and get rolling. */
   1374   1.1    simonb 	(void)timecounter->tc_get_timecount(timecounter);
   1375   1.1    simonb 	(void)timecounter->tc_get_timecount(timecounter);
   1376   1.1    simonb }
   1377