kern_tc.c revision 53751
1132956Smarkm/*-
2132956Smarkm * Copyright (c) 1997, 1998 Poul-Henning Kamp <phk@FreeBSD.org>
3132956Smarkm * Copyright (c) 1982, 1986, 1991, 1993
4132956Smarkm *	The Regents of the University of California.  All rights reserved.
5132956Smarkm * (c) UNIX System Laboratories, Inc.
6132956Smarkm * All or some portions of this file are derived from material licensed
7132956Smarkm * to the University of California by American Telephone and Telegraph
8132956Smarkm * Co. or Unix System Laboratories, Inc. and are reproduced herein with
9132956Smarkm * the permission of UNIX System Laboratories, Inc.
10132956Smarkm *
11132956Smarkm * Redistribution and use in source and binary forms, with or without
12132956Smarkm * modification, are permitted provided that the following conditions
13132956Smarkm * are met:
14132956Smarkm * 1. Redistributions of source code must retain the above copyright
15132956Smarkm *    notice, this list of conditions and the following disclaimer.
16132956Smarkm * 2. Redistributions in binary form must reproduce the above copyright
17132956Smarkm *    notice, this list of conditions and the following disclaimer in the
18132956Smarkm *    documentation and/or other materials provided with the distribution.
19132956Smarkm * 3. All advertising materials mentioning features or use of this software
20132956Smarkm *    must display the following acknowledgement:
21132956Smarkm *	This product includes software developed by the University of
22132956Smarkm *	California, Berkeley and its contributors.
23132956Smarkm * 4. Neither the name of the University nor the names of its contributors
24132956Smarkm *    may be used to endorse or promote products derived from this software
25132956Smarkm *    without specific prior written permission.
26132956Smarkm *
27132956Smarkm * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28207329Sattilio * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29207329Sattilio * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30132956Smarkm * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31207329Sattilio * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32207329Sattilio * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33207329Sattilio * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34207329Sattilio * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35207329Sattilio * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36207329Sattilio * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37207329Sattilio * SUCH DAMAGE.
38207329Sattilio *
39207329Sattilio *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
40207329Sattilio * $FreeBSD: head/sys/kern/kern_tc.c 53751 1999-11-27 14:37:34Z bde $
41207329Sattilio */
42207329Sattilio
43207329Sattilio#include "opt_ntp.h"
44207329Sattilio
45207329Sattilio#include <sys/param.h>
46207329Sattilio#include <sys/systm.h>
47#include <sys/dkstat.h>
48#include <sys/callout.h>
49#include <sys/kernel.h>
50#include <sys/proc.h>
51#include <sys/malloc.h>
52#include <sys/resourcevar.h>
53#include <sys/signalvar.h>
54#include <sys/timex.h>
55#include <sys/timepps.h>
56#include <vm/vm.h>
57#include <sys/lock.h>
58#include <vm/pmap.h>
59#include <vm/vm_map.h>
60#include <sys/sysctl.h>
61
62#include <machine/cpu.h>
63#include <machine/limits.h>
64
65#ifdef GPROF
66#include <sys/gmon.h>
67#endif
68
69#if defined(SMP) && defined(BETTER_CLOCK)
70#include <machine/smp.h>
71#endif
72
73/*
74 * Number of timecounters used to implement stable storage
75 */
76#ifndef NTIMECOUNTER
77#define NTIMECOUNTER	5
78#endif
79
80static MALLOC_DEFINE(M_TIMECOUNTER, "timecounter",
81	"Timecounter stable storage");
82
83static void initclocks __P((void *dummy));
84SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
85
86static void tco_forward __P((int force));
87static void tco_setscales __P((struct timecounter *tc));
88static __inline unsigned tco_delta __P((struct timecounter *tc));
89
90/* Some of these don't belong here, but it's easiest to concentrate them. */
91#if defined(SMP) && defined(BETTER_CLOCK)
92long cp_time[CPUSTATES];
93#else
94static long cp_time[CPUSTATES];
95#endif
96
97long tk_cancc;
98long tk_nin;
99long tk_nout;
100long tk_rawcc;
101
102time_t time_second;
103
104struct	timeval boottime;
105SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
106    &boottime, timeval, "System boottime");
107
108/*
109 * Which update policy to use.
110 *   0 - every tick, bad hardware may fail with "calcru negative..."
111 *   1 - more resistent to the above hardware, but less efficient.
112 */
113static int tco_method;
114
115/*
116 * Implement a dummy timecounter which we can use until we get a real one
117 * in the air.  This allows the console and other early stuff to use
118 * timeservices.
119 */
120
121static unsigned
122dummy_get_timecount(struct timecounter *tc)
123{
124	static unsigned now;
125	return (++now);
126}
127
128static struct timecounter dummy_timecounter = {
129	dummy_get_timecount,
130	0,
131	~0u,
132	1000000,
133	"dummy"
134};
135
136struct timecounter *timecounter = &dummy_timecounter;
137
138/*
139 * Clock handling routines.
140 *
141 * This code is written to operate with two timers that run independently of
142 * each other.
143 *
144 * The main timer, running hz times per second, is used to trigger interval
145 * timers, timeouts and rescheduling as needed.
146 *
147 * The second timer handles kernel and user profiling,
148 * and does resource use estimation.  If the second timer is programmable,
149 * it is randomized to avoid aliasing between the two clocks.  For example,
150 * the randomization prevents an adversary from always giving up the cpu
151 * just before its quantum expires.  Otherwise, it would never accumulate
152 * cpu ticks.  The mean frequency of the second timer is stathz.
153 *
154 * If no second timer exists, stathz will be zero; in this case we drive
155 * profiling and statistics off the main clock.  This WILL NOT be accurate;
156 * do not do it unless absolutely necessary.
157 *
158 * The statistics clock may (or may not) be run at a higher rate while
159 * profiling.  This profile clock runs at profhz.  We require that profhz
160 * be an integral multiple of stathz.
161 *
162 * If the statistics clock is running fast, it must be divided by the ratio
163 * profhz/stathz for statistics.  (For profiling, every tick counts.)
164 *
165 * Time-of-day is maintained using a "timecounter", which may or may
166 * not be related to the hardware generating the above mentioned
167 * interrupts.
168 */
169
170int	stathz;
171int	profhz;
172static int profprocs;
173int	ticks;
174static int psdiv, pscnt;		/* prof => stat divider */
175int	psratio;			/* ratio: prof / stat */
176
177/*
178 * Initialize clock frequencies and start both clocks running.
179 */
180/* ARGSUSED*/
181static void
182initclocks(dummy)
183	void *dummy;
184{
185	register int i;
186
187	/*
188	 * Set divisors to 1 (normal case) and let the machine-specific
189	 * code do its bit.
190	 */
191	psdiv = pscnt = 1;
192	cpu_initclocks();
193
194	/*
195	 * Compute profhz/stathz, and fix profhz if needed.
196	 */
197	i = stathz ? stathz : hz;
198	if (profhz == 0)
199		profhz = i;
200	psratio = profhz / i;
201}
202
203/*
204 * The real-time timer, interrupting hz times per second.
205 */
206void
207hardclock(frame)
208	register struct clockframe *frame;
209{
210	register struct proc *p;
211
212	p = curproc;
213	if (p) {
214		register struct pstats *pstats;
215
216		/*
217		 * Run current process's virtual and profile time, as needed.
218		 */
219		pstats = p->p_stats;
220		if (CLKF_USERMODE(frame) &&
221		    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
222		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
223			psignal(p, SIGVTALRM);
224		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
225		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
226			psignal(p, SIGPROF);
227	}
228
229#if defined(SMP) && defined(BETTER_CLOCK)
230	forward_hardclock(pscnt);
231#endif
232
233	/*
234	 * If no separate statistics clock is available, run it from here.
235	 */
236	if (stathz == 0)
237		statclock(frame);
238
239	tco_forward(0);
240	ticks++;
241
242	/*
243	 * Process callouts at a very low cpu priority, so we don't keep the
244	 * relatively high clock interrupt priority any longer than necessary.
245	 */
246	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
247		if (CLKF_BASEPRI(frame)) {
248			/*
249			 * Save the overhead of a software interrupt;
250			 * it will happen as soon as we return, so do it now.
251			 */
252			(void)splsoftclock();
253			softclock();
254		} else
255			setsoftclock();
256	} else if (softticks + 1 == ticks)
257		++softticks;
258}
259
260/*
261 * Compute number of ticks in the specified amount of time.
262 */
263int
264tvtohz(tv)
265	struct timeval *tv;
266{
267	register unsigned long ticks;
268	register long sec, usec;
269
270	/*
271	 * If the number of usecs in the whole seconds part of the time
272	 * difference fits in a long, then the total number of usecs will
273	 * fit in an unsigned long.  Compute the total and convert it to
274	 * ticks, rounding up and adding 1 to allow for the current tick
275	 * to expire.  Rounding also depends on unsigned long arithmetic
276	 * to avoid overflow.
277	 *
278	 * Otherwise, if the number of ticks in the whole seconds part of
279	 * the time difference fits in a long, then convert the parts to
280	 * ticks separately and add, using similar rounding methods and
281	 * overflow avoidance.  This method would work in the previous
282	 * case but it is slightly slower and assumes that hz is integral.
283	 *
284	 * Otherwise, round the time difference down to the maximum
285	 * representable value.
286	 *
287	 * If ints have 32 bits, then the maximum value for any timeout in
288	 * 10ms ticks is 248 days.
289	 */
290	sec = tv->tv_sec;
291	usec = tv->tv_usec;
292	if (usec < 0) {
293		sec--;
294		usec += 1000000;
295	}
296	if (sec < 0) {
297#ifdef DIAGNOSTIC
298		if (usec > 0) {
299			sec++;
300			usec -= 1000000;
301		}
302		printf("tvotohz: negative time difference %ld sec %ld usec\n",
303		       sec, usec);
304#endif
305		ticks = 1;
306	} else if (sec <= LONG_MAX / 1000000)
307		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
308			/ tick + 1;
309	else if (sec <= LONG_MAX / hz)
310		ticks = sec * hz
311			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
312	else
313		ticks = LONG_MAX;
314	if (ticks > INT_MAX)
315		ticks = INT_MAX;
316	return ((int)ticks);
317}
318
319/*
320 * Start profiling on a process.
321 *
322 * Kernel profiling passes proc0 which never exits and hence
323 * keeps the profile clock running constantly.
324 */
325void
326startprofclock(p)
327	register struct proc *p;
328{
329	int s;
330
331	if ((p->p_flag & P_PROFIL) == 0) {
332		p->p_flag |= P_PROFIL;
333		if (++profprocs == 1 && stathz != 0) {
334			s = splstatclock();
335			psdiv = pscnt = psratio;
336			setstatclockrate(profhz);
337			splx(s);
338		}
339	}
340}
341
342/*
343 * Stop profiling on a process.
344 */
345void
346stopprofclock(p)
347	register struct proc *p;
348{
349	int s;
350
351	if (p->p_flag & P_PROFIL) {
352		p->p_flag &= ~P_PROFIL;
353		if (--profprocs == 0 && stathz != 0) {
354			s = splstatclock();
355			psdiv = pscnt = 1;
356			setstatclockrate(stathz);
357			splx(s);
358		}
359	}
360}
361
362/*
363 * Statistics clock.  Grab profile sample, and if divider reaches 0,
364 * do process and kernel statistics.  Most of the statistics are only
365 * used by user-level statistics programs.  The main exceptions are
366 * p->p_uticks, p->p_sticks, p->p_iticks, and p->p_estcpu.
367 */
368void
369statclock(frame)
370	register struct clockframe *frame;
371{
372#ifdef GPROF
373	register struct gmonparam *g;
374	int i;
375#endif
376	register struct proc *p;
377	struct pstats *pstats;
378	long rss;
379	struct rusage *ru;
380	struct vmspace *vm;
381
382	if (curproc != NULL && CLKF_USERMODE(frame)) {
383		/*
384		 * Came from user mode; CPU was in user state.
385		 * If this process is being profiled, record the tick.
386		 */
387		p = curproc;
388		if (p->p_flag & P_PROFIL)
389			addupc_intr(p, CLKF_PC(frame), 1);
390#if defined(SMP) && defined(BETTER_CLOCK)
391		if (stathz != 0)
392			forward_statclock(pscnt);
393#endif
394		if (--pscnt > 0)
395			return;
396		/*
397		 * Charge the time as appropriate.
398		 */
399		p->p_uticks++;
400		if (p->p_nice > NZERO)
401			cp_time[CP_NICE]++;
402		else
403			cp_time[CP_USER]++;
404	} else {
405#ifdef GPROF
406		/*
407		 * Kernel statistics are just like addupc_intr, only easier.
408		 */
409		g = &_gmonparam;
410		if (g->state == GMON_PROF_ON) {
411			i = CLKF_PC(frame) - g->lowpc;
412			if (i < g->textsize) {
413				i /= HISTFRACTION * sizeof(*g->kcount);
414				g->kcount[i]++;
415			}
416		}
417#endif
418#if defined(SMP) && defined(BETTER_CLOCK)
419		if (stathz != 0)
420			forward_statclock(pscnt);
421#endif
422		if (--pscnt > 0)
423			return;
424		/*
425		 * Came from kernel mode, so we were:
426		 * - handling an interrupt,
427		 * - doing syscall or trap work on behalf of the current
428		 *   user process, or
429		 * - spinning in the idle loop.
430		 * Whichever it is, charge the time as appropriate.
431		 * Note that we charge interrupts to the current process,
432		 * regardless of whether they are ``for'' that process,
433		 * so that we know how much of its real time was spent
434		 * in ``non-process'' (i.e., interrupt) work.
435		 */
436		p = curproc;
437		if (CLKF_INTR(frame)) {
438			if (p != NULL)
439				p->p_iticks++;
440			cp_time[CP_INTR]++;
441		} else if (p != NULL) {
442			p->p_sticks++;
443			cp_time[CP_SYS]++;
444		} else
445			cp_time[CP_IDLE]++;
446	}
447	pscnt = psdiv;
448
449	if (p != NULL) {
450		schedclock(p);
451
452		/* Update resource usage integrals and maximums. */
453		if ((pstats = p->p_stats) != NULL &&
454		    (ru = &pstats->p_ru) != NULL &&
455		    (vm = p->p_vmspace) != NULL) {
456			ru->ru_ixrss += pgtok(vm->vm_tsize);
457			ru->ru_idrss += pgtok(vm->vm_dsize);
458			ru->ru_isrss += pgtok(vm->vm_ssize);
459			rss = pgtok(vmspace_resident_count(vm));
460			if (ru->ru_maxrss < rss)
461				ru->ru_maxrss = rss;
462		}
463	}
464}
465
466/*
467 * Return information about system clocks.
468 */
469static int
470sysctl_kern_clockrate SYSCTL_HANDLER_ARGS
471{
472	struct clockinfo clkinfo;
473	/*
474	 * Construct clockinfo structure.
475	 */
476	clkinfo.hz = hz;
477	clkinfo.tick = tick;
478	clkinfo.tickadj = tickadj;
479	clkinfo.profhz = profhz;
480	clkinfo.stathz = stathz ? stathz : hz;
481	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
482}
483
484SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
485	0, 0, sysctl_kern_clockrate, "S,clockinfo","");
486
487static __inline unsigned
488tco_delta(struct timecounter *tc)
489{
490
491	return ((tc->tc_get_timecount(tc) - tc->tc_offset_count) &
492	    tc->tc_counter_mask);
493}
494
495/*
496 * We have eight functions for looking at the clock, four for
497 * microseconds and four for nanoseconds.  For each there is fast
498 * but less precise version "get{nano|micro}[up]time" which will
499 * return a time which is up to 1/HZ previous to the call, whereas
500 * the raw version "{nano|micro}[up]time" will return a timestamp
501 * which is as precise as possible.  The "up" variants return the
502 * time relative to system boot, these are well suited for time
503 * interval measurements.
504 */
505
506void
507getmicrotime(struct timeval *tvp)
508{
509	struct timecounter *tc;
510
511	if (!tco_method) {
512		tc = timecounter;
513		*tvp = tc->tc_microtime;
514	} else {
515		microtime(tvp);
516	}
517}
518
519void
520getnanotime(struct timespec *tsp)
521{
522	struct timecounter *tc;
523
524	if (!tco_method) {
525		tc = timecounter;
526		*tsp = tc->tc_nanotime;
527	} else {
528		nanotime(tsp);
529	}
530}
531
532void
533microtime(struct timeval *tv)
534{
535	struct timecounter *tc;
536
537	tc = timecounter;
538	tv->tv_sec = tc->tc_offset_sec;
539	tv->tv_usec = tc->tc_offset_micro;
540	tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
541	tv->tv_usec += boottime.tv_usec;
542	tv->tv_sec += boottime.tv_sec;
543	while (tv->tv_usec >= 1000000) {
544		tv->tv_usec -= 1000000;
545		tv->tv_sec++;
546	}
547}
548
549void
550nanotime(struct timespec *ts)
551{
552	unsigned count;
553	u_int64_t delta;
554	struct timecounter *tc;
555
556	tc = timecounter;
557	ts->tv_sec = tc->tc_offset_sec;
558	count = tco_delta(tc);
559	delta = tc->tc_offset_nano;
560	delta += ((u_int64_t)count * tc->tc_scale_nano_f);
561	delta >>= 32;
562	delta += ((u_int64_t)count * tc->tc_scale_nano_i);
563	delta += boottime.tv_usec * 1000;
564	ts->tv_sec += boottime.tv_sec;
565	while (delta >= 1000000000) {
566		delta -= 1000000000;
567		ts->tv_sec++;
568	}
569	ts->tv_nsec = delta;
570}
571
572void
573getmicrouptime(struct timeval *tvp)
574{
575	struct timecounter *tc;
576
577	if (!tco_method) {
578		tc = timecounter;
579		tvp->tv_sec = tc->tc_offset_sec;
580		tvp->tv_usec = tc->tc_offset_micro;
581	} else {
582		microuptime(tvp);
583	}
584}
585
586void
587getnanouptime(struct timespec *tsp)
588{
589	struct timecounter *tc;
590
591	if (!tco_method) {
592		tc = timecounter;
593		tsp->tv_sec = tc->tc_offset_sec;
594		tsp->tv_nsec = tc->tc_offset_nano >> 32;
595	} else {
596		nanouptime(tsp);
597	}
598}
599
600void
601microuptime(struct timeval *tv)
602{
603	struct timecounter *tc;
604
605	tc = timecounter;
606	tv->tv_sec = tc->tc_offset_sec;
607	tv->tv_usec = tc->tc_offset_micro;
608	tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
609	if (tv->tv_usec >= 1000000) {
610		tv->tv_usec -= 1000000;
611		tv->tv_sec++;
612	}
613}
614
615void
616nanouptime(struct timespec *ts)
617{
618	unsigned count;
619	u_int64_t delta;
620	struct timecounter *tc;
621
622	tc = timecounter;
623	ts->tv_sec = tc->tc_offset_sec;
624	count = tco_delta(tc);
625	delta = tc->tc_offset_nano;
626	delta += ((u_int64_t)count * tc->tc_scale_nano_f);
627	delta >>= 32;
628	delta += ((u_int64_t)count * tc->tc_scale_nano_i);
629	if (delta >= 1000000000) {
630		delta -= 1000000000;
631		ts->tv_sec++;
632	}
633	ts->tv_nsec = delta;
634}
635
636static void
637tco_setscales(struct timecounter *tc)
638{
639	u_int64_t scale;
640
641	scale = 1000000000LL << 32;
642	scale += tc->tc_adjustment;
643	scale /= tc->tc_tweak->tc_frequency;
644	tc->tc_scale_micro = scale / 1000;
645	tc->tc_scale_nano_f = scale & 0xffffffff;
646	tc->tc_scale_nano_i = scale >> 32;
647}
648
649void
650update_timecounter(struct timecounter *tc)
651{
652	tco_setscales(tc);
653}
654
655void
656init_timecounter(struct timecounter *tc)
657{
658	struct timespec ts1;
659	struct timecounter *t1, *t2, *t3;
660	int i;
661
662	tc->tc_adjustment = 0;
663	tc->tc_tweak = tc;
664	tco_setscales(tc);
665	tc->tc_offset_count = tc->tc_get_timecount(tc);
666	if (timecounter == &dummy_timecounter)
667		tc->tc_avail = tc;
668	else {
669		tc->tc_avail = timecounter->tc_tweak->tc_avail;
670		timecounter->tc_tweak->tc_avail = tc;
671	}
672	MALLOC(t1, struct timecounter *, sizeof *t1, M_TIMECOUNTER, M_WAITOK);
673	tc->tc_other = t1;
674	*t1 = *tc;
675	t2 = t1;
676	for (i = 1; i < NTIMECOUNTER; i++) {
677		MALLOC(t3, struct timecounter *, sizeof *t3,
678		    M_TIMECOUNTER, M_WAITOK);
679		*t3 = *tc;
680		t3->tc_other = t2;
681		t2 = t3;
682	}
683	t1->tc_other = t3;
684	tc = t1;
685
686	printf("Timecounter \"%s\"  frequency %lu Hz\n",
687	    tc->tc_name, (u_long)tc->tc_frequency);
688
689	/* XXX: For now always start using the counter. */
690	tc->tc_offset_count = tc->tc_get_timecount(tc);
691	nanouptime(&ts1);
692	tc->tc_offset_nano = (u_int64_t)ts1.tv_nsec << 32;
693	tc->tc_offset_micro = ts1.tv_nsec / 1000;
694	tc->tc_offset_sec = ts1.tv_sec;
695	timecounter = tc;
696}
697
698void
699set_timecounter(struct timespec *ts)
700{
701	struct timespec ts2;
702
703	nanouptime(&ts2);
704	boottime.tv_sec = ts->tv_sec - ts2.tv_sec;
705	boottime.tv_usec = (ts->tv_nsec - ts2.tv_nsec) / 1000;
706	if (boottime.tv_usec < 0) {
707		boottime.tv_usec += 1000000;
708		boottime.tv_sec--;
709	}
710	/* fiddle all the little crinkly bits around the fiords... */
711	tco_forward(1);
712}
713
714static void
715switch_timecounter(struct timecounter *newtc)
716{
717	int s;
718	struct timecounter *tc;
719	struct timespec ts;
720
721	s = splclock();
722	tc = timecounter;
723	if (newtc->tc_tweak == tc->tc_tweak) {
724		splx(s);
725		return;
726	}
727	newtc = newtc->tc_tweak->tc_other;
728	nanouptime(&ts);
729	newtc->tc_offset_sec = ts.tv_sec;
730	newtc->tc_offset_nano = (u_int64_t)ts.tv_nsec << 32;
731	newtc->tc_offset_micro = ts.tv_nsec / 1000;
732	newtc->tc_offset_count = newtc->tc_get_timecount(newtc);
733	tco_setscales(newtc);
734	timecounter = newtc;
735	splx(s);
736}
737
738static struct timecounter *
739sync_other_counter(void)
740{
741	struct timecounter *tc, *tcn, *tco;
742	unsigned delta;
743
744	tco = timecounter;
745	tc = tco->tc_other;
746	tcn = tc->tc_other;
747	*tc = *tco;
748	tc->tc_other = tcn;
749	delta = tco_delta(tc);
750	tc->tc_offset_count += delta;
751	tc->tc_offset_count &= tc->tc_counter_mask;
752	tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_f;
753	tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_i << 32;
754	return (tc);
755}
756
757static void
758tco_forward(int force)
759{
760	struct timecounter *tc, *tco;
761
762	tco = timecounter;
763	tc = sync_other_counter();
764	/*
765	 * We may be inducing a tiny error here, the tc_poll_pps() may
766	 * process a latched count which happens after the tco_delta()
767	 * in sync_other_counter(), which would extend the previous
768	 * counters parameters into the domain of this new one.
769	 * Since the timewindow is very small for this, the error is
770	 * going to be only a few weenieseconds (as Dave Mills would
771	 * say), so lets just not talk more about it, OK ?
772	 */
773	if (tco->tc_poll_pps)
774		tco->tc_poll_pps(tco);
775	if (timedelta != 0) {
776		tc->tc_offset_nano += (u_int64_t)(tickdelta * 1000) << 32;
777		timedelta -= tickdelta;
778		force++;
779	}
780
781	while (tc->tc_offset_nano >= 1000000000ULL << 32) {
782		tc->tc_offset_nano -= 1000000000ULL << 32;
783		tc->tc_offset_sec++;
784		ntp_update_second(tc);	/* XXX only needed if xntpd runs */
785		tco_setscales(tc);
786		force++;
787	}
788
789	if (tco_method && !force)
790		return;
791
792	tc->tc_offset_micro = (tc->tc_offset_nano / 1000) >> 32;
793
794	/* Figure out the wall-clock time */
795	tc->tc_nanotime.tv_sec = tc->tc_offset_sec + boottime.tv_sec;
796	tc->tc_nanotime.tv_nsec =
797	    (tc->tc_offset_nano >> 32) + boottime.tv_usec * 1000;
798	tc->tc_microtime.tv_usec = tc->tc_offset_micro + boottime.tv_usec;
799	if (tc->tc_nanotime.tv_nsec >= 1000000000) {
800		tc->tc_nanotime.tv_nsec -= 1000000000;
801		tc->tc_microtime.tv_usec -= 1000000;
802		tc->tc_nanotime.tv_sec++;
803	}
804	time_second = tc->tc_microtime.tv_sec = tc->tc_nanotime.tv_sec;
805
806	timecounter = tc;
807}
808
809SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
810
811SYSCTL_INT(_kern_timecounter, OID_AUTO, method, CTLFLAG_RW, &tco_method, 0,
812    "This variable determines the method used for updating timecounters. "
813    "If the default algorithm (0) fails with \"calcru negative...\" messages "
814    "try the alternate algorithm (1) which handles bad hardware better."
815
816);
817
818static int
819sysctl_kern_timecounter_hardware SYSCTL_HANDLER_ARGS
820{
821	char newname[32];
822	struct timecounter *newtc, *tc;
823	int error;
824
825	tc = timecounter->tc_tweak;
826	strncpy(newname, tc->tc_name, sizeof(newname));
827	error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
828	if (error == 0 && req->newptr != NULL &&
829	    strcmp(newname, tc->tc_name) != 0) {
830		for (newtc = tc->tc_avail; newtc != tc;
831		    newtc = newtc->tc_avail) {
832			if (strcmp(newname, newtc->tc_name) == 0) {
833				/* Warm up new timecounter. */
834				(void)newtc->tc_get_timecount(newtc);
835
836				switch_timecounter(newtc);
837				return (0);
838			}
839		}
840		return (EINVAL);
841	}
842	return (error);
843}
844
845SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
846    0, 0, sysctl_kern_timecounter_hardware, "A", "");
847
848
849int
850pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
851{
852	pps_params_t *app;
853	struct pps_fetch_args *fapi;
854#ifdef PPS_SYNC
855	struct pps_kcbind_args *kapi;
856#endif
857
858	switch (cmd) {
859	case PPS_IOC_CREATE:
860		return (0);
861	case PPS_IOC_DESTROY:
862		return (0);
863	case PPS_IOC_SETPARAMS:
864		app = (pps_params_t *)data;
865		if (app->mode & ~pps->ppscap)
866			return (EINVAL);
867		pps->ppsparam = *app;
868		return (0);
869	case PPS_IOC_GETPARAMS:
870		app = (pps_params_t *)data;
871		*app = pps->ppsparam;
872		app->api_version = PPS_API_VERS_1;
873		return (0);
874	case PPS_IOC_GETCAP:
875		*(int*)data = pps->ppscap;
876		return (0);
877	case PPS_IOC_FETCH:
878		fapi = (struct pps_fetch_args *)data;
879		if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
880			return (EINVAL);
881		if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
882			return (EOPNOTSUPP);
883		pps->ppsinfo.current_mode = pps->ppsparam.mode;
884		fapi->pps_info_buf = pps->ppsinfo;
885		return (0);
886	case PPS_IOC_KCBIND:
887#ifdef PPS_SYNC
888		kapi = (struct pps_kcbind_args *)data;
889		/* XXX Only root should be able to do this */
890		if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
891			return (EINVAL);
892		if (kapi->kernel_consumer != PPS_KC_HARDPPS)
893			return (EINVAL);
894		if (kapi->edge & ~pps->ppscap)
895			return (EINVAL);
896		pps->kcmode = kapi->edge;
897		return (0);
898#else
899		return (EOPNOTSUPP);
900#endif
901	default:
902		return (ENOTTY);
903	}
904}
905
906void
907pps_init(struct pps_state *pps)
908{
909	pps->ppscap |= PPS_TSFMT_TSPEC;
910	if (pps->ppscap & PPS_CAPTUREASSERT)
911		pps->ppscap |= PPS_OFFSETASSERT;
912	if (pps->ppscap & PPS_CAPTURECLEAR)
913		pps->ppscap |= PPS_OFFSETCLEAR;
914}
915
916void
917pps_event(struct pps_state *pps, struct timecounter *tc, unsigned count, int event)
918{
919	struct timespec ts, *tsp, *osp;
920	u_int64_t delta;
921	unsigned tcount, *pcount;
922	int foff, fhard;
923	pps_seq_t	*pseq;
924
925	/* Things would be easier with arrays... */
926	if (event == PPS_CAPTUREASSERT) {
927		tsp = &pps->ppsinfo.assert_timestamp;
928		osp = &pps->ppsparam.assert_offset;
929		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
930		fhard = pps->kcmode & PPS_CAPTUREASSERT;
931		pcount = &pps->ppscount[0];
932		pseq = &pps->ppsinfo.assert_sequence;
933	} else {
934		tsp = &pps->ppsinfo.clear_timestamp;
935		osp = &pps->ppsparam.clear_offset;
936		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
937		fhard = pps->kcmode & PPS_CAPTURECLEAR;
938		pcount = &pps->ppscount[1];
939		pseq = &pps->ppsinfo.clear_sequence;
940	}
941
942	/* The timecounter changed: bail */
943	if (!pps->ppstc ||
944	    pps->ppstc->tc_name != tc->tc_name ||
945	    tc->tc_name != timecounter->tc_name) {
946		pps->ppstc = tc;
947		*pcount = count;
948		return;
949	}
950
951	/* Nothing really happened */
952	if (*pcount == count)
953		return;
954
955	*pcount = count;
956
957	/* Convert the count to timespec */
958	ts.tv_sec = tc->tc_offset_sec;
959	tcount = count - tc->tc_offset_count;
960	tcount &= tc->tc_counter_mask;
961	delta = tc->tc_offset_nano;
962	delta += ((u_int64_t)tcount * tc->tc_scale_nano_f);
963	delta >>= 32;
964	delta += ((u_int64_t)tcount * tc->tc_scale_nano_i);
965	delta += boottime.tv_usec * 1000;
966	ts.tv_sec += boottime.tv_sec;
967	while (delta >= 1000000000) {
968		delta -= 1000000000;
969		ts.tv_sec++;
970	}
971	ts.tv_nsec = delta;
972
973	(*pseq)++;
974	*tsp = ts;
975
976	if (foff) {
977		timespecadd(tsp, osp);
978		if (tsp->tv_nsec < 0) {
979			tsp->tv_nsec += 1000000000;
980			tsp->tv_sec -= 1;
981		}
982	}
983#ifdef PPS_SYNC
984	if (fhard) {
985		/* magic, at its best... */
986		tcount = count - pps->ppscount[2];
987		pps->ppscount[2] = count;
988		tcount &= tc->tc_counter_mask;
989		delta = ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_f);
990		delta >>= 32;
991		delta += ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_i);
992		hardpps(tsp, delta);
993	}
994#endif
995}
996