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