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