xref: /dflybsd-src/sys/kern/kern_clock.c (revision 45be1c61ffc4ced70f698da62c2f88fe6792f339)
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * Copyright (c) 1997, 1998 Poul-Henning Kamp <phk@FreeBSD.org>
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  * (c) UNIX System Laboratories, Inc.
38  * All or some portions of this file are derived from material licensed
39  * to the University of California by American Telephone and Telegraph
40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41  * the permission of UNIX System Laboratories, Inc.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  *
67  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
68  * $FreeBSD: src/sys/kern/kern_clock.c,v 1.105.2.10 2002/10/17 13:19:40 maxim Exp $
69  */
70 
71 #include "opt_ntp.h"
72 #include "opt_ifpoll.h"
73 #include "opt_pctrack.h"
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/callout.h>
78 #include <sys/kernel.h>
79 #include <sys/kinfo.h>
80 #include <sys/proc.h>
81 #include <sys/malloc.h>
82 #include <sys/resource.h>
83 #include <sys/resourcevar.h>
84 #include <sys/signalvar.h>
85 #include <sys/timex.h>
86 #include <sys/timepps.h>
87 #include <vm/vm.h>
88 #include <sys/lock.h>
89 #include <vm/pmap.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_extern.h>
92 #include <sys/sysctl.h>
93 
94 #include <sys/thread2.h>
95 #include <sys/mplock2.h>
96 
97 #include <machine/cpu.h>
98 #include <machine/limits.h>
99 #include <machine/smp.h>
100 #include <machine/cpufunc.h>
101 #include <machine/specialreg.h>
102 #include <machine/clock.h>
103 
104 #ifdef GPROF
105 #include <sys/gmon.h>
106 #endif
107 
108 #ifdef IFPOLL_ENABLE
109 extern void ifpoll_init_pcpu(int);
110 #endif
111 
112 #ifdef DEBUG_PCTRACK
113 static void do_pctrack(struct intrframe *frame, int which);
114 #endif
115 
116 static void initclocks (void *dummy);
117 SYSINIT(clocks, SI_BOOT2_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
118 
119 /*
120  * Some of these don't belong here, but it's easiest to concentrate them.
121  * Note that cpu_time counts in microseconds, but most userland programs
122  * just compare relative times against the total by delta.
123  */
124 struct kinfo_cputime cputime_percpu[MAXCPU];
125 #ifdef DEBUG_PCTRACK
126 struct kinfo_pcheader cputime_pcheader = { PCTRACK_SIZE, PCTRACK_ARYSIZE };
127 struct kinfo_pctrack cputime_pctrack[MAXCPU][PCTRACK_SIZE];
128 #endif
129 
130 static int
131 sysctl_cputime(SYSCTL_HANDLER_ARGS)
132 {
133 	int cpu, error = 0;
134 	size_t size = sizeof(struct kinfo_cputime);
135 
136 	for (cpu = 0; cpu < ncpus; ++cpu) {
137 		if ((error = SYSCTL_OUT(req, &cputime_percpu[cpu], size)))
138 			break;
139 	}
140 
141 	return (error);
142 }
143 SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
144 	sysctl_cputime, "S,kinfo_cputime", "CPU time statistics");
145 
146 static int
147 sysctl_cp_time(SYSCTL_HANDLER_ARGS)
148 {
149 	long cpu_states[5] = {0};
150 	int cpu, error = 0;
151 	size_t size = sizeof(cpu_states);
152 
153 	for (cpu = 0; cpu < ncpus; ++cpu) {
154 		cpu_states[CP_USER] += cputime_percpu[cpu].cp_user;
155 		cpu_states[CP_NICE] += cputime_percpu[cpu].cp_nice;
156 		cpu_states[CP_SYS] += cputime_percpu[cpu].cp_sys;
157 		cpu_states[CP_INTR] += cputime_percpu[cpu].cp_intr;
158 		cpu_states[CP_IDLE] += cputime_percpu[cpu].cp_idle;
159 	}
160 
161 	error = SYSCTL_OUT(req, cpu_states, size);
162 
163 	return (error);
164 }
165 
166 SYSCTL_PROC(_kern, OID_AUTO, cp_time, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
167 	sysctl_cp_time, "LU", "CPU time statistics");
168 
169 /*
170  * boottime is used to calculate the 'real' uptime.  Do not confuse this with
171  * microuptime().  microtime() is not drift compensated.  The real uptime
172  * with compensation is nanotime() - bootime.  boottime is recalculated
173  * whenever the real time is set based on the compensated elapsed time
174  * in seconds (gd->gd_time_seconds).
175  *
176  * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
177  * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
178  * the real time.
179  */
180 struct timespec boottime;	/* boot time (realtime) for reference only */
181 time_t time_second;		/* read-only 'passive' uptime in seconds */
182 time_t time_uptime;		/* read-only 'passive' uptime in seconds */
183 
184 /*
185  * basetime is used to calculate the compensated real time of day.  The
186  * basetime can be modified on a per-tick basis by the adjtime(),
187  * ntp_adjtime(), and sysctl-based time correction APIs.
188  *
189  * Note that frequency corrections can also be made by adjusting
190  * gd_cpuclock_base.
191  *
192  * basetime is a tail-chasing FIFO, updated only by cpu #0.  The FIFO is
193  * used on both SMP and UP systems to avoid MP races between cpu's and
194  * interrupt races on UP systems.
195  */
196 #define BASETIME_ARYSIZE	16
197 #define BASETIME_ARYMASK	(BASETIME_ARYSIZE - 1)
198 static struct timespec basetime[BASETIME_ARYSIZE];
199 static volatile int basetime_index;
200 
201 static int
202 sysctl_get_basetime(SYSCTL_HANDLER_ARGS)
203 {
204 	struct timespec *bt;
205 	int error;
206 	int index;
207 
208 	/*
209 	 * Because basetime data and index may be updated by another cpu,
210 	 * a load fence is required to ensure that the data we read has
211 	 * not been speculatively read relative to a possibly updated index.
212 	 */
213 	index = basetime_index;
214 	cpu_lfence();
215 	bt = &basetime[index];
216 	error = SYSCTL_OUT(req, bt, sizeof(*bt));
217 	return (error);
218 }
219 
220 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
221     &boottime, timespec, "System boottime");
222 SYSCTL_PROC(_kern, OID_AUTO, basetime, CTLTYPE_STRUCT|CTLFLAG_RD, 0, 0,
223     sysctl_get_basetime, "S,timespec", "System basetime");
224 
225 static void hardclock(systimer_t info, int, struct intrframe *frame);
226 static void statclock(systimer_t info, int, struct intrframe *frame);
227 static void schedclock(systimer_t info, int, struct intrframe *frame);
228 static void getnanotime_nbt(struct timespec *nbt, struct timespec *tsp);
229 
230 int	ticks;			/* system master ticks at hz */
231 int	clocks_running;		/* tsleep/timeout clocks operational */
232 int64_t	nsec_adj;		/* ntpd per-tick adjustment in nsec << 32 */
233 int64_t	nsec_acc;		/* accumulator */
234 int	sched_ticks;		/* global schedule clock ticks */
235 
236 /* NTPD time correction fields */
237 int64_t	ntp_tick_permanent;	/* per-tick adjustment in nsec << 32 */
238 int64_t	ntp_tick_acc;		/* accumulator for per-tick adjustment */
239 int64_t	ntp_delta;		/* one-time correction in nsec */
240 int64_t ntp_big_delta = 1000000000;
241 int32_t	ntp_tick_delta;		/* current adjustment rate */
242 int32_t	ntp_default_tick_delta;	/* adjustment rate for ntp_delta */
243 time_t	ntp_leap_second;	/* time of next leap second */
244 int	ntp_leap_insert;	/* whether to insert or remove a second */
245 
246 /*
247  * Finish initializing clock frequencies and start all clocks running.
248  */
249 /* ARGSUSED*/
250 static void
251 initclocks(void *dummy)
252 {
253 	/*psratio = profhz / stathz;*/
254 	initclocks_pcpu();
255 	clocks_running = 1;
256 }
257 
258 /*
259  * Called on a per-cpu basis from the idle thread bootstrap on each cpu
260  * during SMP initialization.
261  *
262  * This routine is called concurrently during low-level SMP initialization
263  * and may not block in any way.  Meaning, among other things, we can't
264  * acquire any tokens.
265  */
266 void
267 initclocks_pcpu(void)
268 {
269 	struct globaldata *gd = mycpu;
270 
271 	crit_enter();
272 	if (gd->gd_cpuid == 0) {
273 	    gd->gd_time_seconds = 1;
274 	    gd->gd_cpuclock_base = sys_cputimer->count();
275 	} else {
276 	    /* XXX */
277 	    gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
278 	    gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
279 	}
280 
281 	systimer_intr_enable();
282 
283 	crit_exit();
284 }
285 
286 /*
287  * This routine is called on just the BSP, just after SMP initialization
288  * completes to * finish initializing any clocks that might contend/block
289  * (e.g. like on a token).  We can't do this in initclocks_pcpu() because
290  * that function is called from the idle thread bootstrap for each cpu and
291  * not allowed to block at all.
292  */
293 static
294 void
295 initclocks_other(void *dummy)
296 {
297 	struct globaldata *ogd = mycpu;
298 	struct globaldata *gd;
299 	int n;
300 
301 	for (n = 0; n < ncpus; ++n) {
302 		lwkt_setcpu_self(globaldata_find(n));
303 		gd = mycpu;
304 
305 		/*
306 		 * Use a non-queued periodic systimer to prevent multiple
307 		 * ticks from building up if the sysclock jumps forward
308 		 * (8254 gets reset).  The sysclock will never jump backwards.
309 		 * Our time sync is based on the actual sysclock, not the
310 		 * ticks count.
311 		 */
312 		systimer_init_periodic_nq(&gd->gd_hardclock, hardclock,
313 					  NULL, hz);
314 		systimer_init_periodic_nq(&gd->gd_statclock, statclock,
315 					  NULL, stathz);
316 		/* XXX correct the frequency for scheduler / estcpu tests */
317 		systimer_init_periodic_nq(&gd->gd_schedclock, schedclock,
318 					  NULL, ESTCPUFREQ);
319 #ifdef IFPOLL_ENABLE
320 		ifpoll_init_pcpu(gd->gd_cpuid);
321 #endif
322 	}
323 	lwkt_setcpu_self(ogd);
324 }
325 SYSINIT(clocks2, SI_BOOT2_POST_SMP, SI_ORDER_ANY, initclocks_other, NULL)
326 
327 /*
328  * This sets the current real time of day.  Timespecs are in seconds and
329  * nanoseconds.  We do not mess with gd_time_seconds and gd_cpuclock_base,
330  * instead we adjust basetime so basetime + gd_* results in the current
331  * time of day.  This way the gd_* fields are guarenteed to represent
332  * a monotonically increasing 'uptime' value.
333  *
334  * When set_timeofday() is called from userland, the system call forces it
335  * onto cpu #0 since only cpu #0 can update basetime_index.
336  */
337 void
338 set_timeofday(struct timespec *ts)
339 {
340 	struct timespec *nbt;
341 	int ni;
342 
343 	/*
344 	 * XXX SMP / non-atomic basetime updates
345 	 */
346 	crit_enter();
347 	ni = (basetime_index + 1) & BASETIME_ARYMASK;
348 	nbt = &basetime[ni];
349 	nanouptime(nbt);
350 	nbt->tv_sec = ts->tv_sec - nbt->tv_sec;
351 	nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec;
352 	if (nbt->tv_nsec < 0) {
353 	    nbt->tv_nsec += 1000000000;
354 	    --nbt->tv_sec;
355 	}
356 
357 	/*
358 	 * Note that basetime diverges from boottime as the clock drift is
359 	 * compensated for, so we cannot do away with boottime.  When setting
360 	 * the absolute time of day the drift is 0 (for an instant) and we
361 	 * can simply assign boottime to basetime.
362 	 *
363 	 * Note that nanouptime() is based on gd_time_seconds which is drift
364 	 * compensated up to a point (it is guarenteed to remain monotonically
365 	 * increasing).  gd_time_seconds is thus our best uptime guess and
366 	 * suitable for use in the boottime calculation.  It is already taken
367 	 * into account in the basetime calculation above.
368 	 */
369 	boottime.tv_sec = nbt->tv_sec;
370 	ntp_delta = 0;
371 
372 	/*
373 	 * We now have a new basetime, make sure all other cpus have it,
374 	 * then update the index.
375 	 */
376 	cpu_sfence();
377 	basetime_index = ni;
378 
379 	crit_exit();
380 }
381 
382 /*
383  * Each cpu has its own hardclock, but we only increments ticks and softticks
384  * on cpu #0.
385  *
386  * NOTE! systimer! the MP lock might not be held here.  We can only safely
387  * manipulate objects owned by the current cpu.
388  */
389 static void
390 hardclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
391 {
392 	sysclock_t cputicks;
393 	struct proc *p;
394 	struct globaldata *gd = mycpu;
395 
396 	/*
397 	 * Realtime updates are per-cpu.  Note that timer corrections as
398 	 * returned by microtime() and friends make an additional adjustment
399 	 * using a system-wise 'basetime', but the running time is always
400 	 * taken from the per-cpu globaldata area.  Since the same clock
401 	 * is distributing (XXX SMP) to all cpus, the per-cpu timebases
402 	 * stay in synch.
403 	 *
404 	 * Note that we never allow info->time (aka gd->gd_hardclock.time)
405 	 * to reverse index gd_cpuclock_base, but that it is possible for
406 	 * it to temporarily get behind in the seconds if something in the
407 	 * system locks interrupts for a long period of time.  Since periodic
408 	 * timers count events, though everything should resynch again
409 	 * immediately.
410 	 */
411 	cputicks = info->time - gd->gd_cpuclock_base;
412 	if (cputicks >= sys_cputimer->freq) {
413 		++gd->gd_time_seconds;
414 		gd->gd_cpuclock_base += sys_cputimer->freq;
415 		if (gd->gd_cpuid == 0)
416 			++time_uptime;	/* uncorrected monotonic 1-sec gran */
417 	}
418 
419 	/*
420 	 * The system-wide ticks counter and NTP related timedelta/tickdelta
421 	 * adjustments only occur on cpu #0.  NTP adjustments are accomplished
422 	 * by updating basetime.
423 	 */
424 	if (gd->gd_cpuid == 0) {
425 	    struct timespec *nbt;
426 	    struct timespec nts;
427 	    int leap;
428 	    int ni;
429 
430 	    ++ticks;
431 
432 #if 0
433 	    if (tco->tc_poll_pps)
434 		tco->tc_poll_pps(tco);
435 #endif
436 
437 	    /*
438 	     * Calculate the new basetime index.  We are in a critical section
439 	     * on cpu #0 and can safely play with basetime_index.  Start
440 	     * with the current basetime and then make adjustments.
441 	     */
442 	    ni = (basetime_index + 1) & BASETIME_ARYMASK;
443 	    nbt = &basetime[ni];
444 	    *nbt = basetime[basetime_index];
445 
446 	    /*
447 	     * Apply adjtime corrections.  (adjtime() API)
448 	     *
449 	     * adjtime() only runs on cpu #0 so our critical section is
450 	     * sufficient to access these variables.
451 	     */
452 	    if (ntp_delta != 0) {
453 		nbt->tv_nsec += ntp_tick_delta;
454 		ntp_delta -= ntp_tick_delta;
455 		if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) ||
456 		    (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) {
457 			ntp_tick_delta = ntp_delta;
458  		}
459  	    }
460 
461 	    /*
462 	     * Apply permanent frequency corrections.  (sysctl API)
463 	     */
464 	    if (ntp_tick_permanent != 0) {
465 		ntp_tick_acc += ntp_tick_permanent;
466 		if (ntp_tick_acc >= (1LL << 32)) {
467 		    nbt->tv_nsec += ntp_tick_acc >> 32;
468 		    ntp_tick_acc -= (ntp_tick_acc >> 32) << 32;
469 		} else if (ntp_tick_acc <= -(1LL << 32)) {
470 		    /* Negate ntp_tick_acc to avoid shifting the sign bit. */
471 		    nbt->tv_nsec -= (-ntp_tick_acc) >> 32;
472 		    ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32;
473 		}
474  	    }
475 
476 	    if (nbt->tv_nsec >= 1000000000) {
477 		    nbt->tv_sec++;
478 		    nbt->tv_nsec -= 1000000000;
479 	    } else if (nbt->tv_nsec < 0) {
480 		    nbt->tv_sec--;
481 		    nbt->tv_nsec += 1000000000;
482 	    }
483 
484 	    /*
485 	     * Another per-tick compensation.  (for ntp_adjtime() API)
486 	     */
487 	    if (nsec_adj != 0) {
488 		nsec_acc += nsec_adj;
489 		if (nsec_acc >= 0x100000000LL) {
490 		    nbt->tv_nsec += nsec_acc >> 32;
491 		    nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
492 		} else if (nsec_acc <= -0x100000000LL) {
493 		    nbt->tv_nsec -= -nsec_acc >> 32;
494 		    nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
495 		}
496 		if (nbt->tv_nsec >= 1000000000) {
497 		    nbt->tv_nsec -= 1000000000;
498 		    ++nbt->tv_sec;
499 		} else if (nbt->tv_nsec < 0) {
500 		    nbt->tv_nsec += 1000000000;
501 		    --nbt->tv_sec;
502 		}
503 	    }
504 
505 	    /************************************************************
506 	     *			LEAP SECOND CORRECTION			*
507 	     ************************************************************
508 	     *
509 	     * Taking into account all the corrections made above, figure
510 	     * out the new real time.  If the seconds field has changed
511 	     * then apply any pending leap-second corrections.
512 	     */
513 	    getnanotime_nbt(nbt, &nts);
514 
515 	    if (time_second != nts.tv_sec) {
516 		/*
517 		 * Apply leap second (sysctl API).  Adjust nts for changes
518 		 * so we do not have to call getnanotime_nbt again.
519 		 */
520 		if (ntp_leap_second) {
521 		    if (ntp_leap_second == nts.tv_sec) {
522 			if (ntp_leap_insert) {
523 			    nbt->tv_sec++;
524 			    nts.tv_sec++;
525 			} else {
526 			    nbt->tv_sec--;
527 			    nts.tv_sec--;
528 			}
529 			ntp_leap_second--;
530 		    }
531 		}
532 
533 		/*
534 		 * Apply leap second (ntp_adjtime() API), calculate a new
535 		 * nsec_adj field.  ntp_update_second() returns nsec_adj
536 		 * as a per-second value but we need it as a per-tick value.
537 		 */
538 		leap = ntp_update_second(time_second, &nsec_adj);
539 		nsec_adj /= hz;
540 		nbt->tv_sec += leap;
541 		nts.tv_sec += leap;
542 
543 		/*
544 		 * Update the time_second 'approximate time' global.
545 		 */
546 		time_second = nts.tv_sec;
547 	    }
548 
549 	    /*
550 	     * Finally, our new basetime is ready to go live!
551 	     */
552 	    cpu_sfence();
553 	    basetime_index = ni;
554 	}
555 
556 	/*
557 	 * lwkt thread scheduler fair queueing
558 	 */
559 	lwkt_schedulerclock(curthread);
560 
561 	/*
562 	 * softticks are handled for all cpus
563 	 */
564 	hardclock_softtick(gd);
565 
566 	/*
567 	 * ITimer handling is per-tick, per-cpu.
568 	 *
569 	 * We must acquire the per-process token in order for ksignal()
570 	 * to be non-blocking.  For the moment this requires an AST fault,
571 	 * the ksignal() cannot be safely issued from this hard interrupt.
572 	 *
573 	 * XXX Even the trytoken here isn't right, and itimer operation in
574 	 *     a multi threaded environment is going to be weird at the
575 	 *     very least.
576 	 */
577 	if ((p = curproc) != NULL && lwkt_trytoken(&p->p_token)) {
578 		crit_enter_hard();
579 		if (frame && CLKF_USERMODE(frame) &&
580 		    timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) &&
581 		    itimerdecr(&p->p_timer[ITIMER_VIRTUAL], ustick) == 0) {
582 			p->p_flags |= P_SIGVTALRM;
583 			need_user_resched();
584 		}
585 		if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) &&
586 		    itimerdecr(&p->p_timer[ITIMER_PROF], ustick) == 0) {
587 			p->p_flags |= P_SIGPROF;
588 			need_user_resched();
589 		}
590 		crit_exit_hard();
591 		lwkt_reltoken(&p->p_token);
592 	}
593 	setdelayed();
594 }
595 
596 /*
597  * The statistics clock typically runs at a 125Hz rate, and is intended
598  * to be frequency offset from the hardclock (typ 100Hz).  It is per-cpu.
599  *
600  * NOTE! systimer! the MP lock might not be held here.  We can only safely
601  * manipulate objects owned by the current cpu.
602  *
603  * The stats clock is responsible for grabbing a profiling sample.
604  * Most of the statistics are only used by user-level statistics programs.
605  * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
606  * p->p_estcpu.
607  *
608  * Like the other clocks, the stat clock is called from what is effectively
609  * a fast interrupt, so the context should be the thread/process that got
610  * interrupted.
611  */
612 static void
613 statclock(systimer_t info, int in_ipi, struct intrframe *frame)
614 {
615 #ifdef GPROF
616 	struct gmonparam *g;
617 	int i;
618 #endif
619 	thread_t td;
620 	struct proc *p;
621 	int bump;
622 	sysclock_t cv;
623 	sysclock_t scv;
624 
625 	/*
626 	 * How big was our timeslice relative to the last time?  Calculate
627 	 * in microseconds.
628 	 *
629 	 * NOTE: Use of microuptime() is typically MPSAFE, but usually not
630 	 *	 during early boot.  Just use the systimer count to be nice
631 	 *	 to e.g. qemu.  The systimer has a better chance of being
632 	 *	 MPSAFE at early boot.
633 	 */
634 	cv = sys_cputimer->count();
635 	scv = mycpu->statint.gd_statcv;
636 	if (scv == 0) {
637 		bump = 1;
638 	} else {
639 		bump = (sys_cputimer->freq64_usec * (cv - scv)) >> 32;
640 		if (bump < 0)
641 			bump = 0;
642 		if (bump > 1000000)
643 			bump = 1000000;
644 	}
645 	mycpu->statint.gd_statcv = cv;
646 
647 #if 0
648 	stv = &mycpu->gd_stattv;
649 	if (stv->tv_sec == 0) {
650 	    bump = 1;
651 	} else {
652 	    bump = tv.tv_usec - stv->tv_usec +
653 		(tv.tv_sec - stv->tv_sec) * 1000000;
654 	    if (bump < 0)
655 		bump = 0;
656 	    if (bump > 1000000)
657 		bump = 1000000;
658 	}
659 	*stv = tv;
660 #endif
661 
662 	td = curthread;
663 	p = td->td_proc;
664 
665 	if (frame && CLKF_USERMODE(frame)) {
666 		/*
667 		 * Came from userland, handle user time and deal with
668 		 * possible process.
669 		 */
670 		if (p && (p->p_flags & P_PROFIL))
671 			addupc_intr(p, CLKF_PC(frame), 1);
672 		td->td_uticks += bump;
673 
674 		/*
675 		 * Charge the time as appropriate
676 		 */
677 		if (p && p->p_nice > NZERO)
678 			cpu_time.cp_nice += bump;
679 		else
680 			cpu_time.cp_user += bump;
681 	} else {
682 		int intr_nest = mycpu->gd_intr_nesting_level;
683 
684 		if (in_ipi) {
685 			/*
686 			 * IPI processing code will bump gd_intr_nesting_level
687 			 * up by one, which breaks following CLKF_INTR testing,
688 			 * so we substract it by one here.
689 			 */
690 			--intr_nest;
691 		}
692 #ifdef GPROF
693 		/*
694 		 * Kernel statistics are just like addupc_intr, only easier.
695 		 */
696 		g = &_gmonparam;
697 		if (g->state == GMON_PROF_ON && frame) {
698 			i = CLKF_PC(frame) - g->lowpc;
699 			if (i < g->textsize) {
700 				i /= HISTFRACTION * sizeof(*g->kcount);
701 				g->kcount[i]++;
702 			}
703 		}
704 #endif
705 
706 #define IS_INTR_RUNNING	((frame && CLKF_INTR(intr_nest)) || CLKF_INTR_TD(td))
707 
708 		/*
709 		 * Came from kernel mode, so we were:
710 		 * - handling an interrupt,
711 		 * - doing syscall or trap work on behalf of the current
712 		 *   user process, or
713 		 * - spinning in the idle loop.
714 		 * Whichever it is, charge the time as appropriate.
715 		 * Note that we charge interrupts to the current process,
716 		 * regardless of whether they are ``for'' that process,
717 		 * so that we know how much of its real time was spent
718 		 * in ``non-process'' (i.e., interrupt) work.
719 		 *
720 		 * XXX assume system if frame is NULL.  A NULL frame
721 		 * can occur if ipi processing is done from a crit_exit().
722 		 */
723 		if (IS_INTR_RUNNING)
724 			td->td_iticks += bump;
725 		else
726 			td->td_sticks += bump;
727 
728 		if (IS_INTR_RUNNING) {
729 			/*
730 			 * If we interrupted an interrupt thread, well,
731 			 * count it as interrupt time.
732 			 */
733 #ifdef DEBUG_PCTRACK
734 			if (frame)
735 				do_pctrack(frame, PCTRACK_INT);
736 #endif
737 			cpu_time.cp_intr += bump;
738 		} else {
739 			if (td == &mycpu->gd_idlethread) {
740 				/*
741 				 * Even if the current thread is the idle
742 				 * thread it could be due to token contention
743 				 * in the LWKT scheduler.  Count such as
744 				 * system time.
745 				 */
746 				if (mycpu->gd_reqflags & RQF_IDLECHECK_WK_MASK)
747 					cpu_time.cp_sys += bump;
748 				else
749 					cpu_time.cp_idle += bump;
750 			} else {
751 				/*
752 				 * System thread was running.
753 				 */
754 #ifdef DEBUG_PCTRACK
755 				if (frame)
756 					do_pctrack(frame, PCTRACK_SYS);
757 #endif
758 				cpu_time.cp_sys += bump;
759 			}
760 		}
761 
762 #undef IS_INTR_RUNNING
763 	}
764 }
765 
766 #ifdef DEBUG_PCTRACK
767 /*
768  * Sample the PC when in the kernel or in an interrupt.  User code can
769  * retrieve the information and generate a histogram or other output.
770  */
771 
772 static void
773 do_pctrack(struct intrframe *frame, int which)
774 {
775 	struct kinfo_pctrack *pctrack;
776 
777 	pctrack = &cputime_pctrack[mycpu->gd_cpuid][which];
778 	pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] =
779 		(void *)CLKF_PC(frame);
780 	++pctrack->pc_index;
781 }
782 
783 static int
784 sysctl_pctrack(SYSCTL_HANDLER_ARGS)
785 {
786 	struct kinfo_pcheader head;
787 	int error;
788 	int cpu;
789 	int ntrack;
790 
791 	head.pc_ntrack = PCTRACK_SIZE;
792 	head.pc_arysize = PCTRACK_ARYSIZE;
793 
794 	if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0)
795 		return (error);
796 
797 	for (cpu = 0; cpu < ncpus; ++cpu) {
798 		for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) {
799 			error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack],
800 					   sizeof(struct kinfo_pctrack));
801 			if (error)
802 				break;
803 		}
804 		if (error)
805 			break;
806 	}
807 	return (error);
808 }
809 SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
810 	sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking");
811 
812 #endif
813 
814 /*
815  * The scheduler clock typically runs at a 50Hz rate.  NOTE! systimer,
816  * the MP lock might not be held.  We can safely manipulate parts of curproc
817  * but that's about it.
818  *
819  * Each cpu has its own scheduler clock.
820  */
821 static void
822 schedclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
823 {
824 	struct lwp *lp;
825 	struct rusage *ru;
826 	struct vmspace *vm;
827 	long rss;
828 
829 	if ((lp = lwkt_preempted_proc()) != NULL) {
830 		/*
831 		 * Account for cpu time used and hit the scheduler.  Note
832 		 * that this call MUST BE MP SAFE, and the BGL IS NOT HELD
833 		 * HERE.
834 		 */
835 		++lp->lwp_cpticks;
836 		usched_schedulerclock(lp, info->periodic, info->time);
837 	} else {
838 		usched_schedulerclock(NULL, info->periodic, info->time);
839 	}
840 	if ((lp = curthread->td_lwp) != NULL) {
841 		/*
842 		 * Update resource usage integrals and maximums.
843 		 */
844 		if ((ru = &lp->lwp_proc->p_ru) &&
845 		    (vm = lp->lwp_proc->p_vmspace) != NULL) {
846 			ru->ru_ixrss += pgtok(vm->vm_tsize);
847 			ru->ru_idrss += pgtok(vm->vm_dsize);
848 			ru->ru_isrss += pgtok(vm->vm_ssize);
849 			if (lwkt_trytoken(&vm->vm_map.token)) {
850 				rss = pgtok(vmspace_resident_count(vm));
851 				if (ru->ru_maxrss < rss)
852 					ru->ru_maxrss = rss;
853 				lwkt_reltoken(&vm->vm_map.token);
854 			}
855 		}
856 	}
857 	/* Increment the global sched_ticks */
858 	if (mycpu->gd_cpuid == 0)
859 		++sched_ticks;
860 }
861 
862 /*
863  * Compute number of ticks for the specified amount of time.  The
864  * return value is intended to be used in a clock interrupt timed
865  * operation and guarenteed to meet or exceed the requested time.
866  * If the representation overflows, return INT_MAX.  The minimum return
867  * value is 1 ticks and the function will average the calculation up.
868  * If any value greater then 0 microseconds is supplied, a value
869  * of at least 2 will be returned to ensure that a near-term clock
870  * interrupt does not cause the timeout to occur (degenerately) early.
871  *
872  * Note that limit checks must take into account microseconds, which is
873  * done simply by using the smaller signed long maximum instead of
874  * the unsigned long maximum.
875  *
876  * If ints have 32 bits, then the maximum value for any timeout in
877  * 10ms ticks is 248 days.
878  */
879 int
880 tvtohz_high(struct timeval *tv)
881 {
882 	int ticks;
883 	long sec, usec;
884 
885 	sec = tv->tv_sec;
886 	usec = tv->tv_usec;
887 	if (usec < 0) {
888 		sec--;
889 		usec += 1000000;
890 	}
891 	if (sec < 0) {
892 #ifdef DIAGNOSTIC
893 		if (usec > 0) {
894 			sec++;
895 			usec -= 1000000;
896 		}
897 		kprintf("tvtohz_high: negative time difference "
898 			"%ld sec %ld usec\n",
899 			sec, usec);
900 #endif
901 		ticks = 1;
902 	} else if (sec <= INT_MAX / hz) {
903 		ticks = (int)(sec * hz +
904 			    ((u_long)usec + (ustick - 1)) / ustick) + 1;
905 	} else {
906 		ticks = INT_MAX;
907 	}
908 	return (ticks);
909 }
910 
911 int
912 tstohz_high(struct timespec *ts)
913 {
914 	int ticks;
915 	long sec, nsec;
916 
917 	sec = ts->tv_sec;
918 	nsec = ts->tv_nsec;
919 	if (nsec < 0) {
920 		sec--;
921 		nsec += 1000000000;
922 	}
923 	if (sec < 0) {
924 #ifdef DIAGNOSTIC
925 		if (nsec > 0) {
926 			sec++;
927 			nsec -= 1000000000;
928 		}
929 		kprintf("tstohz_high: negative time difference "
930 			"%ld sec %ld nsec\n",
931 			sec, nsec);
932 #endif
933 		ticks = 1;
934 	} else if (sec <= INT_MAX / hz) {
935 		ticks = (int)(sec * hz +
936 			    ((u_long)nsec + (nstick - 1)) / nstick) + 1;
937 	} else {
938 		ticks = INT_MAX;
939 	}
940 	return (ticks);
941 }
942 
943 
944 /*
945  * Compute number of ticks for the specified amount of time, erroring on
946  * the side of it being too low to ensure that sleeping the returned number
947  * of ticks will not result in a late return.
948  *
949  * The supplied timeval may not be negative and should be normalized.  A
950  * return value of 0 is possible if the timeval converts to less then
951  * 1 tick.
952  *
953  * If ints have 32 bits, then the maximum value for any timeout in
954  * 10ms ticks is 248 days.
955  */
956 int
957 tvtohz_low(struct timeval *tv)
958 {
959 	int ticks;
960 	long sec;
961 
962 	sec = tv->tv_sec;
963 	if (sec <= INT_MAX / hz)
964 		ticks = (int)(sec * hz + (u_long)tv->tv_usec / ustick);
965 	else
966 		ticks = INT_MAX;
967 	return (ticks);
968 }
969 
970 int
971 tstohz_low(struct timespec *ts)
972 {
973 	int ticks;
974 	long sec;
975 
976 	sec = ts->tv_sec;
977 	if (sec <= INT_MAX / hz)
978 		ticks = (int)(sec * hz + (u_long)ts->tv_nsec / nstick);
979 	else
980 		ticks = INT_MAX;
981 	return (ticks);
982 }
983 
984 /*
985  * Start profiling on a process.
986  *
987  * Kernel profiling passes proc0 which never exits and hence
988  * keeps the profile clock running constantly.
989  */
990 void
991 startprofclock(struct proc *p)
992 {
993 	if ((p->p_flags & P_PROFIL) == 0) {
994 		p->p_flags |= P_PROFIL;
995 #if 0	/* XXX */
996 		if (++profprocs == 1 && stathz != 0) {
997 			crit_enter();
998 			psdiv = psratio;
999 			setstatclockrate(profhz);
1000 			crit_exit();
1001 		}
1002 #endif
1003 	}
1004 }
1005 
1006 /*
1007  * Stop profiling on a process.
1008  *
1009  * caller must hold p->p_token
1010  */
1011 void
1012 stopprofclock(struct proc *p)
1013 {
1014 	if (p->p_flags & P_PROFIL) {
1015 		p->p_flags &= ~P_PROFIL;
1016 #if 0	/* XXX */
1017 		if (--profprocs == 0 && stathz != 0) {
1018 			crit_enter();
1019 			psdiv = 1;
1020 			setstatclockrate(stathz);
1021 			crit_exit();
1022 		}
1023 #endif
1024 	}
1025 }
1026 
1027 /*
1028  * Return information about system clocks.
1029  */
1030 static int
1031 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
1032 {
1033 	struct kinfo_clockinfo clkinfo;
1034 	/*
1035 	 * Construct clockinfo structure.
1036 	 */
1037 	clkinfo.ci_hz = hz;
1038 	clkinfo.ci_tick = ustick;
1039 	clkinfo.ci_tickadj = ntp_default_tick_delta / 1000;
1040 	clkinfo.ci_profhz = profhz;
1041 	clkinfo.ci_stathz = stathz ? stathz : hz;
1042 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
1043 }
1044 
1045 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
1046 	0, 0, sysctl_kern_clockrate, "S,clockinfo","");
1047 
1048 /*
1049  * We have eight functions for looking at the clock, four for
1050  * microseconds and four for nanoseconds.  For each there is fast
1051  * but less precise version "get{nano|micro}[up]time" which will
1052  * return a time which is up to 1/HZ previous to the call, whereas
1053  * the raw version "{nano|micro}[up]time" will return a timestamp
1054  * which is as precise as possible.  The "up" variants return the
1055  * time relative to system boot, these are well suited for time
1056  * interval measurements.
1057  *
1058  * Each cpu independantly maintains the current time of day, so all
1059  * we need to do to protect ourselves from changes is to do a loop
1060  * check on the seconds field changing out from under us.
1061  *
1062  * The system timer maintains a 32 bit count and due to various issues
1063  * it is possible for the calculated delta to occassionally exceed
1064  * sys_cputimer->freq.  If this occurs the sys_cputimer->freq64_nsec
1065  * multiplication can easily overflow, so we deal with the case.  For
1066  * uniformity we deal with the case in the usec case too.
1067  *
1068  * All the [get][micro,nano][time,uptime]() routines are MPSAFE.
1069  */
1070 void
1071 getmicrouptime(struct timeval *tvp)
1072 {
1073 	struct globaldata *gd = mycpu;
1074 	sysclock_t delta;
1075 
1076 	do {
1077 		tvp->tv_sec = gd->gd_time_seconds;
1078 		delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1079 	} while (tvp->tv_sec != gd->gd_time_seconds);
1080 
1081 	if (delta >= sys_cputimer->freq) {
1082 		tvp->tv_sec += delta / sys_cputimer->freq;
1083 		delta %= sys_cputimer->freq;
1084 	}
1085 	tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1086 	if (tvp->tv_usec >= 1000000) {
1087 		tvp->tv_usec -= 1000000;
1088 		++tvp->tv_sec;
1089 	}
1090 }
1091 
1092 void
1093 getnanouptime(struct timespec *tsp)
1094 {
1095 	struct globaldata *gd = mycpu;
1096 	sysclock_t delta;
1097 
1098 	do {
1099 		tsp->tv_sec = gd->gd_time_seconds;
1100 		delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1101 	} while (tsp->tv_sec != gd->gd_time_seconds);
1102 
1103 	if (delta >= sys_cputimer->freq) {
1104 		tsp->tv_sec += delta / sys_cputimer->freq;
1105 		delta %= sys_cputimer->freq;
1106 	}
1107 	tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1108 }
1109 
1110 void
1111 microuptime(struct timeval *tvp)
1112 {
1113 	struct globaldata *gd = mycpu;
1114 	sysclock_t delta;
1115 
1116 	do {
1117 		tvp->tv_sec = gd->gd_time_seconds;
1118 		delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1119 	} while (tvp->tv_sec != gd->gd_time_seconds);
1120 
1121 	if (delta >= sys_cputimer->freq) {
1122 		tvp->tv_sec += delta / sys_cputimer->freq;
1123 		delta %= sys_cputimer->freq;
1124 	}
1125 	tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1126 }
1127 
1128 void
1129 nanouptime(struct timespec *tsp)
1130 {
1131 	struct globaldata *gd = mycpu;
1132 	sysclock_t delta;
1133 
1134 	do {
1135 		tsp->tv_sec = gd->gd_time_seconds;
1136 		delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1137 	} while (tsp->tv_sec != gd->gd_time_seconds);
1138 
1139 	if (delta >= sys_cputimer->freq) {
1140 		tsp->tv_sec += delta / sys_cputimer->freq;
1141 		delta %= sys_cputimer->freq;
1142 	}
1143 	tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1144 }
1145 
1146 /*
1147  * realtime routines
1148  */
1149 void
1150 getmicrotime(struct timeval *tvp)
1151 {
1152 	struct globaldata *gd = mycpu;
1153 	struct timespec *bt;
1154 	sysclock_t delta;
1155 
1156 	do {
1157 		tvp->tv_sec = gd->gd_time_seconds;
1158 		delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1159 	} while (tvp->tv_sec != gd->gd_time_seconds);
1160 
1161 	if (delta >= sys_cputimer->freq) {
1162 		tvp->tv_sec += delta / sys_cputimer->freq;
1163 		delta %= sys_cputimer->freq;
1164 	}
1165 	tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1166 
1167 	bt = &basetime[basetime_index];
1168 	tvp->tv_sec += bt->tv_sec;
1169 	tvp->tv_usec += bt->tv_nsec / 1000;
1170 	while (tvp->tv_usec >= 1000000) {
1171 		tvp->tv_usec -= 1000000;
1172 		++tvp->tv_sec;
1173 	}
1174 }
1175 
1176 void
1177 getnanotime(struct timespec *tsp)
1178 {
1179 	struct globaldata *gd = mycpu;
1180 	struct timespec *bt;
1181 	sysclock_t delta;
1182 
1183 	do {
1184 		tsp->tv_sec = gd->gd_time_seconds;
1185 		delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1186 	} while (tsp->tv_sec != gd->gd_time_seconds);
1187 
1188 	if (delta >= sys_cputimer->freq) {
1189 		tsp->tv_sec += delta / sys_cputimer->freq;
1190 		delta %= sys_cputimer->freq;
1191 	}
1192 	tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1193 
1194 	bt = &basetime[basetime_index];
1195 	tsp->tv_sec += bt->tv_sec;
1196 	tsp->tv_nsec += bt->tv_nsec;
1197 	while (tsp->tv_nsec >= 1000000000) {
1198 		tsp->tv_nsec -= 1000000000;
1199 		++tsp->tv_sec;
1200 	}
1201 }
1202 
1203 static void
1204 getnanotime_nbt(struct timespec *nbt, struct timespec *tsp)
1205 {
1206 	struct globaldata *gd = mycpu;
1207 	sysclock_t delta;
1208 
1209 	do {
1210 		tsp->tv_sec = gd->gd_time_seconds;
1211 		delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1212 	} while (tsp->tv_sec != gd->gd_time_seconds);
1213 
1214 	if (delta >= sys_cputimer->freq) {
1215 		tsp->tv_sec += delta / sys_cputimer->freq;
1216 		delta %= sys_cputimer->freq;
1217 	}
1218 	tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1219 
1220 	tsp->tv_sec += nbt->tv_sec;
1221 	tsp->tv_nsec += nbt->tv_nsec;
1222 	while (tsp->tv_nsec >= 1000000000) {
1223 		tsp->tv_nsec -= 1000000000;
1224 		++tsp->tv_sec;
1225 	}
1226 }
1227 
1228 
1229 void
1230 microtime(struct timeval *tvp)
1231 {
1232 	struct globaldata *gd = mycpu;
1233 	struct timespec *bt;
1234 	sysclock_t delta;
1235 
1236 	do {
1237 		tvp->tv_sec = gd->gd_time_seconds;
1238 		delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1239 	} while (tvp->tv_sec != gd->gd_time_seconds);
1240 
1241 	if (delta >= sys_cputimer->freq) {
1242 		tvp->tv_sec += delta / sys_cputimer->freq;
1243 		delta %= sys_cputimer->freq;
1244 	}
1245 	tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1246 
1247 	bt = &basetime[basetime_index];
1248 	tvp->tv_sec += bt->tv_sec;
1249 	tvp->tv_usec += bt->tv_nsec / 1000;
1250 	while (tvp->tv_usec >= 1000000) {
1251 		tvp->tv_usec -= 1000000;
1252 		++tvp->tv_sec;
1253 	}
1254 }
1255 
1256 void
1257 nanotime(struct timespec *tsp)
1258 {
1259 	struct globaldata *gd = mycpu;
1260 	struct timespec *bt;
1261 	sysclock_t delta;
1262 
1263 	do {
1264 		tsp->tv_sec = gd->gd_time_seconds;
1265 		delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1266 	} while (tsp->tv_sec != gd->gd_time_seconds);
1267 
1268 	if (delta >= sys_cputimer->freq) {
1269 		tsp->tv_sec += delta / sys_cputimer->freq;
1270 		delta %= sys_cputimer->freq;
1271 	}
1272 	tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1273 
1274 	bt = &basetime[basetime_index];
1275 	tsp->tv_sec += bt->tv_sec;
1276 	tsp->tv_nsec += bt->tv_nsec;
1277 	while (tsp->tv_nsec >= 1000000000) {
1278 		tsp->tv_nsec -= 1000000000;
1279 		++tsp->tv_sec;
1280 	}
1281 }
1282 
1283 /*
1284  * note: this is not exactly synchronized with real time.  To do that we
1285  * would have to do what microtime does and check for a nanoseconds overflow.
1286  */
1287 time_t
1288 get_approximate_time_t(void)
1289 {
1290 	struct globaldata *gd = mycpu;
1291 	struct timespec *bt;
1292 
1293 	bt = &basetime[basetime_index];
1294 	return(gd->gd_time_seconds + bt->tv_sec);
1295 }
1296 
1297 int
1298 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1299 {
1300 	pps_params_t *app;
1301 	struct pps_fetch_args *fapi;
1302 #ifdef PPS_SYNC
1303 	struct pps_kcbind_args *kapi;
1304 #endif
1305 
1306 	switch (cmd) {
1307 	case PPS_IOC_CREATE:
1308 		return (0);
1309 	case PPS_IOC_DESTROY:
1310 		return (0);
1311 	case PPS_IOC_SETPARAMS:
1312 		app = (pps_params_t *)data;
1313 		if (app->mode & ~pps->ppscap)
1314 			return (EINVAL);
1315 		pps->ppsparam = *app;
1316 		return (0);
1317 	case PPS_IOC_GETPARAMS:
1318 		app = (pps_params_t *)data;
1319 		*app = pps->ppsparam;
1320 		app->api_version = PPS_API_VERS_1;
1321 		return (0);
1322 	case PPS_IOC_GETCAP:
1323 		*(int*)data = pps->ppscap;
1324 		return (0);
1325 	case PPS_IOC_FETCH:
1326 		fapi = (struct pps_fetch_args *)data;
1327 		if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1328 			return (EINVAL);
1329 		if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1330 			return (EOPNOTSUPP);
1331 		pps->ppsinfo.current_mode = pps->ppsparam.mode;
1332 		fapi->pps_info_buf = pps->ppsinfo;
1333 		return (0);
1334 	case PPS_IOC_KCBIND:
1335 #ifdef PPS_SYNC
1336 		kapi = (struct pps_kcbind_args *)data;
1337 		/* XXX Only root should be able to do this */
1338 		if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1339 			return (EINVAL);
1340 		if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1341 			return (EINVAL);
1342 		if (kapi->edge & ~pps->ppscap)
1343 			return (EINVAL);
1344 		pps->kcmode = kapi->edge;
1345 		return (0);
1346 #else
1347 		return (EOPNOTSUPP);
1348 #endif
1349 	default:
1350 		return (ENOTTY);
1351 	}
1352 }
1353 
1354 void
1355 pps_init(struct pps_state *pps)
1356 {
1357 	pps->ppscap |= PPS_TSFMT_TSPEC;
1358 	if (pps->ppscap & PPS_CAPTUREASSERT)
1359 		pps->ppscap |= PPS_OFFSETASSERT;
1360 	if (pps->ppscap & PPS_CAPTURECLEAR)
1361 		pps->ppscap |= PPS_OFFSETCLEAR;
1362 }
1363 
1364 void
1365 pps_event(struct pps_state *pps, sysclock_t count, int event)
1366 {
1367 	struct globaldata *gd;
1368 	struct timespec *tsp;
1369 	struct timespec *osp;
1370 	struct timespec *bt;
1371 	struct timespec ts;
1372 	sysclock_t *pcount;
1373 #ifdef PPS_SYNC
1374 	sysclock_t tcount;
1375 #endif
1376 	sysclock_t delta;
1377 	pps_seq_t *pseq;
1378 	int foff;
1379 	int fhard;
1380 
1381 	gd = mycpu;
1382 
1383 	/* Things would be easier with arrays... */
1384 	if (event == PPS_CAPTUREASSERT) {
1385 		tsp = &pps->ppsinfo.assert_timestamp;
1386 		osp = &pps->ppsparam.assert_offset;
1387 		foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1388 		fhard = pps->kcmode & PPS_CAPTUREASSERT;
1389 		pcount = &pps->ppscount[0];
1390 		pseq = &pps->ppsinfo.assert_sequence;
1391 	} else {
1392 		tsp = &pps->ppsinfo.clear_timestamp;
1393 		osp = &pps->ppsparam.clear_offset;
1394 		foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1395 		fhard = pps->kcmode & PPS_CAPTURECLEAR;
1396 		pcount = &pps->ppscount[1];
1397 		pseq = &pps->ppsinfo.clear_sequence;
1398 	}
1399 
1400 	/* Nothing really happened */
1401 	if (*pcount == count)
1402 		return;
1403 
1404 	*pcount = count;
1405 
1406 	do {
1407 		ts.tv_sec = gd->gd_time_seconds;
1408 		delta = count - gd->gd_cpuclock_base;
1409 	} while (ts.tv_sec != gd->gd_time_seconds);
1410 
1411 	if (delta >= sys_cputimer->freq) {
1412 		ts.tv_sec += delta / sys_cputimer->freq;
1413 		delta %= sys_cputimer->freq;
1414 	}
1415 	ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1416 	bt = &basetime[basetime_index];
1417 	ts.tv_sec += bt->tv_sec;
1418 	ts.tv_nsec += bt->tv_nsec;
1419 	while (ts.tv_nsec >= 1000000000) {
1420 		ts.tv_nsec -= 1000000000;
1421 		++ts.tv_sec;
1422 	}
1423 
1424 	(*pseq)++;
1425 	*tsp = ts;
1426 
1427 	if (foff) {
1428 		timespecadd(tsp, osp);
1429 		if (tsp->tv_nsec < 0) {
1430 			tsp->tv_nsec += 1000000000;
1431 			tsp->tv_sec -= 1;
1432 		}
1433 	}
1434 #ifdef PPS_SYNC
1435 	if (fhard) {
1436 		/* magic, at its best... */
1437 		tcount = count - pps->ppscount[2];
1438 		pps->ppscount[2] = count;
1439 		if (tcount >= sys_cputimer->freq) {
1440 			delta = (1000000000 * (tcount / sys_cputimer->freq) +
1441 				 sys_cputimer->freq64_nsec *
1442 				 (tcount % sys_cputimer->freq)) >> 32;
1443 		} else {
1444 			delta = (sys_cputimer->freq64_nsec * tcount) >> 32;
1445 		}
1446 		hardpps(tsp, delta);
1447 	}
1448 #endif
1449 }
1450 
1451 /*
1452  * Return the tsc target value for a delay of (ns).
1453  *
1454  * Returns -1 if the TSC is not supported.
1455  */
1456 int64_t
1457 tsc_get_target(int ns)
1458 {
1459 #if defined(_RDTSC_SUPPORTED_)
1460 	if (cpu_feature & CPUID_TSC) {
1461 		return (rdtsc() + tsc_frequency * ns / (int64_t)1000000000);
1462 	}
1463 #endif
1464 	return(-1);
1465 }
1466 
1467 /*
1468  * Compare the tsc against the passed target
1469  *
1470  * Returns +1 if the target has been reached
1471  * Returns  0 if the target has not yet been reached
1472  * Returns -1 if the TSC is not supported.
1473  *
1474  * Typical use:		while (tsc_test_target(target) == 0) { ...poll... }
1475  */
1476 int
1477 tsc_test_target(int64_t target)
1478 {
1479 #if defined(_RDTSC_SUPPORTED_)
1480 	if (cpu_feature & CPUID_TSC) {
1481 		if ((int64_t)(target - rdtsc()) <= 0)
1482 			return(1);
1483 		return(0);
1484 	}
1485 #endif
1486 	return(-1);
1487 }
1488 
1489 /*
1490  * Delay the specified number of nanoseconds using the tsc.  This function
1491  * returns immediately if the TSC is not supported.  At least one cpu_pause()
1492  * will be issued.
1493  */
1494 void
1495 tsc_delay(int ns)
1496 {
1497 	int64_t clk;
1498 
1499 	clk = tsc_get_target(ns);
1500 	cpu_pause();
1501 	while (tsc_test_target(clk) == 0)
1502 		cpu_pause();
1503 }
1504