Home | History | Annotate | Line # | Download | only in kern
kern_tc.c revision 1.40
      1  1.40    kardel /* $NetBSD: kern_tc.c,v 1.40 2009/06/14 13:16:32 kardel 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.40    kardel __KERNEL_RCSID(0, "$NetBSD: kern_tc.c,v 1.40 2009/06/14 13:16:32 kardel Exp $");
     44   1.1    simonb 
     45   1.1    simonb #include "opt_ntp.h"
     46   1.1    simonb 
     47   1.1    simonb #include <sys/param.h>
     48   1.1    simonb #include <sys/kernel.h>
     49   1.2    kardel #include <sys/reboot.h>	/* XXX just to get AB_VERBOSE */
     50   1.1    simonb #include <sys/sysctl.h>
     51   1.1    simonb #include <sys/syslog.h>
     52   1.1    simonb #include <sys/systm.h>
     53   1.1    simonb #include <sys/timepps.h>
     54   1.1    simonb #include <sys/timetc.h>
     55   1.1    simonb #include <sys/timex.h>
     56   1.2    kardel #include <sys/evcnt.h>
     57   1.2    kardel #include <sys/kauth.h>
     58  1.25        ad #include <sys/mutex.h>
     59  1.27        ad #include <sys/atomic.h>
     60  1.39        ad #include <sys/xcall.h>
     61   1.2    kardel 
     62   1.2    kardel /*
     63   1.1    simonb  * A large step happens on boot.  This constant detects such steps.
     64   1.1    simonb  * It is relatively small so that ntp_update_second gets called enough
     65   1.1    simonb  * in the typical 'missed a couple of seconds' case, but doesn't loop
     66   1.1    simonb  * forever when the time step is large.
     67   1.1    simonb  */
     68   1.1    simonb #define LARGE_STEP	200
     69   1.1    simonb 
     70   1.1    simonb /*
     71   1.1    simonb  * Implement a dummy timecounter which we can use until we get a real one
     72   1.1    simonb  * in the air.  This allows the console and other early stuff to use
     73   1.1    simonb  * time services.
     74   1.1    simonb  */
     75   1.1    simonb 
     76   1.1    simonb static u_int
     77  1.16      yamt dummy_get_timecount(struct timecounter *tc)
     78   1.1    simonb {
     79   1.1    simonb 	static u_int now;
     80   1.1    simonb 
     81   1.1    simonb 	return (++now);
     82   1.1    simonb }
     83   1.1    simonb 
     84   1.1    simonb static struct timecounter dummy_timecounter = {
     85   1.8  christos 	dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000, NULL, NULL,
     86   1.1    simonb };
     87   1.1    simonb 
     88   1.1    simonb struct timehands {
     89   1.1    simonb 	/* These fields must be initialized by the driver. */
     90  1.40    kardel 	struct timecounter	*th_counter;     /* active timecounter */
     91  1.40    kardel 	int64_t			th_adjustment;   /* frequency adjustment */
     92  1.40    kardel 						 /* (NTP/adjtime) */
     93  1.40    kardel 	u_int64_t		th_scale;        /* scale factor (counter */
     94  1.40    kardel 						 /* tick->time) */
     95  1.40    kardel 	u_int64_t 		th_offset_count; /* offset at last time */
     96  1.40    kardel 						 /* update (tc_windup()) */
     97  1.40    kardel 	struct bintime		th_offset;       /* bin (up)time at windup */
     98  1.40    kardel 	struct timeval		th_microtime;    /* cached microtime */
     99  1.40    kardel 	struct timespec		th_nanotime;     /* cached nanotime */
    100   1.1    simonb 	/* Fields not to be copied in tc_windup start with th_generation. */
    101  1.40    kardel 	volatile u_int		th_generation;   /* current genration */
    102  1.40    kardel 	struct timehands	*th_next;        /* next timehand */
    103   1.1    simonb };
    104   1.1    simonb 
    105   1.1    simonb static struct timehands th0;
    106  1.10  christos static struct timehands th9 = { .th_next = &th0, };
    107  1.10  christos static struct timehands th8 = { .th_next = &th9, };
    108  1.10  christos static struct timehands th7 = { .th_next = &th8, };
    109  1.10  christos static struct timehands th6 = { .th_next = &th7, };
    110  1.10  christos static struct timehands th5 = { .th_next = &th6, };
    111  1.10  christos static struct timehands th4 = { .th_next = &th5, };
    112  1.10  christos static struct timehands th3 = { .th_next = &th4, };
    113  1.10  christos static struct timehands th2 = { .th_next = &th3, };
    114  1.10  christos static struct timehands th1 = { .th_next = &th2, };
    115   1.1    simonb static struct timehands th0 = {
    116  1.10  christos 	.th_counter = &dummy_timecounter,
    117  1.10  christos 	.th_scale = (uint64_t)-1 / 1000000,
    118  1.10  christos 	.th_offset = { .sec = 1, .frac = 0 },
    119  1.10  christos 	.th_generation = 1,
    120  1.10  christos 	.th_next = &th1,
    121   1.1    simonb };
    122   1.1    simonb 
    123   1.1    simonb static struct timehands *volatile timehands = &th0;
    124   1.1    simonb struct timecounter *timecounter = &dummy_timecounter;
    125   1.1    simonb static struct timecounter *timecounters = &dummy_timecounter;
    126   1.1    simonb 
    127   1.1    simonb time_t time_second = 1;
    128   1.1    simonb time_t time_uptime = 1;
    129   1.1    simonb 
    130   1.4    kardel static struct bintime timebasebin;
    131   1.1    simonb 
    132   1.1    simonb static int timestepwarnings;
    133   1.2    kardel 
    134  1.33        ad kmutex_t timecounter_lock;
    135  1.35        ad static u_int timecounter_mods;
    136  1.39        ad static volatile int timecounter_removals = 1;
    137  1.35        ad static u_int timecounter_bad;
    138  1.25        ad 
    139   1.2    kardel #ifdef __FreeBSD__
    140   1.1    simonb SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
    141   1.1    simonb     &timestepwarnings, 0, "");
    142   1.2    kardel #endif /* __FreeBSD__ */
    143   1.2    kardel 
    144   1.2    kardel /*
    145  1.28      yamt  * sysctl helper routine for kern.timercounter.hardware
    146   1.2    kardel  */
    147   1.2    kardel static int
    148   1.2    kardel sysctl_kern_timecounter_hardware(SYSCTLFN_ARGS)
    149   1.2    kardel {
    150   1.2    kardel 	struct sysctlnode node;
    151   1.2    kardel 	int error;
    152   1.2    kardel 	char newname[MAX_TCNAMELEN];
    153   1.2    kardel 	struct timecounter *newtc, *tc;
    154   1.2    kardel 
    155   1.2    kardel 	tc = timecounter;
    156   1.2    kardel 
    157   1.2    kardel 	strlcpy(newname, tc->tc_name, sizeof(newname));
    158   1.2    kardel 
    159   1.2    kardel 	node = *rnode;
    160   1.2    kardel 	node.sysctl_data = newname;
    161   1.2    kardel 	node.sysctl_size = sizeof(newname);
    162   1.2    kardel 
    163   1.2    kardel 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    164   1.2    kardel 
    165   1.2    kardel 	if (error ||
    166   1.2    kardel 	    newp == NULL ||
    167   1.2    kardel 	    strncmp(newname, tc->tc_name, sizeof(newname)) == 0)
    168   1.2    kardel 		return error;
    169   1.1    simonb 
    170  1.26      elad 	if (l != NULL && (error = kauth_authorize_system(l->l_cred,
    171  1.26      elad 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_TIMECOUNTERS, newname,
    172  1.26      elad 	    NULL, NULL)) != 0)
    173   1.2    kardel 		return (error);
    174   1.2    kardel 
    175  1.22        ad 	if (!cold)
    176  1.35        ad 		mutex_spin_enter(&timecounter_lock);
    177  1.23        ad 	error = EINVAL;
    178   1.2    kardel 	for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
    179   1.2    kardel 		if (strcmp(newname, newtc->tc_name) != 0)
    180   1.2    kardel 			continue;
    181   1.2    kardel 		/* Warm up new timecounter. */
    182   1.2    kardel 		(void)newtc->tc_get_timecount(newtc);
    183   1.2    kardel 		(void)newtc->tc_get_timecount(newtc);
    184   1.2    kardel 		timecounter = newtc;
    185  1.22        ad 		error = 0;
    186  1.23        ad 		break;
    187  1.23        ad 	}
    188  1.22        ad 	if (!cold)
    189  1.35        ad 		mutex_spin_exit(&timecounter_lock);
    190  1.22        ad 	return error;
    191   1.2    kardel }
    192   1.2    kardel 
    193   1.2    kardel static int
    194   1.2    kardel sysctl_kern_timecounter_choice(SYSCTLFN_ARGS)
    195   1.2    kardel {
    196   1.9    kardel 	char buf[MAX_TCNAMELEN+48];
    197  1.35        ad 	char *where;
    198   1.2    kardel 	const char *spc;
    199   1.2    kardel 	struct timecounter *tc;
    200   1.2    kardel 	size_t needed, left, slen;
    201  1.35        ad 	int error, mods;
    202   1.2    kardel 
    203   1.2    kardel 	if (newp != NULL)
    204   1.2    kardel 		return (EPERM);
    205   1.2    kardel 	if (namelen != 0)
    206   1.2    kardel 		return (EINVAL);
    207   1.2    kardel 
    208  1.35        ad 	mutex_spin_enter(&timecounter_lock);
    209  1.35        ad  retry:
    210   1.2    kardel 	spc = "";
    211   1.2    kardel 	error = 0;
    212   1.2    kardel 	needed = 0;
    213   1.2    kardel 	left = *oldlenp;
    214  1.35        ad 	where = oldp;
    215   1.2    kardel 	for (tc = timecounters; error == 0 && tc != NULL; tc = tc->tc_next) {
    216   1.2    kardel 		if (where == NULL) {
    217   1.2    kardel 			needed += sizeof(buf);  /* be conservative */
    218   1.2    kardel 		} else {
    219   1.2    kardel 			slen = snprintf(buf, sizeof(buf), "%s%s(q=%d, f=%" PRId64
    220   1.2    kardel 					" Hz)", spc, tc->tc_name, tc->tc_quality,
    221   1.2    kardel 					tc->tc_frequency);
    222   1.2    kardel 			if (left < slen + 1)
    223   1.2    kardel 				break;
    224  1.35        ad 		 	mods = timecounter_mods;
    225  1.35        ad 			mutex_spin_exit(&timecounter_lock);
    226   1.2    kardel 			error = copyout(buf, where, slen + 1);
    227  1.35        ad 			mutex_spin_enter(&timecounter_lock);
    228  1.35        ad 			if (mods != timecounter_mods) {
    229  1.35        ad 				goto retry;
    230  1.35        ad 			}
    231   1.2    kardel 			spc = " ";
    232   1.2    kardel 			where += slen;
    233   1.2    kardel 			needed += slen;
    234   1.2    kardel 			left -= slen;
    235   1.2    kardel 		}
    236   1.2    kardel 	}
    237  1.35        ad 	mutex_spin_exit(&timecounter_lock);
    238   1.2    kardel 
    239   1.2    kardel 	*oldlenp = needed;
    240   1.2    kardel 	return (error);
    241   1.2    kardel }
    242   1.2    kardel 
    243   1.2    kardel SYSCTL_SETUP(sysctl_timecounter_setup, "sysctl timecounter setup")
    244   1.2    kardel {
    245   1.2    kardel 	const struct sysctlnode *node;
    246   1.2    kardel 
    247   1.2    kardel 	sysctl_createv(clog, 0, NULL, &node,
    248   1.2    kardel 		       CTLFLAG_PERMANENT,
    249   1.2    kardel 		       CTLTYPE_NODE, "timecounter",
    250   1.2    kardel 		       SYSCTL_DESCR("time counter information"),
    251   1.2    kardel 		       NULL, 0, NULL, 0,
    252   1.2    kardel 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    253   1.2    kardel 
    254   1.2    kardel 	if (node != NULL) {
    255   1.2    kardel 		sysctl_createv(clog, 0, NULL, NULL,
    256   1.2    kardel 			       CTLFLAG_PERMANENT,
    257   1.2    kardel 			       CTLTYPE_STRING, "choice",
    258   1.2    kardel 			       SYSCTL_DESCR("available counters"),
    259   1.2    kardel 			       sysctl_kern_timecounter_choice, 0, NULL, 0,
    260   1.2    kardel 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    261   1.2    kardel 
    262   1.2    kardel 		sysctl_createv(clog, 0, NULL, NULL,
    263   1.2    kardel 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    264   1.2    kardel 			       CTLTYPE_STRING, "hardware",
    265   1.2    kardel 			       SYSCTL_DESCR("currently active time counter"),
    266   1.2    kardel 			       sysctl_kern_timecounter_hardware, 0, NULL, MAX_TCNAMELEN,
    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_INT, "timestepwarnings",
    272   1.2    kardel 			       SYSCTL_DESCR("log time steps"),
    273   1.2    kardel 			       NULL, 0, &timestepwarnings, 0,
    274   1.2    kardel 			       CTL_KERN, node->sysctl_num, CTL_CREATE, CTL_EOL);
    275   1.2    kardel 	}
    276   1.2    kardel }
    277   1.2    kardel 
    278  1.32        ad #ifdef TC_COUNTERS
    279   1.2    kardel #define	TC_STATS(name)							\
    280   1.2    kardel static struct evcnt n##name =						\
    281   1.2    kardel     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "timecounter", #name);	\
    282   1.2    kardel EVCNT_ATTACH_STATIC(n##name)
    283   1.2    kardel TC_STATS(binuptime);    TC_STATS(nanouptime);    TC_STATS(microuptime);
    284   1.2    kardel TC_STATS(bintime);      TC_STATS(nanotime);      TC_STATS(microtime);
    285   1.2    kardel TC_STATS(getbinuptime); TC_STATS(getnanouptime); TC_STATS(getmicrouptime);
    286   1.2    kardel TC_STATS(getbintime);   TC_STATS(getnanotime);   TC_STATS(getmicrotime);
    287   1.2    kardel TC_STATS(setclock);
    288  1.32        ad #define	TC_COUNT(var)	var.ev_count++
    289   1.1    simonb #undef TC_STATS
    290  1.32        ad #else
    291  1.32        ad #define	TC_COUNT(var)	/* nothing */
    292  1.32        ad #endif	/* TC_COUNTERS */
    293   1.1    simonb 
    294   1.1    simonb static void tc_windup(void);
    295   1.1    simonb 
    296   1.1    simonb /*
    297   1.1    simonb  * Return the difference between the timehands' counter value now and what
    298   1.1    simonb  * was when we copied it to the timehands' offset_count.
    299   1.1    simonb  */
    300   1.1    simonb static __inline u_int
    301   1.1    simonb tc_delta(struct timehands *th)
    302   1.1    simonb {
    303   1.1    simonb 	struct timecounter *tc;
    304   1.1    simonb 
    305   1.1    simonb 	tc = th->th_counter;
    306   1.2    kardel 	return ((tc->tc_get_timecount(tc) -
    307   1.2    kardel 		 th->th_offset_count) & tc->tc_counter_mask);
    308   1.1    simonb }
    309   1.1    simonb 
    310   1.1    simonb /*
    311   1.1    simonb  * Functions for reading the time.  We have to loop until we are sure that
    312   1.1    simonb  * the timehands that we operated on was not updated under our feet.  See
    313  1.21    simonb  * the comment in <sys/timevar.h> for a description of these 12 functions.
    314   1.1    simonb  */
    315   1.1    simonb 
    316   1.1    simonb void
    317   1.1    simonb binuptime(struct bintime *bt)
    318   1.1    simonb {
    319   1.1    simonb 	struct timehands *th;
    320  1.39        ad 	lwp_t *l;
    321  1.39        ad 	u_int lgen, gen;
    322   1.1    simonb 
    323  1.32        ad 	TC_COUNT(nbinuptime);
    324  1.39        ad 
    325  1.39        ad 	/*
    326  1.39        ad 	 * Provide exclusion against tc_detach().
    327  1.39        ad 	 *
    328  1.39        ad 	 * We record the number of timecounter removals before accessing
    329  1.39        ad 	 * timecounter state.  Note that the LWP can be using multiple
    330  1.39        ad 	 * "generations" at once, due to interrupts (interrupted while in
    331  1.39        ad 	 * this function).  Hardware interrupts will borrow the interrupted
    332  1.39        ad 	 * LWP's l_tcgen value for this purpose, and can themselves be
    333  1.39        ad 	 * interrupted by higher priority interrupts.  In this case we need
    334  1.39        ad 	 * to ensure that the oldest generation in use is recorded.
    335  1.39        ad 	 *
    336  1.39        ad 	 * splsched() is too expensive to use, so we take care to structure
    337  1.39        ad 	 * this code in such a way that it is not required.  Likewise, we
    338  1.39        ad 	 * do not disable preemption.
    339  1.39        ad 	 *
    340  1.39        ad 	 * Memory barriers are also too expensive to use for such a
    341  1.39        ad 	 * performance critical function.  The good news is that we do not
    342  1.39        ad 	 * need memory barriers for this type of exclusion, as the thread
    343  1.39        ad 	 * updating timecounter_removals will issue a broadcast cross call
    344  1.39        ad 	 * before inspecting our l_tcgen value (this elides memory ordering
    345  1.39        ad 	 * issues).
    346  1.39        ad 	 */
    347  1.39        ad 	l = curlwp;
    348  1.39        ad 	lgen = l->l_tcgen;
    349  1.39        ad 	if (__predict_true(lgen == 0)) {
    350  1.39        ad 		l->l_tcgen = timecounter_removals;
    351  1.39        ad 	}
    352  1.39        ad 	__insn_barrier();
    353  1.39        ad 
    354   1.1    simonb 	do {
    355   1.1    simonb 		th = timehands;
    356   1.1    simonb 		gen = th->th_generation;
    357   1.1    simonb 		*bt = th->th_offset;
    358   1.1    simonb 		bintime_addx(bt, th->th_scale * tc_delta(th));
    359   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    360  1.39        ad 
    361  1.39        ad 	__insn_barrier();
    362  1.39        ad 	l->l_tcgen = lgen;
    363   1.1    simonb }
    364   1.1    simonb 
    365   1.1    simonb void
    366   1.1    simonb nanouptime(struct timespec *tsp)
    367   1.1    simonb {
    368   1.1    simonb 	struct bintime bt;
    369   1.1    simonb 
    370  1.32        ad 	TC_COUNT(nnanouptime);
    371   1.1    simonb 	binuptime(&bt);
    372   1.1    simonb 	bintime2timespec(&bt, tsp);
    373   1.1    simonb }
    374   1.1    simonb 
    375   1.1    simonb void
    376   1.1    simonb microuptime(struct timeval *tvp)
    377   1.1    simonb {
    378   1.1    simonb 	struct bintime bt;
    379   1.1    simonb 
    380  1.32        ad 	TC_COUNT(nmicrouptime);
    381   1.1    simonb 	binuptime(&bt);
    382   1.1    simonb 	bintime2timeval(&bt, tvp);
    383   1.1    simonb }
    384   1.1    simonb 
    385   1.1    simonb void
    386   1.1    simonb bintime(struct bintime *bt)
    387   1.1    simonb {
    388   1.1    simonb 
    389  1.32        ad 	TC_COUNT(nbintime);
    390   1.1    simonb 	binuptime(bt);
    391   1.4    kardel 	bintime_add(bt, &timebasebin);
    392   1.1    simonb }
    393   1.1    simonb 
    394   1.1    simonb void
    395   1.1    simonb nanotime(struct timespec *tsp)
    396   1.1    simonb {
    397   1.1    simonb 	struct bintime bt;
    398   1.1    simonb 
    399  1.32        ad 	TC_COUNT(nnanotime);
    400   1.1    simonb 	bintime(&bt);
    401   1.1    simonb 	bintime2timespec(&bt, tsp);
    402   1.1    simonb }
    403   1.1    simonb 
    404   1.1    simonb void
    405   1.1    simonb microtime(struct timeval *tvp)
    406   1.1    simonb {
    407   1.1    simonb 	struct bintime bt;
    408   1.1    simonb 
    409  1.32        ad 	TC_COUNT(nmicrotime);
    410   1.1    simonb 	bintime(&bt);
    411   1.1    simonb 	bintime2timeval(&bt, tvp);
    412   1.1    simonb }
    413   1.1    simonb 
    414   1.1    simonb void
    415   1.1    simonb getbinuptime(struct bintime *bt)
    416   1.1    simonb {
    417   1.1    simonb 	struct timehands *th;
    418   1.1    simonb 	u_int gen;
    419   1.1    simonb 
    420  1.32        ad 	TC_COUNT(ngetbinuptime);
    421   1.1    simonb 	do {
    422   1.1    simonb 		th = timehands;
    423   1.1    simonb 		gen = th->th_generation;
    424   1.1    simonb 		*bt = th->th_offset;
    425   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    426   1.1    simonb }
    427   1.1    simonb 
    428   1.1    simonb void
    429   1.1    simonb getnanouptime(struct timespec *tsp)
    430   1.1    simonb {
    431   1.1    simonb 	struct timehands *th;
    432   1.1    simonb 	u_int gen;
    433   1.1    simonb 
    434  1.32        ad 	TC_COUNT(ngetnanouptime);
    435   1.1    simonb 	do {
    436   1.1    simonb 		th = timehands;
    437   1.1    simonb 		gen = th->th_generation;
    438   1.1    simonb 		bintime2timespec(&th->th_offset, tsp);
    439   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    440   1.1    simonb }
    441   1.1    simonb 
    442   1.1    simonb void
    443   1.1    simonb getmicrouptime(struct timeval *tvp)
    444   1.1    simonb {
    445   1.1    simonb 	struct timehands *th;
    446   1.1    simonb 	u_int gen;
    447   1.1    simonb 
    448  1.32        ad 	TC_COUNT(ngetmicrouptime);
    449   1.1    simonb 	do {
    450   1.1    simonb 		th = timehands;
    451   1.1    simonb 		gen = th->th_generation;
    452   1.1    simonb 		bintime2timeval(&th->th_offset, tvp);
    453   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    454   1.1    simonb }
    455   1.1    simonb 
    456   1.1    simonb void
    457   1.1    simonb getbintime(struct bintime *bt)
    458   1.1    simonb {
    459   1.1    simonb 	struct timehands *th;
    460   1.1    simonb 	u_int gen;
    461   1.1    simonb 
    462  1.32        ad 	TC_COUNT(ngetbintime);
    463   1.1    simonb 	do {
    464   1.1    simonb 		th = timehands;
    465   1.1    simonb 		gen = th->th_generation;
    466   1.1    simonb 		*bt = th->th_offset;
    467   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    468   1.4    kardel 	bintime_add(bt, &timebasebin);
    469   1.1    simonb }
    470   1.1    simonb 
    471   1.1    simonb void
    472   1.1    simonb getnanotime(struct timespec *tsp)
    473   1.1    simonb {
    474   1.1    simonb 	struct timehands *th;
    475   1.1    simonb 	u_int gen;
    476   1.1    simonb 
    477  1.32        ad 	TC_COUNT(ngetnanotime);
    478   1.1    simonb 	do {
    479   1.1    simonb 		th = timehands;
    480   1.1    simonb 		gen = th->th_generation;
    481   1.1    simonb 		*tsp = th->th_nanotime;
    482   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    483   1.1    simonb }
    484   1.1    simonb 
    485   1.1    simonb void
    486   1.1    simonb getmicrotime(struct timeval *tvp)
    487   1.1    simonb {
    488   1.1    simonb 	struct timehands *th;
    489   1.1    simonb 	u_int gen;
    490   1.1    simonb 
    491  1.32        ad 	TC_COUNT(ngetmicrotime);
    492   1.1    simonb 	do {
    493   1.1    simonb 		th = timehands;
    494   1.1    simonb 		gen = th->th_generation;
    495   1.1    simonb 		*tvp = th->th_microtime;
    496   1.1    simonb 	} while (gen == 0 || gen != th->th_generation);
    497   1.1    simonb }
    498   1.1    simonb 
    499   1.1    simonb /*
    500   1.1    simonb  * Initialize a new timecounter and possibly use it.
    501   1.1    simonb  */
    502   1.1    simonb void
    503   1.1    simonb tc_init(struct timecounter *tc)
    504   1.1    simonb {
    505   1.1    simonb 	u_int u;
    506   1.1    simonb 
    507   1.1    simonb 	u = tc->tc_frequency / tc->tc_counter_mask;
    508   1.1    simonb 	/* XXX: We need some margin here, 10% is a guess */
    509   1.1    simonb 	u *= 11;
    510   1.1    simonb 	u /= 10;
    511   1.1    simonb 	if (u > hz && tc->tc_quality >= 0) {
    512   1.1    simonb 		tc->tc_quality = -2000;
    513  1.18        ad 		aprint_verbose(
    514  1.18        ad 		    "timecounter: Timecounter \"%s\" frequency %ju Hz",
    515   1.7     bjh21 			    tc->tc_name, (uintmax_t)tc->tc_frequency);
    516  1.18        ad 		aprint_verbose(" -- Insufficient hz, needs at least %u\n", u);
    517   1.1    simonb 	} else if (tc->tc_quality >= 0 || bootverbose) {
    518  1.18        ad 		aprint_verbose(
    519  1.18        ad 		    "timecounter: Timecounter \"%s\" frequency %ju Hz "
    520  1.18        ad 		    "quality %d\n", tc->tc_name, (uintmax_t)tc->tc_frequency,
    521   1.7     bjh21 		    tc->tc_quality);
    522   1.1    simonb 	}
    523   1.1    simonb 
    524  1.33        ad 	mutex_spin_enter(&timecounter_lock);
    525   1.1    simonb 	tc->tc_next = timecounters;
    526   1.1    simonb 	timecounters = tc;
    527  1.35        ad 	timecounter_mods++;
    528   1.1    simonb 	/*
    529   1.1    simonb 	 * Never automatically use a timecounter with negative quality.
    530   1.1    simonb 	 * Even though we run on the dummy counter, switching here may be
    531   1.1    simonb 	 * worse since this timecounter may not be monotonous.
    532   1.1    simonb 	 */
    533  1.22        ad 	if (tc->tc_quality >= 0 && (tc->tc_quality > timecounter->tc_quality ||
    534  1.24        ad 	    (tc->tc_quality == timecounter->tc_quality &&
    535  1.24        ad 	    tc->tc_frequency > timecounter->tc_frequency))) {
    536  1.22        ad 		(void)tc->tc_get_timecount(tc);
    537  1.22        ad 		(void)tc->tc_get_timecount(tc);
    538  1.22        ad 		timecounter = tc;
    539  1.22        ad 		tc_windup();
    540  1.22        ad 	}
    541  1.33        ad 	mutex_spin_exit(&timecounter_lock);
    542  1.35        ad }
    543  1.35        ad 
    544  1.35        ad /*
    545  1.35        ad  * Pick a new timecounter due to the existing counter going bad.
    546  1.35        ad  */
    547  1.35        ad static void
    548  1.35        ad tc_pick(void)
    549  1.35        ad {
    550  1.35        ad 	struct timecounter *best, *tc;
    551  1.35        ad 
    552  1.35        ad 	KASSERT(mutex_owned(&timecounter_lock));
    553  1.35        ad 
    554  1.35        ad 	for (best = tc = timecounters; tc != NULL; tc = tc->tc_next) {
    555  1.35        ad 		if (tc->tc_quality > best->tc_quality)
    556  1.35        ad 			best = tc;
    557  1.35        ad 		else if (tc->tc_quality < best->tc_quality)
    558  1.35        ad 			continue;
    559  1.35        ad 		else if (tc->tc_frequency > best->tc_frequency)
    560  1.35        ad 			best = tc;
    561  1.35        ad 	}
    562  1.35        ad 	(void)best->tc_get_timecount(best);
    563  1.35        ad 	(void)best->tc_get_timecount(best);
    564  1.35        ad 	timecounter = best;
    565  1.35        ad }
    566  1.35        ad 
    567  1.35        ad /*
    568  1.35        ad  * A timecounter has gone bad, arrange to pick a new one at the next
    569  1.35        ad  * clock tick.
    570  1.35        ad  */
    571  1.35        ad void
    572  1.35        ad tc_gonebad(struct timecounter *tc)
    573  1.35        ad {
    574  1.35        ad 
    575  1.35        ad 	tc->tc_quality = -100;
    576  1.35        ad 	membar_producer();
    577  1.35        ad 	atomic_inc_uint(&timecounter_bad);
    578   1.1    simonb }
    579   1.1    simonb 
    580  1.29    dyoung /*
    581  1.29    dyoung  * Stop using a timecounter and remove it from the timecounters list.
    582  1.29    dyoung  */
    583  1.29    dyoung int
    584  1.29    dyoung tc_detach(struct timecounter *target)
    585  1.29    dyoung {
    586  1.35        ad 	struct timecounter *tc;
    587  1.29    dyoung 	struct timecounter **tcp = NULL;
    588  1.39        ad 	int removals;
    589  1.39        ad 	uint64_t where;
    590  1.39        ad 	lwp_t *l;
    591  1.29    dyoung 
    592  1.39        ad 	/* First, find the timecounter. */
    593  1.35        ad 	mutex_spin_enter(&timecounter_lock);
    594  1.29    dyoung 	for (tcp = &timecounters, tc = timecounters;
    595  1.29    dyoung 	     tc != NULL;
    596  1.29    dyoung 	     tcp = &tc->tc_next, tc = tc->tc_next) {
    597  1.29    dyoung 		if (tc == target)
    598  1.29    dyoung 			break;
    599  1.29    dyoung 	}
    600  1.29    dyoung 	if (tc == NULL) {
    601  1.39        ad 		mutex_spin_exit(&timecounter_lock);
    602  1.39        ad 		return ESRCH;
    603  1.39        ad 	}
    604  1.39        ad 
    605  1.39        ad 	/* And now, remove it. */
    606  1.39        ad 	*tcp = tc->tc_next;
    607  1.39        ad 	if (timecounter == target) {
    608  1.39        ad 		tc_pick();
    609  1.39        ad 		tc_windup();
    610  1.39        ad 	}
    611  1.39        ad 	timecounter_mods++;
    612  1.39        ad 	removals = timecounter_removals++;
    613  1.39        ad 	mutex_spin_exit(&timecounter_lock);
    614  1.39        ad 
    615  1.39        ad 	/*
    616  1.39        ad 	 * We now have to determine if any threads in the system are still
    617  1.39        ad 	 * making use of this timecounter.
    618  1.39        ad 	 *
    619  1.39        ad 	 * We issue a broadcast cross call to elide memory ordering issues,
    620  1.39        ad 	 * then scan all LWPs in the system looking at each's timecounter
    621  1.39        ad 	 * generation number.  We need to see a value of zero (not actively
    622  1.39        ad 	 * using a timecounter) or a value greater than our removal value.
    623  1.39        ad 	 *
    624  1.39        ad 	 * We may race with threads that read `timecounter_removals' and
    625  1.39        ad 	 * and then get preempted before updating `l_tcgen'.  This is not
    626  1.39        ad 	 * a problem, since it means that these threads have not yet started
    627  1.39        ad 	 * accessing timecounter state.  All we do need is one clean
    628  1.39        ad 	 * snapshot of the system where every thread appears not to be using
    629  1.39        ad 	 * old timecounter state.
    630  1.39        ad 	 */
    631  1.39        ad 	for (;;) {
    632  1.39        ad 		where = xc_broadcast(0, (xcfunc_t)nullop, NULL, NULL);
    633  1.39        ad 		xc_wait(where);
    634  1.39        ad 
    635  1.39        ad 		mutex_enter(proc_lock);
    636  1.39        ad 		LIST_FOREACH(l, &alllwp, l_list) {
    637  1.39        ad 			if (l->l_tcgen == 0 || l->l_tcgen > removals) {
    638  1.39        ad 				/*
    639  1.39        ad 				 * Not using timecounter or old timecounter
    640  1.39        ad 				 * state at time of our xcall or later.
    641  1.39        ad 				 */
    642  1.39        ad 				continue;
    643  1.39        ad 			}
    644  1.39        ad 			break;
    645  1.39        ad 		}
    646  1.39        ad 		mutex_exit(proc_lock);
    647  1.39        ad 
    648  1.39        ad 		/*
    649  1.39        ad 		 * If the timecounter is still in use, wait at least 10ms
    650  1.39        ad 		 * before retrying.
    651  1.39        ad 		 */
    652  1.39        ad 		if (l == NULL) {
    653  1.39        ad 			return 0;
    654  1.35        ad 		}
    655  1.39        ad 		(void)kpause("tcdetach", false, mstohz(10), NULL);
    656  1.29    dyoung 	}
    657  1.29    dyoung }
    658  1.29    dyoung 
    659   1.1    simonb /* Report the frequency of the current timecounter. */
    660   1.1    simonb u_int64_t
    661   1.1    simonb tc_getfrequency(void)
    662   1.1    simonb {
    663   1.1    simonb 
    664   1.1    simonb 	return (timehands->th_counter->tc_frequency);
    665   1.1    simonb }
    666   1.1    simonb 
    667   1.1    simonb /*
    668   1.1    simonb  * Step our concept of UTC.  This is done by modifying our estimate of
    669   1.1    simonb  * when we booted.
    670   1.1    simonb  */
    671   1.1    simonb void
    672  1.38  christos tc_setclock(const struct timespec *ts)
    673   1.1    simonb {
    674   1.1    simonb 	struct timespec ts2;
    675   1.1    simonb 	struct bintime bt, bt2;
    676   1.1    simonb 
    677  1.33        ad 	mutex_spin_enter(&timecounter_lock);
    678  1.32        ad 	TC_COUNT(nsetclock);
    679   1.1    simonb 	binuptime(&bt2);
    680   1.1    simonb 	timespec2bintime(ts, &bt);
    681   1.1    simonb 	bintime_sub(&bt, &bt2);
    682   1.4    kardel 	bintime_add(&bt2, &timebasebin);
    683   1.4    kardel 	timebasebin = bt;
    684  1.30        ad 	tc_windup();
    685  1.33        ad 	mutex_spin_exit(&timecounter_lock);
    686   1.1    simonb 
    687   1.1    simonb 	if (timestepwarnings) {
    688   1.1    simonb 		bintime2timespec(&bt2, &ts2);
    689  1.38  christos 		log(LOG_INFO, "Time stepped from %lld.%09ld to %lld.%09ld\n",
    690  1.38  christos 		    (long long)ts2.tv_sec, ts2.tv_nsec,
    691  1.38  christos 		    (long long)ts->tv_sec, ts->tv_nsec);
    692   1.1    simonb 	}
    693   1.1    simonb }
    694   1.1    simonb 
    695   1.1    simonb /*
    696   1.1    simonb  * Initialize the next struct timehands in the ring and make
    697   1.1    simonb  * it the active timehands.  Along the way we might switch to a different
    698   1.1    simonb  * timecounter and/or do seconds processing in NTP.  Slightly magic.
    699   1.1    simonb  */
    700   1.1    simonb static void
    701   1.1    simonb tc_windup(void)
    702   1.1    simonb {
    703   1.1    simonb 	struct bintime bt;
    704   1.1    simonb 	struct timehands *th, *tho;
    705   1.1    simonb 	u_int64_t scale;
    706   1.1    simonb 	u_int delta, ncount, ogen;
    707  1.13    kardel 	int i, s_update;
    708   1.1    simonb 	time_t t;
    709   1.1    simonb 
    710  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    711  1.30        ad 
    712  1.13    kardel 	s_update = 0;
    713  1.20        ad 
    714   1.1    simonb 	/*
    715   1.1    simonb 	 * Make the next timehands a copy of the current one, but do not
    716   1.1    simonb 	 * overwrite the generation or next pointer.  While we update
    717  1.20        ad 	 * the contents, the generation must be zero.  Ensure global
    718  1.20        ad 	 * visibility of the generation before proceeding.
    719   1.1    simonb 	 */
    720   1.1    simonb 	tho = timehands;
    721   1.1    simonb 	th = tho->th_next;
    722   1.1    simonb 	ogen = th->th_generation;
    723   1.1    simonb 	th->th_generation = 0;
    724  1.27        ad 	membar_producer();
    725   1.1    simonb 	bcopy(tho, th, offsetof(struct timehands, th_generation));
    726   1.1    simonb 
    727   1.1    simonb 	/*
    728   1.1    simonb 	 * Capture a timecounter delta on the current timecounter and if
    729   1.1    simonb 	 * changing timecounters, a counter value from the new timecounter.
    730   1.1    simonb 	 * Update the offset fields accordingly.
    731   1.1    simonb 	 */
    732   1.1    simonb 	delta = tc_delta(th);
    733   1.1    simonb 	if (th->th_counter != timecounter)
    734   1.1    simonb 		ncount = timecounter->tc_get_timecount(timecounter);
    735   1.1    simonb 	else
    736   1.1    simonb 		ncount = 0;
    737   1.1    simonb 	th->th_offset_count += delta;
    738   1.1    simonb 	bintime_addx(&th->th_offset, th->th_scale * delta);
    739   1.1    simonb 
    740   1.1    simonb 	/*
    741   1.1    simonb 	 * Hardware latching timecounters may not generate interrupts on
    742   1.1    simonb 	 * PPS events, so instead we poll them.  There is a finite risk that
    743   1.1    simonb 	 * the hardware might capture a count which is later than the one we
    744   1.1    simonb 	 * got above, and therefore possibly in the next NTP second which might
    745   1.1    simonb 	 * have a different rate than the current NTP second.  It doesn't
    746   1.1    simonb 	 * matter in practice.
    747   1.1    simonb 	 */
    748   1.1    simonb 	if (tho->th_counter->tc_poll_pps)
    749   1.1    simonb 		tho->th_counter->tc_poll_pps(tho->th_counter);
    750   1.1    simonb 
    751   1.1    simonb 	/*
    752   1.1    simonb 	 * Deal with NTP second processing.  The for loop normally
    753   1.1    simonb 	 * iterates at most once, but in extreme situations it might
    754   1.1    simonb 	 * keep NTP sane if timeouts are not run for several seconds.
    755   1.1    simonb 	 * At boot, the time step can be large when the TOD hardware
    756   1.1    simonb 	 * has been read, so on really large steps, we call
    757   1.1    simonb 	 * ntp_update_second only twice.  We need to call it twice in
    758   1.1    simonb 	 * case we missed a leap second.
    759   1.2    kardel 	 * If NTP is not compiled in ntp_update_second still calculates
    760   1.2    kardel 	 * the adjustment resulting from adjtime() calls.
    761   1.1    simonb 	 */
    762   1.1    simonb 	bt = th->th_offset;
    763   1.4    kardel 	bintime_add(&bt, &timebasebin);
    764   1.1    simonb 	i = bt.sec - tho->th_microtime.tv_sec;
    765   1.1    simonb 	if (i > LARGE_STEP)
    766   1.1    simonb 		i = 2;
    767   1.1    simonb 	for (; i > 0; i--) {
    768   1.1    simonb 		t = bt.sec;
    769   1.1    simonb 		ntp_update_second(&th->th_adjustment, &bt.sec);
    770  1.13    kardel 		s_update = 1;
    771   1.1    simonb 		if (bt.sec != t)
    772   1.4    kardel 			timebasebin.sec += bt.sec - t;
    773   1.1    simonb 	}
    774   1.2    kardel 
    775   1.1    simonb 	/* Update the UTC timestamps used by the get*() functions. */
    776   1.1    simonb 	/* XXX shouldn't do this here.  Should force non-`get' versions. */
    777   1.1    simonb 	bintime2timeval(&bt, &th->th_microtime);
    778   1.1    simonb 	bintime2timespec(&bt, &th->th_nanotime);
    779   1.1    simonb 	/* Now is a good time to change timecounters. */
    780   1.1    simonb 	if (th->th_counter != timecounter) {
    781   1.1    simonb 		th->th_counter = timecounter;
    782   1.1    simonb 		th->th_offset_count = ncount;
    783  1.13    kardel 		s_update = 1;
    784   1.1    simonb 	}
    785   1.1    simonb 
    786   1.1    simonb 	/*-
    787   1.1    simonb 	 * Recalculate the scaling factor.  We want the number of 1/2^64
    788   1.1    simonb 	 * fractions of a second per period of the hardware counter, taking
    789   1.1    simonb 	 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
    790   1.1    simonb 	 * processing provides us with.
    791   1.1    simonb 	 *
    792   1.1    simonb 	 * The th_adjustment is nanoseconds per second with 32 bit binary
    793   1.1    simonb 	 * fraction and we want 64 bit binary fraction of second:
    794   1.1    simonb 	 *
    795   1.1    simonb 	 *	 x = a * 2^32 / 10^9 = a * 4.294967296
    796   1.1    simonb 	 *
    797   1.1    simonb 	 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
    798   1.1    simonb 	 * we can only multiply by about 850 without overflowing, but that
    799   1.1    simonb 	 * leaves suitably precise fractions for multiply before divide.
    800   1.1    simonb 	 *
    801   1.1    simonb 	 * Divide before multiply with a fraction of 2199/512 results in a
    802   1.1    simonb 	 * systematic undercompensation of 10PPM of th_adjustment.  On a
    803   1.1    simonb 	 * 5000PPM adjustment this is a 0.05PPM error.  This is acceptable.
    804   1.1    simonb  	 *
    805   1.1    simonb 	 * We happily sacrifice the lowest of the 64 bits of our result
    806   1.1    simonb 	 * to the goddess of code clarity.
    807   1.1    simonb 	 *
    808   1.1    simonb 	 */
    809  1.13    kardel 	if (s_update) {
    810  1.13    kardel 		scale = (u_int64_t)1 << 63;
    811  1.13    kardel 		scale += (th->th_adjustment / 1024) * 2199;
    812  1.13    kardel 		scale /= th->th_counter->tc_frequency;
    813  1.13    kardel 		th->th_scale = scale * 2;
    814  1.13    kardel 	}
    815   1.1    simonb 	/*
    816   1.1    simonb 	 * Now that the struct timehands is again consistent, set the new
    817  1.20        ad 	 * generation number, making sure to not make it zero.  Ensure
    818  1.20        ad 	 * changes are globally visible before changing.
    819   1.1    simonb 	 */
    820   1.1    simonb 	if (++ogen == 0)
    821   1.1    simonb 		ogen = 1;
    822  1.27        ad 	membar_producer();
    823   1.1    simonb 	th->th_generation = ogen;
    824   1.1    simonb 
    825  1.20        ad 	/*
    826  1.20        ad 	 * Go live with the new struct timehands.  Ensure changes are
    827  1.20        ad 	 * globally visible before changing.
    828  1.20        ad 	 */
    829   1.1    simonb 	time_second = th->th_microtime.tv_sec;
    830   1.1    simonb 	time_uptime = th->th_offset.sec;
    831  1.27        ad 	membar_producer();
    832   1.1    simonb 	timehands = th;
    833  1.24        ad 
    834  1.24        ad 	/*
    835  1.24        ad 	 * Force users of the old timehand to move on.  This is
    836  1.24        ad 	 * necessary for MP systems; we need to ensure that the
    837  1.24        ad 	 * consumers will move away from the old timehand before
    838  1.24        ad 	 * we begin updating it again when we eventually wrap
    839  1.24        ad 	 * around.
    840  1.24        ad 	 */
    841  1.24        ad 	if (++tho->th_generation == 0)
    842  1.24        ad 		tho->th_generation = 1;
    843   1.1    simonb }
    844   1.1    simonb 
    845   1.1    simonb /*
    846   1.1    simonb  * RFC 2783 PPS-API implementation.
    847   1.1    simonb  */
    848   1.1    simonb 
    849   1.1    simonb int
    850  1.19  christos pps_ioctl(u_long cmd, void *data, struct pps_state *pps)
    851   1.1    simonb {
    852   1.1    simonb 	pps_params_t *app;
    853   1.2    kardel 	pps_info_t *pipi;
    854   1.1    simonb #ifdef PPS_SYNC
    855   1.2    kardel 	int *epi;
    856   1.1    simonb #endif
    857   1.1    simonb 
    858  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    859  1.33        ad 
    860   1.2    kardel 	KASSERT(pps != NULL); /* XXX ("NULL pps pointer in pps_ioctl") */
    861   1.1    simonb 	switch (cmd) {
    862   1.1    simonb 	case PPS_IOC_CREATE:
    863   1.1    simonb 		return (0);
    864   1.1    simonb 	case PPS_IOC_DESTROY:
    865   1.1    simonb 		return (0);
    866   1.1    simonb 	case PPS_IOC_SETPARAMS:
    867   1.1    simonb 		app = (pps_params_t *)data;
    868   1.1    simonb 		if (app->mode & ~pps->ppscap)
    869   1.1    simonb 			return (EINVAL);
    870   1.1    simonb 		pps->ppsparam = *app;
    871   1.1    simonb 		return (0);
    872   1.1    simonb 	case PPS_IOC_GETPARAMS:
    873   1.1    simonb 		app = (pps_params_t *)data;
    874   1.1    simonb 		*app = pps->ppsparam;
    875   1.1    simonb 		app->api_version = PPS_API_VERS_1;
    876   1.1    simonb 		return (0);
    877   1.1    simonb 	case PPS_IOC_GETCAP:
    878   1.1    simonb 		*(int*)data = pps->ppscap;
    879   1.1    simonb 		return (0);
    880   1.1    simonb 	case PPS_IOC_FETCH:
    881   1.2    kardel 		pipi = (pps_info_t *)data;
    882   1.1    simonb 		pps->ppsinfo.current_mode = pps->ppsparam.mode;
    883   1.2    kardel 		*pipi = pps->ppsinfo;
    884   1.1    simonb 		return (0);
    885   1.1    simonb 	case PPS_IOC_KCBIND:
    886   1.1    simonb #ifdef PPS_SYNC
    887   1.2    kardel 		epi = (int *)data;
    888   1.1    simonb 		/* XXX Only root should be able to do this */
    889   1.2    kardel 		if (*epi & ~pps->ppscap)
    890   1.1    simonb 			return (EINVAL);
    891   1.2    kardel 		pps->kcmode = *epi;
    892   1.1    simonb 		return (0);
    893   1.1    simonb #else
    894   1.1    simonb 		return (EOPNOTSUPP);
    895   1.1    simonb #endif
    896   1.1    simonb 	default:
    897   1.2    kardel 		return (EPASSTHROUGH);
    898   1.1    simonb 	}
    899   1.1    simonb }
    900   1.1    simonb 
    901   1.1    simonb void
    902   1.1    simonb pps_init(struct pps_state *pps)
    903   1.1    simonb {
    904  1.33        ad 
    905  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    906  1.33        ad 
    907   1.1    simonb 	pps->ppscap |= PPS_TSFMT_TSPEC;
    908   1.1    simonb 	if (pps->ppscap & PPS_CAPTUREASSERT)
    909   1.1    simonb 		pps->ppscap |= PPS_OFFSETASSERT;
    910   1.1    simonb 	if (pps->ppscap & PPS_CAPTURECLEAR)
    911   1.1    simonb 		pps->ppscap |= PPS_OFFSETCLEAR;
    912   1.1    simonb }
    913   1.1    simonb 
    914   1.1    simonb void
    915   1.1    simonb pps_capture(struct pps_state *pps)
    916   1.1    simonb {
    917   1.1    simonb 	struct timehands *th;
    918   1.1    simonb 
    919  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    920  1.33        ad 	KASSERT(pps != NULL);
    921  1.33        ad 
    922   1.1    simonb 	th = timehands;
    923   1.1    simonb 	pps->capgen = th->th_generation;
    924   1.1    simonb 	pps->capth = th;
    925  1.40    kardel 	pps->capcount = (u_int64_t)tc_delta(th) + th->th_offset_count;
    926   1.1    simonb 	if (pps->capgen != th->th_generation)
    927   1.1    simonb 		pps->capgen = 0;
    928   1.1    simonb }
    929   1.1    simonb 
    930   1.1    simonb void
    931   1.1    simonb pps_event(struct pps_state *pps, int event)
    932   1.1    simonb {
    933   1.1    simonb 	struct bintime bt;
    934   1.1    simonb 	struct timespec ts, *tsp, *osp;
    935  1.40    kardel 	u_int64_t tcount, *pcount;
    936   1.1    simonb 	int foff, fhard;
    937   1.1    simonb 	pps_seq_t *pseq;
    938   1.1    simonb 
    939  1.33        ad 	KASSERT(mutex_owned(&timecounter_lock));
    940  1.33        ad 
    941   1.2    kardel 	KASSERT(pps != NULL); /* XXX ("NULL pps pointer in pps_event") */
    942   1.1    simonb 	/* If the timecounter was wound up underneath us, bail out. */
    943   1.1    simonb 	if (pps->capgen == 0 || pps->capgen != pps->capth->th_generation)
    944   1.1    simonb 		return;
    945   1.1    simonb 
    946   1.1    simonb 	/* Things would be easier with arrays. */
    947   1.1    simonb 	if (event == PPS_CAPTUREASSERT) {
    948   1.1    simonb 		tsp = &pps->ppsinfo.assert_timestamp;
    949   1.1    simonb 		osp = &pps->ppsparam.assert_offset;
    950   1.1    simonb 		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
    951   1.1    simonb 		fhard = pps->kcmode & PPS_CAPTUREASSERT;
    952   1.1    simonb 		pcount = &pps->ppscount[0];
    953   1.1    simonb 		pseq = &pps->ppsinfo.assert_sequence;
    954   1.1    simonb 	} else {
    955   1.1    simonb 		tsp = &pps->ppsinfo.clear_timestamp;
    956   1.1    simonb 		osp = &pps->ppsparam.clear_offset;
    957   1.1    simonb 		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
    958   1.1    simonb 		fhard = pps->kcmode & PPS_CAPTURECLEAR;
    959   1.1    simonb 		pcount = &pps->ppscount[1];
    960   1.1    simonb 		pseq = &pps->ppsinfo.clear_sequence;
    961   1.1    simonb 	}
    962   1.1    simonb 
    963   1.1    simonb 	/*
    964   1.1    simonb 	 * If the timecounter changed, we cannot compare the count values, so
    965   1.1    simonb 	 * we have to drop the rest of the PPS-stuff until the next event.
    966   1.1    simonb 	 */
    967   1.1    simonb 	if (pps->ppstc != pps->capth->th_counter) {
    968   1.1    simonb 		pps->ppstc = pps->capth->th_counter;
    969   1.1    simonb 		*pcount = pps->capcount;
    970   1.1    simonb 		pps->ppscount[2] = pps->capcount;
    971   1.1    simonb 		return;
    972   1.1    simonb 	}
    973   1.1    simonb 
    974   1.1    simonb 	/* Convert the count to a timespec. */
    975   1.1    simonb 	tcount = pps->capcount - pps->capth->th_offset_count;
    976   1.1    simonb 	bt = pps->capth->th_offset;
    977   1.1    simonb 	bintime_addx(&bt, pps->capth->th_scale * tcount);
    978   1.4    kardel 	bintime_add(&bt, &timebasebin);
    979   1.1    simonb 	bintime2timespec(&bt, &ts);
    980   1.1    simonb 
    981   1.1    simonb 	/* If the timecounter was wound up underneath us, bail out. */
    982   1.1    simonb 	if (pps->capgen != pps->capth->th_generation)
    983   1.1    simonb 		return;
    984   1.1    simonb 
    985   1.1    simonb 	*pcount = pps->capcount;
    986   1.1    simonb 	(*pseq)++;
    987   1.1    simonb 	*tsp = ts;
    988   1.1    simonb 
    989   1.1    simonb 	if (foff) {
    990   1.2    kardel 		timespecadd(tsp, osp, tsp);
    991   1.1    simonb 		if (tsp->tv_nsec < 0) {
    992   1.1    simonb 			tsp->tv_nsec += 1000000000;
    993   1.1    simonb 			tsp->tv_sec -= 1;
    994   1.1    simonb 		}
    995   1.1    simonb 	}
    996   1.1    simonb #ifdef PPS_SYNC
    997   1.1    simonb 	if (fhard) {
    998   1.1    simonb 		u_int64_t scale;
    999   1.1    simonb 
   1000   1.1    simonb 		/*
   1001   1.1    simonb 		 * Feed the NTP PLL/FLL.
   1002   1.1    simonb 		 * The FLL wants to know how many (hardware) nanoseconds
   1003   1.1    simonb 		 * elapsed since the previous event.
   1004   1.1    simonb 		 */
   1005   1.1    simonb 		tcount = pps->capcount - pps->ppscount[2];
   1006   1.1    simonb 		pps->ppscount[2] = pps->capcount;
   1007   1.1    simonb 		tcount &= pps->capth->th_counter->tc_counter_mask;
   1008   1.1    simonb 		scale = (u_int64_t)1 << 63;
   1009   1.1    simonb 		scale /= pps->capth->th_counter->tc_frequency;
   1010   1.1    simonb 		scale *= 2;
   1011   1.1    simonb 		bt.sec = 0;
   1012   1.1    simonb 		bt.frac = 0;
   1013   1.1    simonb 		bintime_addx(&bt, scale * tcount);
   1014   1.1    simonb 		bintime2timespec(&bt, &ts);
   1015   1.1    simonb 		hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
   1016   1.1    simonb 	}
   1017   1.1    simonb #endif
   1018   1.1    simonb }
   1019   1.1    simonb 
   1020   1.1    simonb /*
   1021   1.1    simonb  * Timecounters need to be updated every so often to prevent the hardware
   1022   1.1    simonb  * counter from overflowing.  Updating also recalculates the cached values
   1023   1.1    simonb  * used by the get*() family of functions, so their precision depends on
   1024   1.1    simonb  * the update frequency.
   1025   1.1    simonb  */
   1026   1.1    simonb 
   1027   1.1    simonb static int tc_tick;
   1028   1.1    simonb 
   1029   1.1    simonb void
   1030   1.1    simonb tc_ticktock(void)
   1031   1.1    simonb {
   1032   1.1    simonb 	static int count;
   1033   1.1    simonb 
   1034   1.1    simonb 	if (++count < tc_tick)
   1035   1.1    simonb 		return;
   1036   1.1    simonb 	count = 0;
   1037  1.33        ad 	mutex_spin_enter(&timecounter_lock);
   1038  1.35        ad 	if (timecounter_bad != 0) {
   1039  1.35        ad 		/* An existing timecounter has gone bad, pick a new one. */
   1040  1.35        ad 		(void)atomic_swap_uint(&timecounter_bad, 0);
   1041  1.35        ad 		if (timecounter->tc_quality < 0) {
   1042  1.35        ad 			tc_pick();
   1043  1.35        ad 		}
   1044  1.35        ad 	}
   1045   1.1    simonb 	tc_windup();
   1046  1.33        ad 	mutex_spin_exit(&timecounter_lock);
   1047   1.1    simonb }
   1048   1.1    simonb 
   1049   1.2    kardel void
   1050   1.2    kardel inittimecounter(void)
   1051   1.1    simonb {
   1052   1.1    simonb 	u_int p;
   1053   1.1    simonb 
   1054  1.37    kardel 	mutex_init(&timecounter_lock, MUTEX_DEFAULT, IPL_HIGH);
   1055  1.30        ad 
   1056   1.1    simonb 	/*
   1057   1.1    simonb 	 * Set the initial timeout to
   1058   1.1    simonb 	 * max(1, <approx. number of hardclock ticks in a millisecond>).
   1059   1.1    simonb 	 * People should probably not use the sysctl to set the timeout
   1060   1.1    simonb 	 * to smaller than its inital value, since that value is the
   1061   1.1    simonb 	 * smallest reasonable one.  If they want better timestamps they
   1062   1.1    simonb 	 * should use the non-"get"* functions.
   1063   1.1    simonb 	 */
   1064   1.1    simonb 	if (hz > 1000)
   1065   1.1    simonb 		tc_tick = (hz + 500) / 1000;
   1066   1.1    simonb 	else
   1067   1.1    simonb 		tc_tick = 1;
   1068   1.1    simonb 	p = (tc_tick * 1000000) / hz;
   1069  1.18        ad 	aprint_verbose("timecounter: Timecounters tick every %d.%03u msec\n",
   1070  1.18        ad 	    p / 1000, p % 1000);
   1071   1.1    simonb 
   1072   1.1    simonb 	/* warm up new timecounter (again) and get rolling. */
   1073   1.1    simonb 	(void)timecounter->tc_get_timecount(timecounter);
   1074   1.1    simonb 	(void)timecounter->tc_get_timecount(timecounter);
   1075   1.1    simonb }
   1076