kern_clock.c revision 45245
159243Sobrien/*-
259243Sobrien * Copyright (c) 1997, 1998 Poul-Henning Kamp <phk@FreeBSD.org>
359243Sobrien * Copyright (c) 1982, 1986, 1991, 1993
459243Sobrien *	The Regents of the University of California.  All rights reserved.
559243Sobrien * (c) UNIX System Laboratories, Inc.
659243Sobrien * All or some portions of this file are derived from material licensed
759243Sobrien * to the University of California by American Telephone and Telegraph
859243Sobrien * Co. or Unix System Laboratories, Inc. and are reproduced herein with
959243Sobrien * the permission of UNIX System Laboratories, Inc.
1059243Sobrien *
1159243Sobrien * Redistribution and use in source and binary forms, with or without
1259243Sobrien * modification, are permitted provided that the following conditions
1359243Sobrien * are met:
1459243Sobrien * 1. Redistributions of source code must retain the above copyright
1559243Sobrien *    notice, this list of conditions and the following disclaimer.
1659243Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1759243Sobrien *    notice, this list of conditions and the following disclaimer in the
1859243Sobrien *    documentation and/or other materials provided with the distribution.
1959243Sobrien * 3. All advertising materials mentioning features or use of this software
2059243Sobrien *    must display the following acknowledgement:
2159243Sobrien *	This product includes software developed by the University of
2259243Sobrien *	California, Berkeley and its contributors.
2359243Sobrien * 4. Neither the name of the University nor the names of its contributors
2459243Sobrien *    may be used to endorse or promote products derived from this software
2559243Sobrien *    without specific prior written permission.
2659243Sobrien *
2759243Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2859243Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2959243Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3059243Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3159243Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3259243Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3359243Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3459243Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3559243Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3659243Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3759243Sobrien * SUCH DAMAGE.
3859243Sobrien *
3959243Sobrien *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
4059243Sobrien * $Id: kern_clock.c,v 1.92 1999/03/12 21:58:54 phk Exp $
4159243Sobrien */
4259243Sobrien
4359243Sobrien#include "opt_ntp.h"
4459243Sobrien
4559243Sobrien#include <sys/param.h>
4659243Sobrien#include <sys/systm.h>
4759243Sobrien#include <sys/dkstat.h>
4859243Sobrien#include <sys/callout.h>
4959243Sobrien#include <sys/kernel.h>
5059243Sobrien#include <sys/proc.h>
5159243Sobrien#include <sys/malloc.h>
5259243Sobrien#include <sys/resourcevar.h>
5359243Sobrien#include <sys/signalvar.h>
5459243Sobrien#include <sys/timex.h>
5559243Sobrien#include <sys/timepps.h>
5659243Sobrien#include <vm/vm.h>
5759243Sobrien#include <sys/lock.h>
5859243Sobrien#include <vm/pmap.h>
5959243Sobrien#include <vm/vm_map.h>
6059243Sobrien#include <sys/sysctl.h>
6159243Sobrien
6259243Sobrien#include <machine/cpu.h>
6359243Sobrien#include <machine/limits.h>
6459243Sobrien
6559243Sobrien#ifdef GPROF
6659243Sobrien#include <sys/gmon.h>
6759243Sobrien#endif
6859243Sobrien
6959243Sobrien#if defined(SMP) && defined(BETTER_CLOCK)
7059243Sobrien#include <machine/smp.h>
7159243Sobrien#endif
7259243Sobrien
7359243Sobrien/*
7459243Sobrien * Number of timecounters used to implement stable storage
7559243Sobrien */
7659243Sobrien#ifndef NTIMECOUNTER
7759243Sobrien#define NTIMECOUNTER	5
7859243Sobrien#endif
7959243Sobrien
8059243Sobrienstatic MALLOC_DEFINE(M_TIMECOUNTER, "timecounter",
8159243Sobrien	"Timecounter stable storage");
8259243Sobrien
8359243Sobrienstatic void initclocks __P((void *dummy));
8459243SobrienSYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
85195609Smp
8659243Sobrienstatic void tco_forward __P((int force));
8759243Sobrienstatic void tco_setscales __P((struct timecounter *tc));
8859243Sobrienstatic __inline unsigned tco_delta __P((struct timecounter *tc));
8959243Sobrien
9059243Sobrien/* Some of these don't belong here, but it's easiest to concentrate them. */
9159243Sobrien#if defined(SMP) && defined(BETTER_CLOCK)
9259243Sobrienlong cp_time[CPUSTATES];
9359243Sobrien#else
9459243Sobrienstatic long cp_time[CPUSTATES];
9559243Sobrien#endif
9659243Sobrien
9759243Sobrienlong tk_cancc;
9859243Sobrienlong tk_nin;
9959243Sobrienlong tk_nout;
10059243Sobrienlong tk_rawcc;
10159243Sobrien
10259243Sobrientime_t time_second;
10359243Sobrien
10459243Sobrien/*
10559243Sobrien * Which update policy to use.
10659243Sobrien *   0 - every tick, bad hardware may fail with "calcru negative..."
10759243Sobrien *   1 - more resistent to the above hardware, but less efficient.
10859243Sobrien */
10959243Sobrienstatic int tco_method;
11059243Sobrien
11159243Sobrien/*
11259243Sobrien * Implement a dummy timecounter which we can use until we get a real one
11359243Sobrien * in the air.  This allows the console and other early stuff to use
11459243Sobrien * timeservices.
11559243Sobrien */
11659243Sobrien
11759243Sobrienstatic unsigned
11859243Sobriendummy_get_timecount(struct timecounter *tc)
11959243Sobrien{
12059243Sobrien	static unsigned now;
12159243Sobrien	return (++now);
12259243Sobrien}
12359243Sobrien
12459243Sobrienstatic struct timecounter dummy_timecounter = {
12559243Sobrien	dummy_get_timecount,
12659243Sobrien	0,
12759243Sobrien	~0u,
12859243Sobrien	1000000,
12959243Sobrien	"dummy"
13059243Sobrien};
13159243Sobrien
13259243Sobrienstruct timecounter *timecounter = &dummy_timecounter;
13359243Sobrien
13459243Sobrien/*
135167465Smp * Clock handling routines.
136167465Smp *
137167465Smp * This code is written to operate with two timers that run independently of
138195609Smp * each other.
139167465Smp *
140167465Smp * The main timer, running hz times per second, is used to trigger interval
141167465Smp * timers, timeouts and rescheduling as needed.
142167465Smp *
143167465Smp * The second timer handles kernel and user profiling,
144167465Smp * and does resource use estimation.  If the second timer is programmable,
145167465Smp * it is randomized to avoid aliasing between the two clocks.  For example,
146167465Smp * the randomization prevents an adversary from always giving up the cpu
147167465Smp * just before its quantum expires.  Otherwise, it would never accumulate
148167465Smp * cpu ticks.  The mean frequency of the second timer is stathz.
149167465Smp *
150167465Smp * If no second timer exists, stathz will be zero; in this case we drive
15159243Sobrien * profiling and statistics off the main clock.  This WILL NOT be accurate;
15259243Sobrien * do not do it unless absolutely necessary.
15359243Sobrien *
15459243Sobrien * The statistics clock may (or may not) be run at a higher rate while
155167465Smp * profiling.  This profile clock runs at profhz.  We require that profhz
156167465Smp * be an integral multiple of stathz.
15759243Sobrien *
158145479Smp * If the statistics clock is running fast, it must be divided by the ratio
159145479Smp * profhz/stathz for statistics.  (For profiling, every tick counts.)
16059243Sobrien *
16159243Sobrien * Time-of-day is maintained using a "timecounter", which may or may
16259243Sobrien * not be related to the hardware generating the above mentioned
16359243Sobrien * interrupts.
16459243Sobrien */
16559243Sobrien
16659243Sobrienint	stathz;
16759243Sobrienint	profhz;
16859243Sobrienstatic int profprocs;
16959243Sobrienint	ticks;
17059243Sobrienstatic int psdiv, pscnt;		/* prof => stat divider */
17159243Sobrienint	psratio;			/* ratio: prof / stat */
17259243Sobrien
17359243Sobrien/*
17459243Sobrien * Initialize clock frequencies and start both clocks running.
17559243Sobrien */
176195609Smp/* ARGSUSED*/
17759243Sobrienstatic void
17859243Sobrieninitclocks(dummy)
17959243Sobrien	void *dummy;
18059243Sobrien{
18159243Sobrien	register int i;
18259243Sobrien
18359243Sobrien	/*
18459243Sobrien	 * Set divisors to 1 (normal case) and let the machine-specific
18559243Sobrien	 * code do its bit.
18659243Sobrien	 */
18759243Sobrien	psdiv = pscnt = 1;
18859243Sobrien	cpu_initclocks();
18959243Sobrien
19059243Sobrien	/*
19159243Sobrien	 * Compute profhz/stathz, and fix profhz if needed.
19259243Sobrien	 */
19359243Sobrien	i = stathz ? stathz : hz;
19459243Sobrien	if (profhz == 0)
19559243Sobrien		profhz = i;
19659243Sobrien	psratio = profhz / i;
19759243Sobrien}
19859243Sobrien
19959243Sobrien/*
20059243Sobrien * The real-time timer, interrupting hz times per second.
20159243Sobrien */
20259243Sobrienvoid
20359243Sobrienhardclock(frame)
20459243Sobrien	register struct clockframe *frame;
20559243Sobrien{
20659243Sobrien	register struct proc *p;
20759243Sobrien
20859243Sobrien	p = curproc;
20959243Sobrien	if (p) {
21059243Sobrien		register struct pstats *pstats;
21159243Sobrien
21259243Sobrien		/*
21359243Sobrien		 * Run current process's virtual and profile time, as needed.
21459243Sobrien		 */
21559243Sobrien		pstats = p->p_stats;
21659243Sobrien		if (CLKF_USERMODE(frame) &&
21759243Sobrien		    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
21859243Sobrien		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
21959243Sobrien			psignal(p, SIGVTALRM);
22059243Sobrien		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
22159243Sobrien		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
22259243Sobrien			psignal(p, SIGPROF);
22359243Sobrien	}
22459243Sobrien
22559243Sobrien#if defined(SMP) && defined(BETTER_CLOCK)
22659243Sobrien	forward_hardclock(pscnt);
22759243Sobrien#endif
22859243Sobrien
22959243Sobrien	/*
23059243Sobrien	 * If no separate statistics clock is available, run it from here.
23159243Sobrien	 */
232167465Smp	if (stathz == 0)
23359243Sobrien		statclock(frame);
234145479Smp
235145479Smp	tco_forward(0);
236145479Smp	ticks++;
23759243Sobrien
23859243Sobrien	/*
23959243Sobrien	 * Process callouts at a very low cpu priority, so we don't keep the
24059243Sobrien	 * relatively high clock interrupt priority any longer than necessary.
24159243Sobrien	 */
24259243Sobrien	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
24359243Sobrien		if (CLKF_BASEPRI(frame)) {
24459243Sobrien			/*
24559243Sobrien			 * Save the overhead of a software interrupt;
24659243Sobrien			 * it will happen as soon as we return, so do it now.
24759243Sobrien			 */
24859243Sobrien			(void)splsoftclock();
249167465Smp			softclock();
250167465Smp		} else
25159243Sobrien			setsoftclock();
25259243Sobrien	} else if (softticks + 1 == ticks)
25359243Sobrien		++softticks;
25459243Sobrien}
25559243Sobrien
25659243Sobrien/*
25759243Sobrien * Compute number of ticks in the specified amount of time.
25859243Sobrien */
25959243Sobrienint
26059243Sobrientvtohz(tv)
26159243Sobrien	struct timeval *tv;
26259243Sobrien{
26359243Sobrien	register unsigned long ticks;
26459243Sobrien	register long sec, usec;
26559243Sobrien
26659243Sobrien	/*
26759243Sobrien	 * If the number of usecs in the whole seconds part of the time
26859243Sobrien	 * difference fits in a long, then the total number of usecs will
26959243Sobrien	 * fit in an unsigned long.  Compute the total and convert it to
27059243Sobrien	 * ticks, rounding up and adding 1 to allow for the current tick
27159243Sobrien	 * to expire.  Rounding also depends on unsigned long arithmetic
27259243Sobrien	 * to avoid overflow.
27359243Sobrien	 *
27459243Sobrien	 * Otherwise, if the number of ticks in the whole seconds part of
27559243Sobrien	 * the time difference fits in a long, then convert the parts to
27659243Sobrien	 * ticks separately and add, using similar rounding methods and
27759243Sobrien	 * overflow avoidance.  This method would work in the previous
27859243Sobrien	 * case but it is slightly slower and assumes that hz is integral.
27959243Sobrien	 *
28059243Sobrien	 * Otherwise, round the time difference down to the maximum
28159243Sobrien	 * representable value.
28259243Sobrien	 *
28359243Sobrien	 * If ints have 32 bits, then the maximum value for any timeout in
284167465Smp	 * 10ms ticks is 248 days.
28559243Sobrien	 */
286145479Smp	sec = tv->tv_sec;
287145479Smp	usec = tv->tv_usec;
288145479Smp	if (usec < 0) {
28959243Sobrien		sec--;
29059243Sobrien		usec += 1000000;
29159243Sobrien	}
29259243Sobrien	if (sec < 0) {
29359243Sobrien#ifdef DIAGNOSTIC
29459243Sobrien		if (usec > 0) {
29559243Sobrien			sec++;
29659243Sobrien			usec -= 1000000;
29759243Sobrien		}
29859243Sobrien		printf("tvotohz: negative time difference %ld sec %ld usec\n",
29959243Sobrien		       sec, usec);
30059243Sobrien#endif
30159243Sobrien		ticks = 1;
30259243Sobrien	} else if (sec <= LONG_MAX / 1000000)
30359243Sobrien		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
30459243Sobrien			/ tick + 1;
30559243Sobrien	else if (sec <= LONG_MAX / hz)
30659243Sobrien		ticks = sec * hz
30759243Sobrien			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
30859243Sobrien	else
30959243Sobrien		ticks = LONG_MAX;
31059243Sobrien	if (ticks > INT_MAX)
31159243Sobrien		ticks = INT_MAX;
312167465Smp	return ((int)ticks);
31359243Sobrien}
314145479Smp
315145479Smp/*
316145479Smp * Start profiling on a process.
31759243Sobrien *
31859243Sobrien * Kernel profiling passes proc0 which never exits and hence
31959243Sobrien * keeps the profile clock running constantly.
32059243Sobrien */
32159243Sobrienvoid
32259243Sobrienstartprofclock(p)
32359243Sobrien	register struct proc *p;
32459243Sobrien{
32559243Sobrien	int s;
32659243Sobrien
32759243Sobrien	if ((p->p_flag & P_PROFIL) == 0) {
32859243Sobrien		p->p_flag |= P_PROFIL;
32959243Sobrien		if (++profprocs == 1 && stathz != 0) {
33059243Sobrien			s = splstatclock();
33159243Sobrien			psdiv = pscnt = psratio;
33259243Sobrien			setstatclockrate(profhz);
33359243Sobrien			splx(s);
33459243Sobrien		}
33559243Sobrien	}
33659243Sobrien}
33759243Sobrien
33859243Sobrien/*
33959243Sobrien * Stop profiling on a process.
34059243Sobrien */
34159243Sobrienvoid
34259243Sobrienstopprofclock(p)
34359243Sobrien	register struct proc *p;
34459243Sobrien{
345195609Smp	int s;
34659243Sobrien
347145479Smp	if (p->p_flag & P_PROFIL) {
348145479Smp		p->p_flag &= ~P_PROFIL;
349145479Smp		if (--profprocs == 0 && stathz != 0) {
350167465Smp			s = splstatclock();
35159243Sobrien			psdiv = pscnt = 1;
35259243Sobrien			setstatclockrate(stathz);
35359243Sobrien			splx(s);
35459243Sobrien		}
35559243Sobrien	}
35659243Sobrien}
35759243Sobrien
35859243Sobrien/*
35959243Sobrien * Statistics clock.  Grab profile sample, and if divider reaches 0,
36059243Sobrien * do process and kernel statistics.
36159243Sobrien */
36259243Sobrienvoid
36359243Sobrienstatclock(frame)
36459243Sobrien	register struct clockframe *frame;
36559243Sobrien{
36659243Sobrien#ifdef GPROF
36759243Sobrien	register struct gmonparam *g;
36859243Sobrien	int i;
36959243Sobrien#endif
37059243Sobrien	register struct proc *p;
37159243Sobrien	struct pstats *pstats;
37259243Sobrien	long rss;
37359243Sobrien	struct rusage *ru;
37459243Sobrien	struct vmspace *vm;
37559243Sobrien
37659243Sobrien	if (curproc != NULL && CLKF_USERMODE(frame)) {
37759243Sobrien		p = curproc;
37859243Sobrien		if (p->p_flag & P_PROFIL)
37959243Sobrien			addupc_intr(p, CLKF_PC(frame), 1);
38059243Sobrien#if defined(SMP) && defined(BETTER_CLOCK)
38159243Sobrien		if (stathz != 0)
38259243Sobrien			forward_statclock(pscnt);
38359243Sobrien#endif
38459243Sobrien		if (--pscnt > 0)
38559243Sobrien			return;
38659243Sobrien		/*
38759243Sobrien		 * Came from user mode; CPU was in user state.
388167465Smp		 * If this process is being profiled record the tick.
38959243Sobrien		 */
390145479Smp		p->p_uticks++;
391145479Smp		if (p->p_nice > NZERO)
392145479Smp			cp_time[CP_NICE]++;
393167465Smp		else
39459243Sobrien			cp_time[CP_USER]++;
39559243Sobrien	} else {
39659243Sobrien#ifdef GPROF
39759243Sobrien		/*
39859243Sobrien		 * Kernel statistics are just like addupc_intr, only easier.
39959243Sobrien		 */
40059243Sobrien		g = &_gmonparam;
40159243Sobrien		if (g->state == GMON_PROF_ON) {
40259243Sobrien			i = CLKF_PC(frame) - g->lowpc;
40359243Sobrien			if (i < g->textsize) {
40459243Sobrien				i /= HISTFRACTION * sizeof(*g->kcount);
40559243Sobrien				g->kcount[i]++;
40659243Sobrien			}
40759243Sobrien		}
40859243Sobrien#endif
40959243Sobrien#if defined(SMP) && defined(BETTER_CLOCK)
41059243Sobrien		if (stathz != 0)
41159243Sobrien			forward_statclock(pscnt);
412167465Smp#endif
41359243Sobrien		if (--pscnt > 0)
414145479Smp			return;
415145479Smp		/*
41659243Sobrien		 * Came from kernel mode, so we were:
41759243Sobrien		 * - handling an interrupt,
41859243Sobrien		 * - doing syscall or trap work on behalf of the current
41959243Sobrien		 *   user process, or
42059243Sobrien		 * - spinning in the idle loop.
42159243Sobrien		 * Whichever it is, charge the time as appropriate.
42259243Sobrien		 * Note that we charge interrupts to the current process,
42359243Sobrien		 * regardless of whether they are ``for'' that process,
42459243Sobrien		 * so that we know how much of its real time was spent
42559243Sobrien		 * in ``non-process'' (i.e., interrupt) work.
42659243Sobrien		 */
42759243Sobrien		p = curproc;
428167465Smp		if (CLKF_INTR(frame)) {
42959243Sobrien			if (p != NULL)
430145479Smp				p->p_iticks++;
431145479Smp			cp_time[CP_INTR]++;
43259243Sobrien		} else if (p != NULL) {
43359243Sobrien			p->p_sticks++;
43459243Sobrien			cp_time[CP_SYS]++;
43559243Sobrien		} else
43659243Sobrien			cp_time[CP_IDLE]++;
43759243Sobrien	}
438131962Smp	pscnt = psdiv;
439131962Smp
44059243Sobrien	/*
44159243Sobrien	 * We maintain statistics shown by user-level statistics
44259243Sobrien	 * programs:  the amount of time in each cpu state.
44359243Sobrien	 */
444167465Smp
44559243Sobrien	/*
446145479Smp	 * We adjust the priority of the current process.  The priority of
44759243Sobrien	 * a process gets worse as it accumulates CPU time.  The cpu usage
44859243Sobrien	 * estimator (p_estcpu) is increased here.  The formula for computing
44959243Sobrien	 * priorities (in kern_synch.c) will compute a different value each
45059243Sobrien	 * time p_estcpu increases by 4.  The cpu usage estimator ramps up
45159243Sobrien	 * quite quickly when the process is running (linearly), and decays
45259243Sobrien	 * away exponentially, at a rate which is proportionally slower when
453167465Smp	 * the system is busy.  The basic principal is that the system will
45459243Sobrien	 * 90% forget that the process used a lot of CPU time in 5 * loadav
455145479Smp	 * seconds.  This causes the system to favor processes which haven't
456145479Smp	 * run much recently, and to round-robin among other processes.
457167465Smp	 */
45859243Sobrien	if (p != NULL) {
45959243Sobrien		p->p_cpticks++;
46059243Sobrien		if (++p->p_estcpu == 0)
46159243Sobrien			p->p_estcpu--;
46259243Sobrien		if ((p->p_estcpu & 3) == 0) {
46359243Sobrien			resetpriority(p);
46459243Sobrien			if (p->p_priority >= PUSER)
46559243Sobrien				p->p_priority = p->p_usrpri;
46659243Sobrien		}
46759243Sobrien
46859243Sobrien		/* Update resource usage integrals and maximums. */
46959243Sobrien		if ((pstats = p->p_stats) != NULL &&
47059243Sobrien		    (ru = &pstats->p_ru) != NULL &&
47159243Sobrien		    (vm = p->p_vmspace) != NULL) {
47259243Sobrien			ru->ru_ixrss += pgtok(vm->vm_tsize);
47359243Sobrien			ru->ru_idrss += pgtok(vm->vm_dsize);
47459243Sobrien			ru->ru_isrss += pgtok(vm->vm_ssize);
47559243Sobrien			rss = pgtok(vmspace_resident_count(vm));
47659243Sobrien			if (ru->ru_maxrss < rss)
47759243Sobrien				ru->ru_maxrss = rss;
47859243Sobrien        	}
479167465Smp	}
48059243Sobrien}
481145479Smp
482145479Smp/*
48359243Sobrien * Return information about system clocks.
48459243Sobrien */
48559243Sobrienstatic int
48659243Sobriensysctl_kern_clockrate SYSCTL_HANDLER_ARGS
48759243Sobrien{
48859243Sobrien	struct clockinfo clkinfo;
48959243Sobrien	/*
49059243Sobrien	 * Construct clockinfo structure.
49159243Sobrien	 */
49259243Sobrien	clkinfo.hz = hz;
49359243Sobrien	clkinfo.tick = tick;
49459243Sobrien	clkinfo.tickadj = tickadj;
495167465Smp	clkinfo.profhz = profhz;
49659243Sobrien	clkinfo.stathz = stathz ? stathz : hz;
497145479Smp	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
49859243Sobrien}
49959243Sobrien
50059243SobrienSYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
50159243Sobrien	0, 0, sysctl_kern_clockrate, "S,clockinfo","");
50259243Sobrien
50359243Sobrienstatic __inline unsigned
50459243Sobrientco_delta(struct timecounter *tc)
50559243Sobrien{
50659243Sobrien
50759243Sobrien	return ((tc->tc_get_timecount(tc) - tc->tc_offset_count) &
50859243Sobrien	    tc->tc_counter_mask);
50959243Sobrien}
510167465Smp
51159243Sobrien/*
512145479Smp * We have eight functions for looking at the clock, four for
51359243Sobrien * microseconds and four for nanoseconds.  For each there is fast
51459243Sobrien * but less precise version "get{nano|micro}[up]time" which will
51559243Sobrien * return a time which is up to 1/HZ previous to the call, whereas
51659243Sobrien * the raw version "{nano|micro}[up]time" will return a timestamp
51759243Sobrien * which is as precise as possible.  The "up" variants return the
51859243Sobrien * time relative to system boot, these are well suited for time
51959243Sobrien * interval measurements.
52059243Sobrien */
52159243Sobrien
52259243Sobrienvoid
52359243Sobriengetmicrotime(struct timeval *tvp)
52459243Sobrien{
525167465Smp	struct timecounter *tc;
52659243Sobrien
527145479Smp	if (!tco_method) {
528145479Smp		tc = timecounter;
52959243Sobrien		*tvp = tc->tc_microtime;
53059243Sobrien	} else {
53159243Sobrien		microtime(tvp);
53259243Sobrien	}
53359243Sobrien}
53459243Sobrien
53559243Sobrienvoid
53659243Sobriengetnanotime(struct timespec *tsp)
53759243Sobrien{
53859243Sobrien	struct timecounter *tc;
53959243Sobrien
54059243Sobrien	if (!tco_method) {
541167465Smp		tc = timecounter;
54259243Sobrien		*tsp = tc->tc_nanotime;
543145479Smp	} else {
54459243Sobrien		nanotime(tsp);
54559243Sobrien	}
54659243Sobrien}
54759243Sobrien
54859243Sobrienvoid
54959243Sobrienmicrotime(struct timeval *tv)
55059243Sobrien{
55159243Sobrien	struct timecounter *tc;
55259243Sobrien
55359243Sobrien	tc = (struct timecounter *)timecounter;
55459243Sobrien	tv->tv_sec = tc->tc_offset_sec;
55559243Sobrien	tv->tv_usec = tc->tc_offset_micro;
556167465Smp	tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
55759243Sobrien	tv->tv_usec += boottime.tv_usec;
558145479Smp	tv->tv_sec += boottime.tv_sec;
559167465Smp	while (tv->tv_usec >= 1000000) {
56059243Sobrien		tv->tv_usec -= 1000000;
56159243Sobrien		tv->tv_sec++;
56259243Sobrien	}
56359243Sobrien}
56459243Sobrien
56559243Sobrienvoid
56659243Sobriennanotime(struct timespec *ts)
56759243Sobrien{
56859243Sobrien	unsigned count;
56959243Sobrien	u_int64_t delta;
57059243Sobrien	struct timecounter *tc;
57159243Sobrien
57259243Sobrien	tc = (struct timecounter *)timecounter;
57359243Sobrien	ts->tv_sec = tc->tc_offset_sec;
57459243Sobrien	count = tco_delta(tc);
57559243Sobrien	delta = tc->tc_offset_nano;
57659243Sobrien	delta += ((u_int64_t)count * tc->tc_scale_nano_f);
577167465Smp	delta >>= 32;
57859243Sobrien	delta += ((u_int64_t)count * tc->tc_scale_nano_i);
579145479Smp	delta += boottime.tv_usec * 1000;
580145479Smp	ts->tv_sec += boottime.tv_sec;
581167465Smp	while (delta >= 1000000000) {
58259243Sobrien		delta -= 1000000000;
58359243Sobrien		ts->tv_sec++;
58459243Sobrien	}
58559243Sobrien	ts->tv_nsec = delta;
58659243Sobrien}
58759243Sobrien
58859243Sobrienvoid
58959243Sobriengetmicrouptime(struct timeval *tvp)
59059243Sobrien{
59159243Sobrien	struct timecounter *tc;
59259243Sobrien
59359243Sobrien	if (!tco_method) {
59459243Sobrien		tc = timecounter;
595		tvp->tv_sec = tc->tc_offset_sec;
596		tvp->tv_usec = tc->tc_offset_micro;
597	} else {
598		microuptime(tvp);
599	}
600}
601
602void
603getnanouptime(struct timespec *tsp)
604{
605	struct timecounter *tc;
606
607	if (!tco_method) {
608		tc = timecounter;
609		tsp->tv_sec = tc->tc_offset_sec;
610		tsp->tv_nsec = tc->tc_offset_nano >> 32;
611	} else {
612		nanouptime(tsp);
613	}
614}
615
616void
617microuptime(struct timeval *tv)
618{
619	struct timecounter *tc;
620
621	tc = (struct timecounter *)timecounter;
622	tv->tv_sec = tc->tc_offset_sec;
623	tv->tv_usec = tc->tc_offset_micro;
624	tv->tv_usec += ((u_int64_t)tco_delta(tc) * tc->tc_scale_micro) >> 32;
625	if (tv->tv_usec >= 1000000) {
626		tv->tv_usec -= 1000000;
627		tv->tv_sec++;
628	}
629}
630
631void
632nanouptime(struct timespec *ts)
633{
634	unsigned count;
635	u_int64_t delta;
636	struct timecounter *tc;
637
638	tc = (struct timecounter *)timecounter;
639	ts->tv_sec = tc->tc_offset_sec;
640	count = tco_delta(tc);
641	delta = tc->tc_offset_nano;
642	delta += ((u_int64_t)count * tc->tc_scale_nano_f);
643	delta >>= 32;
644	delta += ((u_int64_t)count * tc->tc_scale_nano_i);
645	if (delta >= 1000000000) {
646		delta -= 1000000000;
647		ts->tv_sec++;
648	}
649	ts->tv_nsec = delta;
650}
651
652static void
653tco_setscales(struct timecounter *tc)
654{
655	u_int64_t scale;
656
657	scale = 1000000000LL << 32;
658	scale += tc->tc_adjustment;
659	scale /= tc->tc_frequency;
660	tc->tc_scale_micro = scale / 1000;
661	tc->tc_scale_nano_f = scale & 0xffffffff;
662	tc->tc_scale_nano_i = scale >> 32;
663}
664
665void
666init_timecounter(struct timecounter *tc)
667{
668	struct timespec ts1;
669	struct timecounter *t1, *t2, *t3;
670	int i;
671
672	tc->tc_adjustment = 0;
673	tco_setscales(tc);
674	tc->tc_offset_count = tc->tc_get_timecount(tc);
675	tc->tc_tweak = tc;
676	MALLOC(t1, struct timecounter *, sizeof *t1, M_TIMECOUNTER, M_WAITOK);
677	*t1 = *tc;
678	t2 = t1;
679	for (i = 1; i < NTIMECOUNTER; i++) {
680		MALLOC(t3, struct timecounter *, sizeof *t3,
681		    M_TIMECOUNTER, M_WAITOK);
682		*t3 = *tc;
683		t3->tc_other = t2;
684		t2 = t3;
685	}
686	t1->tc_other = t3;
687	tc = t1;
688
689	printf("Timecounter \"%s\"  frequency %lu Hz\n",
690	    tc->tc_name, (u_long)tc->tc_frequency);
691
692	/* XXX: For now always start using the counter. */
693	tc->tc_offset_count = tc->tc_get_timecount(tc);
694	nanouptime(&ts1);
695	tc->tc_offset_nano = (u_int64_t)ts1.tv_nsec << 32;
696	tc->tc_offset_micro = ts1.tv_nsec / 1000;
697	tc->tc_offset_sec = ts1.tv_sec;
698	timecounter = tc;
699}
700
701void
702set_timecounter(struct timespec *ts)
703{
704	struct timespec ts2;
705
706	nanouptime(&ts2);
707	boottime.tv_sec = ts->tv_sec - ts2.tv_sec;
708	boottime.tv_usec = (ts->tv_nsec - ts2.tv_nsec) / 1000;
709	if (boottime.tv_usec < 0) {
710		boottime.tv_usec += 1000000;
711		boottime.tv_sec--;
712	}
713	/* fiddle all the little crinkly bits around the fiords... */
714	tco_forward(1);
715}
716
717
718#if 0 /* Currently unused */
719void
720switch_timecounter(struct timecounter *newtc)
721{
722	int s;
723	struct timecounter *tc;
724	struct timespec ts;
725
726	s = splclock();
727	tc = timecounter;
728	if (newtc == tc || newtc == tc->tc_other) {
729		splx(s);
730		return;
731	}
732	nanouptime(&ts);
733	newtc->tc_offset_sec = ts.tv_sec;
734	newtc->tc_offset_nano = (u_int64_t)ts.tv_nsec << 32;
735	newtc->tc_offset_micro = ts.tv_nsec / 1000;
736	newtc->tc_offset_count = newtc->tc_get_timecount(newtc);
737	timecounter = newtc;
738	splx(s);
739}
740#endif
741
742static struct timecounter *
743sync_other_counter(void)
744{
745	struct timecounter *tc, *tcn, *tco;
746	unsigned delta;
747
748	tco = timecounter;
749	tc = tco->tc_other;
750	tcn = tc->tc_other;
751	*tc = *tco;
752	tc->tc_other = tcn;
753	delta = tco_delta(tc);
754	tc->tc_offset_count += delta;
755	tc->tc_offset_count &= tc->tc_counter_mask;
756	tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_f;
757	tc->tc_offset_nano += (u_int64_t)delta * tc->tc_scale_nano_i << 32;
758	return (tc);
759}
760
761static void
762tco_forward(int force)
763{
764	struct timecounter *tc, *tco;
765
766	tco = timecounter;
767	tc = sync_other_counter();
768	/*
769	 * We may be inducing a tiny error here, the tc_poll_pps() may
770	 * process a latched count which happens after the tco_delta()
771	 * in sync_other_counter(), which would extend the previous
772	 * counters parameters into the domain of this new one.
773	 * Since the timewindow is very small for this, the error is
774	 * going to be only a few weenieseconds (as Dave Mills would
775	 * say), so lets just not talk more about it, OK ?
776	 */
777	if (tco->tc_poll_pps)
778		tco->tc_poll_pps(tco);
779	if (timedelta != 0) {
780		tc->tc_offset_nano += (u_int64_t)(tickdelta * 1000) << 32;
781		timedelta -= tickdelta;
782		force++;
783	}
784
785	while (tc->tc_offset_nano >= 1000000000ULL << 32) {
786		tc->tc_offset_nano -= 1000000000ULL << 32;
787		tc->tc_offset_sec++;
788		ntp_update_second(tc);	/* XXX only needed if xntpd runs */
789		tco_setscales(tc);
790		force++;
791	}
792
793	if (tco_method && !force)
794		return;
795
796	tc->tc_offset_micro = (tc->tc_offset_nano / 1000) >> 32;
797
798	/* Figure out the wall-clock time */
799	tc->tc_nanotime.tv_sec = tc->tc_offset_sec + boottime.tv_sec;
800	tc->tc_nanotime.tv_nsec =
801	    (tc->tc_offset_nano >> 32) + boottime.tv_usec * 1000;
802	tc->tc_microtime.tv_usec = tc->tc_offset_micro + boottime.tv_usec;
803	if (tc->tc_nanotime.tv_nsec >= 1000000000) {
804		tc->tc_nanotime.tv_nsec -= 1000000000;
805		tc->tc_microtime.tv_usec -= 1000000;
806		tc->tc_nanotime.tv_sec++;
807	}
808	time_second = tc->tc_microtime.tv_sec = tc->tc_nanotime.tv_sec;
809
810	timecounter = tc;
811}
812
813SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
814
815SYSCTL_INT(_kern_timecounter, OID_AUTO, method, CTLFLAG_RW, &tco_method, 0,
816    "This variable determines the method used for updating timecounters. "
817    "If the default algorithm (0) fails with \"calcru negative...\" messages "
818    "try the alternate algorithm (1) which handles bad hardware better."
819
820);
821
822
823int
824pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
825{
826        pps_params_t *app;
827        pps_info_t *api;
828
829        switch (cmd) {
830        case PPS_IOC_CREATE:
831                return (0);
832        case PPS_IOC_DESTROY:
833                return (0);
834        case PPS_IOC_SETPARAMS:
835                app = (pps_params_t *)data;
836                if (app->mode & ~pps->ppscap)
837                        return (EINVAL);
838                pps->ppsparam = *app;
839                return (0);
840        case PPS_IOC_GETPARAMS:
841                app = (pps_params_t *)data;
842                *app = pps->ppsparam;
843                return (0);
844        case PPS_IOC_GETCAP:
845                *(int*)data = pps->ppscap;
846                return (0);
847        case PPS_IOC_FETCH:
848                api = (pps_info_t *)data;
849                pps->ppsinfo.current_mode = pps->ppsparam.mode;
850                *api = pps->ppsinfo;
851                return (0);
852        case PPS_IOC_WAIT:
853                return (EOPNOTSUPP);
854        default:
855                return (ENOTTY);
856        }
857}
858
859void
860pps_init(struct pps_state *pps)
861{
862	pps->ppscap |= PPS_TSFMT_TSPEC;
863	if (pps->ppscap & PPS_CAPTUREASSERT)
864		pps->ppscap |= PPS_OFFSETASSERT;
865	if (pps->ppscap & PPS_CAPTURECLEAR)
866		pps->ppscap |= PPS_OFFSETCLEAR;
867#ifdef PPS_SYNC
868	if (pps->ppscap & PPS_CAPTUREASSERT)
869		pps->ppscap |= PPS_HARDPPSONASSERT;
870	if (pps->ppscap & PPS_CAPTURECLEAR)
871		pps->ppscap |= PPS_HARDPPSONCLEAR;
872#endif
873}
874
875void
876pps_event(struct pps_state *pps, struct timecounter *tc, unsigned count, int event)
877{
878	struct timespec ts, *tsp, *osp;
879	u_int64_t delta;
880	unsigned tcount, *pcount;
881	int foff, fhard;
882	pps_seq_t	*pseq;
883
884	/* Things would be easier with arrays... */
885	if (event == PPS_CAPTUREASSERT) {
886		tsp = &pps->ppsinfo.assert_timestamp;
887		osp = &pps->ppsparam.assert_offset;
888		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
889		fhard = pps->ppsparam.mode & PPS_HARDPPSONASSERT;
890		pcount = &pps->ppscount[0];
891		pseq = &pps->ppsinfo.assert_sequence;
892	} else {
893		tsp = &pps->ppsinfo.clear_timestamp;
894		osp = &pps->ppsparam.clear_offset;
895		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
896		fhard = pps->ppsparam.mode & PPS_HARDPPSONCLEAR;
897		pcount = &pps->ppscount[1];
898		pseq = &pps->ppsinfo.clear_sequence;
899	}
900
901	/* The timecounter changed: bail */
902	if (!pps->ppstc ||
903	    pps->ppstc->tc_name != tc->tc_name ||
904	    tc->tc_name != timecounter->tc_name) {
905		pps->ppstc = tc;
906		*pcount = count;
907		return;
908	}
909
910	/* Nothing really happened */
911	if (*pcount == count)
912		return;
913
914	*pcount = count;
915
916	/* Convert the count to timespec */
917	ts.tv_sec = tc->tc_offset_sec;
918	tcount = count - tc->tc_offset_count;
919	tcount &= tc->tc_counter_mask;
920	delta = tc->tc_offset_nano;
921	delta += ((u_int64_t)tcount * tc->tc_scale_nano_f);
922	delta >>= 32;
923	delta += ((u_int64_t)tcount * tc->tc_scale_nano_i);
924	delta += boottime.tv_usec * 1000;
925	ts.tv_sec += boottime.tv_sec;
926	while (delta >= 1000000000) {
927		delta -= 1000000000;
928		ts.tv_sec++;
929	}
930	ts.tv_nsec = delta;
931
932	(*pseq)++;
933	*tsp = ts;
934
935	if (foff) {
936		timespecadd(tsp, osp);
937		if (tsp->tv_nsec < 0) {
938			tsp->tv_nsec += 1000000000;
939			tsp->tv_sec -= 1;
940		}
941	}
942#ifdef PPS_SYNC
943	if (fhard) {
944		/* magic, at its best... */
945		tcount = count - pps->ppscount[2];
946		pps->ppscount[2] = count;
947		tcount &= tc->tc_counter_mask;
948		delta = ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_f);
949		delta >>= 32;
950		delta += ((u_int64_t)tcount * tc->tc_tweak->tc_scale_nano_i);
951		hardpps(tsp, delta);
952	}
953#endif
954}
955
956