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