2 * Copyright (c) 2003,2004 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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.
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
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.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
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.
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
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 $
72 #include "opt_ifpoll.h"
73 #include "opt_pctrack.h"
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/callout.h>
78 #include <sys/kernel.h>
79 #include <sys/kinfo.h>
81 #include <sys/malloc.h>
82 #include <sys/resource.h>
83 #include <sys/resourcevar.h>
84 #include <sys/signalvar.h>
85 #include <sys/timex.h>
86 #include <sys/timepps.h>
87 #include <sys/upmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_extern.h>
93 #include <sys/sysctl.h>
95 #include <sys/thread2.h>
96 #include <sys/mplock2.h>
98 #include <machine/cpu.h>
99 #include <machine/limits.h>
100 #include <machine/smp.h>
101 #include <machine/cpufunc.h>
102 #include <machine/specialreg.h>
103 #include <machine/clock.h>
106 #include <sys/gmon.h>
110 extern void ifpoll_init_pcpu(int);
114 static void do_pctrack(struct intrframe *frame, int which);
117 static void initclocks (void *dummy);
118 SYSINIT(clocks, SI_BOOT2_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
121 * Some of these don't belong here, but it's easiest to concentrate them.
122 * Note that cpu_time counts in microseconds, but most userland programs
123 * just compare relative times against the total by delta.
125 struct kinfo_cputime cputime_percpu[MAXCPU];
127 struct kinfo_pcheader cputime_pcheader = { PCTRACK_SIZE, PCTRACK_ARYSIZE };
128 struct kinfo_pctrack cputime_pctrack[MAXCPU][PCTRACK_SIZE];
132 sysctl_cputime(SYSCTL_HANDLER_ARGS)
135 size_t size = sizeof(struct kinfo_cputime);
137 for (cpu = 0; cpu < ncpus; ++cpu) {
138 if ((error = SYSCTL_OUT(req, &cputime_percpu[cpu], size)))
144 SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
145 sysctl_cputime, "S,kinfo_cputime", "CPU time statistics");
148 sysctl_cp_time(SYSCTL_HANDLER_ARGS)
150 long cpu_states[5] = {0};
152 size_t size = sizeof(cpu_states);
154 for (cpu = 0; cpu < ncpus; ++cpu) {
155 cpu_states[CP_USER] += cputime_percpu[cpu].cp_user;
156 cpu_states[CP_NICE] += cputime_percpu[cpu].cp_nice;
157 cpu_states[CP_SYS] += cputime_percpu[cpu].cp_sys;
158 cpu_states[CP_INTR] += cputime_percpu[cpu].cp_intr;
159 cpu_states[CP_IDLE] += cputime_percpu[cpu].cp_idle;
162 error = SYSCTL_OUT(req, cpu_states, size);
167 SYSCTL_PROC(_kern, OID_AUTO, cp_time, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
168 sysctl_cp_time, "LU", "CPU time statistics");
171 * boottime is used to calculate the 'real' uptime. Do not confuse this with
172 * microuptime(). microtime() is not drift compensated. The real uptime
173 * with compensation is nanotime() - bootime. boottime is recalculated
174 * whenever the real time is set based on the compensated elapsed time
175 * in seconds (gd->gd_time_seconds).
177 * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
178 * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
181 struct timespec boottime; /* boot time (realtime) for reference only */
182 time_t time_second; /* read-only 'passive' uptime in seconds */
183 time_t time_uptime; /* read-only 'passive' uptime in seconds */
186 * basetime is used to calculate the compensated real time of day. The
187 * basetime can be modified on a per-tick basis by the adjtime(),
188 * ntp_adjtime(), and sysctl-based time correction APIs.
190 * Note that frequency corrections can also be made by adjusting
193 * basetime is a tail-chasing FIFO, updated only by cpu #0. The FIFO is
194 * used on both SMP and UP systems to avoid MP races between cpu's and
195 * interrupt races on UP systems.
197 #define BASETIME_ARYSIZE 16
198 #define BASETIME_ARYMASK (BASETIME_ARYSIZE - 1)
199 static struct timespec basetime[BASETIME_ARYSIZE];
200 static volatile int basetime_index;
203 sysctl_get_basetime(SYSCTL_HANDLER_ARGS)
210 * Because basetime data and index may be updated by another cpu,
211 * a load fence is required to ensure that the data we read has
212 * not been speculatively read relative to a possibly updated index.
214 index = basetime_index;
216 bt = &basetime[index];
217 error = SYSCTL_OUT(req, bt, sizeof(*bt));
221 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
222 &boottime, timespec, "System boottime");
223 SYSCTL_PROC(_kern, OID_AUTO, basetime, CTLTYPE_STRUCT|CTLFLAG_RD, 0, 0,
224 sysctl_get_basetime, "S,timespec", "System basetime");
226 static void hardclock(systimer_t info, int, struct intrframe *frame);
227 static void statclock(systimer_t info, int, struct intrframe *frame);
228 static void schedclock(systimer_t info, int, struct intrframe *frame);
229 static void getnanotime_nbt(struct timespec *nbt, struct timespec *tsp);
231 int ticks; /* system master ticks at hz */
232 int clocks_running; /* tsleep/timeout clocks operational */
233 int64_t nsec_adj; /* ntpd per-tick adjustment in nsec << 32 */
234 int64_t nsec_acc; /* accumulator */
235 int sched_ticks; /* global schedule clock ticks */
237 /* NTPD time correction fields */
238 int64_t ntp_tick_permanent; /* per-tick adjustment in nsec << 32 */
239 int64_t ntp_tick_acc; /* accumulator for per-tick adjustment */
240 int64_t ntp_delta; /* one-time correction in nsec */
241 int64_t ntp_big_delta = 1000000000;
242 int32_t ntp_tick_delta; /* current adjustment rate */
243 int32_t ntp_default_tick_delta; /* adjustment rate for ntp_delta */
244 time_t ntp_leap_second; /* time of next leap second */
245 int ntp_leap_insert; /* whether to insert or remove a second */
248 * Finish initializing clock frequencies and start all clocks running.
252 initclocks(void *dummy)
254 /*psratio = profhz / stathz;*/
258 kpmap->tsc_freq = (uint64_t)tsc_frequency;
259 kpmap->tick_freq = hz;
264 * Called on a per-cpu basis from the idle thread bootstrap on each cpu
265 * during SMP initialization.
267 * This routine is called concurrently during low-level SMP initialization
268 * and may not block in any way. Meaning, among other things, we can't
269 * acquire any tokens.
272 initclocks_pcpu(void)
274 struct globaldata *gd = mycpu;
277 if (gd->gd_cpuid == 0) {
278 gd->gd_time_seconds = 1;
279 gd->gd_cpuclock_base = sys_cputimer->count();
282 gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
283 gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
286 systimer_intr_enable();
292 * This routine is called on just the BSP, just after SMP initialization
293 * completes to * finish initializing any clocks that might contend/block
294 * (e.g. like on a token). We can't do this in initclocks_pcpu() because
295 * that function is called from the idle thread bootstrap for each cpu and
296 * not allowed to block at all.
300 initclocks_other(void *dummy)
302 struct globaldata *ogd = mycpu;
303 struct globaldata *gd;
306 for (n = 0; n < ncpus; ++n) {
307 lwkt_setcpu_self(globaldata_find(n));
311 * Use a non-queued periodic systimer to prevent multiple
312 * ticks from building up if the sysclock jumps forward
313 * (8254 gets reset). The sysclock will never jump backwards.
314 * Our time sync is based on the actual sysclock, not the
317 systimer_init_periodic_nq(&gd->gd_hardclock, hardclock,
319 systimer_init_periodic_nq(&gd->gd_statclock, statclock,
321 /* XXX correct the frequency for scheduler / estcpu tests */
322 systimer_init_periodic_nq(&gd->gd_schedclock, schedclock,
325 ifpoll_init_pcpu(gd->gd_cpuid);
328 lwkt_setcpu_self(ogd);
330 SYSINIT(clocks2, SI_BOOT2_POST_SMP, SI_ORDER_ANY, initclocks_other, NULL)
333 * This sets the current real time of day. Timespecs are in seconds and
334 * nanoseconds. We do not mess with gd_time_seconds and gd_cpuclock_base,
335 * instead we adjust basetime so basetime + gd_* results in the current
336 * time of day. This way the gd_* fields are guarenteed to represent
337 * a monotonically increasing 'uptime' value.
339 * When set_timeofday() is called from userland, the system call forces it
340 * onto cpu #0 since only cpu #0 can update basetime_index.
343 set_timeofday(struct timespec *ts)
345 struct timespec *nbt;
349 * XXX SMP / non-atomic basetime updates
352 ni = (basetime_index + 1) & BASETIME_ARYMASK;
355 nbt->tv_sec = ts->tv_sec - nbt->tv_sec;
356 nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec;
357 if (nbt->tv_nsec < 0) {
358 nbt->tv_nsec += 1000000000;
363 * Note that basetime diverges from boottime as the clock drift is
364 * compensated for, so we cannot do away with boottime. When setting
365 * the absolute time of day the drift is 0 (for an instant) and we
366 * can simply assign boottime to basetime.
368 * Note that nanouptime() is based on gd_time_seconds which is drift
369 * compensated up to a point (it is guarenteed to remain monotonically
370 * increasing). gd_time_seconds is thus our best uptime guess and
371 * suitable for use in the boottime calculation. It is already taken
372 * into account in the basetime calculation above.
374 boottime.tv_sec = nbt->tv_sec;
378 * We now have a new basetime, make sure all other cpus have it,
379 * then update the index.
388 * Each cpu has its own hardclock, but we only increments ticks and softticks
391 * NOTE! systimer! the MP lock might not be held here. We can only safely
392 * manipulate objects owned by the current cpu.
395 hardclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
399 struct globaldata *gd = mycpu;
402 * Realtime updates are per-cpu. Note that timer corrections as
403 * returned by microtime() and friends make an additional adjustment
404 * using a system-wise 'basetime', but the running time is always
405 * taken from the per-cpu globaldata area. Since the same clock
406 * is distributing (XXX SMP) to all cpus, the per-cpu timebases
409 * Note that we never allow info->time (aka gd->gd_hardclock.time)
410 * to reverse index gd_cpuclock_base, but that it is possible for
411 * it to temporarily get behind in the seconds if something in the
412 * system locks interrupts for a long period of time. Since periodic
413 * timers count events, though everything should resynch again
416 cputicks = info->time - gd->gd_cpuclock_base;
417 if (cputicks >= sys_cputimer->freq) {
418 ++gd->gd_time_seconds;
419 gd->gd_cpuclock_base += sys_cputimer->freq;
420 if (gd->gd_cpuid == 0)
421 ++time_uptime; /* uncorrected monotonic 1-sec gran */
425 * The system-wide ticks counter and NTP related timedelta/tickdelta
426 * adjustments only occur on cpu #0. NTP adjustments are accomplished
427 * by updating basetime.
429 if (gd->gd_cpuid == 0) {
430 struct timespec *nbt;
438 if (tco->tc_poll_pps)
439 tco->tc_poll_pps(tco);
443 * Calculate the new basetime index. We are in a critical section
444 * on cpu #0 and can safely play with basetime_index. Start
445 * with the current basetime and then make adjustments.
447 ni = (basetime_index + 1) & BASETIME_ARYMASK;
449 *nbt = basetime[basetime_index];
452 * Apply adjtime corrections. (adjtime() API)
454 * adjtime() only runs on cpu #0 so our critical section is
455 * sufficient to access these variables.
457 if (ntp_delta != 0) {
458 nbt->tv_nsec += ntp_tick_delta;
459 ntp_delta -= ntp_tick_delta;
460 if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) ||
461 (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) {
462 ntp_tick_delta = ntp_delta;
467 * Apply permanent frequency corrections. (sysctl API)
469 if (ntp_tick_permanent != 0) {
470 ntp_tick_acc += ntp_tick_permanent;
471 if (ntp_tick_acc >= (1LL << 32)) {
472 nbt->tv_nsec += ntp_tick_acc >> 32;
473 ntp_tick_acc -= (ntp_tick_acc >> 32) << 32;
474 } else if (ntp_tick_acc <= -(1LL << 32)) {
475 /* Negate ntp_tick_acc to avoid shifting the sign bit. */
476 nbt->tv_nsec -= (-ntp_tick_acc) >> 32;
477 ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32;
481 if (nbt->tv_nsec >= 1000000000) {
483 nbt->tv_nsec -= 1000000000;
484 } else if (nbt->tv_nsec < 0) {
486 nbt->tv_nsec += 1000000000;
490 * Another per-tick compensation. (for ntp_adjtime() API)
493 nsec_acc += nsec_adj;
494 if (nsec_acc >= 0x100000000LL) {
495 nbt->tv_nsec += nsec_acc >> 32;
496 nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
497 } else if (nsec_acc <= -0x100000000LL) {
498 nbt->tv_nsec -= -nsec_acc >> 32;
499 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
501 if (nbt->tv_nsec >= 1000000000) {
502 nbt->tv_nsec -= 1000000000;
504 } else if (nbt->tv_nsec < 0) {
505 nbt->tv_nsec += 1000000000;
510 /************************************************************
511 * LEAP SECOND CORRECTION *
512 ************************************************************
514 * Taking into account all the corrections made above, figure
515 * out the new real time. If the seconds field has changed
516 * then apply any pending leap-second corrections.
518 getnanotime_nbt(nbt, &nts);
520 if (time_second != nts.tv_sec) {
522 * Apply leap second (sysctl API). Adjust nts for changes
523 * so we do not have to call getnanotime_nbt again.
525 if (ntp_leap_second) {
526 if (ntp_leap_second == nts.tv_sec) {
527 if (ntp_leap_insert) {
539 * Apply leap second (ntp_adjtime() API), calculate a new
540 * nsec_adj field. ntp_update_second() returns nsec_adj
541 * as a per-second value but we need it as a per-tick value.
543 leap = ntp_update_second(time_second, &nsec_adj);
549 * Update the time_second 'approximate time' global.
551 time_second = nts.tv_sec;
555 * Finally, our new basetime is ready to go live!
561 * Update kpmap on each tick
564 getnanouptime(&kpmap->ts_uptime);
565 getnanotime(&kpmap->ts_realtime);
570 * lwkt thread scheduler fair queueing
572 lwkt_schedulerclock(curthread);
575 * softticks are handled for all cpus
577 hardclock_softtick(gd);
580 * ITimer handling is per-tick, per-cpu.
582 * We must acquire the per-process token in order for ksignal()
583 * to be non-blocking. For the moment this requires an AST fault,
584 * the ksignal() cannot be safely issued from this hard interrupt.
586 * XXX Even the trytoken here isn't right, and itimer operation in
587 * a multi threaded environment is going to be weird at the
590 if ((p = curproc) != NULL && lwkt_trytoken(&p->p_token)) {
593 ++p->p_upmap->runticks;
595 if (frame && CLKF_USERMODE(frame) &&
596 timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) &&
597 itimerdecr(&p->p_timer[ITIMER_VIRTUAL], ustick) == 0) {
598 p->p_flags |= P_SIGVTALRM;
601 if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) &&
602 itimerdecr(&p->p_timer[ITIMER_PROF], ustick) == 0) {
603 p->p_flags |= P_SIGPROF;
607 lwkt_reltoken(&p->p_token);
613 * The statistics clock typically runs at a 125Hz rate, and is intended
614 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu.
616 * NOTE! systimer! the MP lock might not be held here. We can only safely
617 * manipulate objects owned by the current cpu.
619 * The stats clock is responsible for grabbing a profiling sample.
620 * Most of the statistics are only used by user-level statistics programs.
621 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
624 * Like the other clocks, the stat clock is called from what is effectively
625 * a fast interrupt, so the context should be the thread/process that got
629 statclock(systimer_t info, int in_ipi, struct intrframe *frame)
642 * How big was our timeslice relative to the last time? Calculate
645 * NOTE: Use of microuptime() is typically MPSAFE, but usually not
646 * during early boot. Just use the systimer count to be nice
647 * to e.g. qemu. The systimer has a better chance of being
648 * MPSAFE at early boot.
650 cv = sys_cputimer->count();
651 scv = mycpu->statint.gd_statcv;
655 bump = (sys_cputimer->freq64_usec * (cv - scv)) >> 32;
661 mycpu->statint.gd_statcv = cv;
664 stv = &mycpu->gd_stattv;
665 if (stv->tv_sec == 0) {
668 bump = tv.tv_usec - stv->tv_usec +
669 (tv.tv_sec - stv->tv_sec) * 1000000;
681 if (frame && CLKF_USERMODE(frame)) {
683 * Came from userland, handle user time and deal with
686 if (p && (p->p_flags & P_PROFIL))
687 addupc_intr(p, CLKF_PC(frame), 1);
688 td->td_uticks += bump;
691 * Charge the time as appropriate
693 if (p && p->p_nice > NZERO)
694 cpu_time.cp_nice += bump;
696 cpu_time.cp_user += bump;
698 int intr_nest = mycpu->gd_intr_nesting_level;
702 * IPI processing code will bump gd_intr_nesting_level
703 * up by one, which breaks following CLKF_INTR testing,
704 * so we substract it by one here.
710 * Kernel statistics are just like addupc_intr, only easier.
713 if (g->state == GMON_PROF_ON && frame) {
714 i = CLKF_PC(frame) - g->lowpc;
715 if (i < g->textsize) {
716 i /= HISTFRACTION * sizeof(*g->kcount);
722 #define IS_INTR_RUNNING ((frame && CLKF_INTR(intr_nest)) || CLKF_INTR_TD(td))
725 * Came from kernel mode, so we were:
726 * - handling an interrupt,
727 * - doing syscall or trap work on behalf of the current
729 * - spinning in the idle loop.
730 * Whichever it is, charge the time as appropriate.
731 * Note that we charge interrupts to the current process,
732 * regardless of whether they are ``for'' that process,
733 * so that we know how much of its real time was spent
734 * in ``non-process'' (i.e., interrupt) work.
736 * XXX assume system if frame is NULL. A NULL frame
737 * can occur if ipi processing is done from a crit_exit().
740 td->td_iticks += bump;
742 td->td_sticks += bump;
744 if (IS_INTR_RUNNING) {
746 * If we interrupted an interrupt thread, well,
747 * count it as interrupt time.
751 do_pctrack(frame, PCTRACK_INT);
753 cpu_time.cp_intr += bump;
755 if (td == &mycpu->gd_idlethread) {
757 * Even if the current thread is the idle
758 * thread it could be due to token contention
759 * in the LWKT scheduler. Count such as
762 if (mycpu->gd_reqflags & RQF_IDLECHECK_WK_MASK)
763 cpu_time.cp_sys += bump;
765 cpu_time.cp_idle += bump;
768 * System thread was running.
772 do_pctrack(frame, PCTRACK_SYS);
774 cpu_time.cp_sys += bump;
778 #undef IS_INTR_RUNNING
784 * Sample the PC when in the kernel or in an interrupt. User code can
785 * retrieve the information and generate a histogram or other output.
789 do_pctrack(struct intrframe *frame, int which)
791 struct kinfo_pctrack *pctrack;
793 pctrack = &cputime_pctrack[mycpu->gd_cpuid][which];
794 pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] =
795 (void *)CLKF_PC(frame);
800 sysctl_pctrack(SYSCTL_HANDLER_ARGS)
802 struct kinfo_pcheader head;
807 head.pc_ntrack = PCTRACK_SIZE;
808 head.pc_arysize = PCTRACK_ARYSIZE;
810 if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0)
813 for (cpu = 0; cpu < ncpus; ++cpu) {
814 for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) {
815 error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack],
816 sizeof(struct kinfo_pctrack));
825 SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
826 sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking");
831 * The scheduler clock typically runs at a 50Hz rate. NOTE! systimer,
832 * the MP lock might not be held. We can safely manipulate parts of curproc
833 * but that's about it.
835 * Each cpu has its own scheduler clock.
838 schedclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
845 if ((lp = lwkt_preempted_proc()) != NULL) {
847 * Account for cpu time used and hit the scheduler. Note
848 * that this call MUST BE MP SAFE, and the BGL IS NOT HELD
852 usched_schedulerclock(lp, info->periodic, info->time);
854 usched_schedulerclock(NULL, info->periodic, info->time);
856 if ((lp = curthread->td_lwp) != NULL) {
858 * Update resource usage integrals and maximums.
860 if ((ru = &lp->lwp_proc->p_ru) &&
861 (vm = lp->lwp_proc->p_vmspace) != NULL) {
862 ru->ru_ixrss += pgtok(vm->vm_tsize);
863 ru->ru_idrss += pgtok(vm->vm_dsize);
864 ru->ru_isrss += pgtok(vm->vm_ssize);
865 if (lwkt_trytoken(&vm->vm_map.token)) {
866 rss = pgtok(vmspace_resident_count(vm));
867 if (ru->ru_maxrss < rss)
869 lwkt_reltoken(&vm->vm_map.token);
873 /* Increment the global sched_ticks */
874 if (mycpu->gd_cpuid == 0)
879 * Compute number of ticks for the specified amount of time. The
880 * return value is intended to be used in a clock interrupt timed
881 * operation and guarenteed to meet or exceed the requested time.
882 * If the representation overflows, return INT_MAX. The minimum return
883 * value is 1 ticks and the function will average the calculation up.
884 * If any value greater then 0 microseconds is supplied, a value
885 * of at least 2 will be returned to ensure that a near-term clock
886 * interrupt does not cause the timeout to occur (degenerately) early.
888 * Note that limit checks must take into account microseconds, which is
889 * done simply by using the smaller signed long maximum instead of
890 * the unsigned long maximum.
892 * If ints have 32 bits, then the maximum value for any timeout in
893 * 10ms ticks is 248 days.
896 tvtohz_high(struct timeval *tv)
913 kprintf("tvtohz_high: negative time difference "
914 "%ld sec %ld usec\n",
918 } else if (sec <= INT_MAX / hz) {
919 ticks = (int)(sec * hz +
920 ((u_long)usec + (ustick - 1)) / ustick) + 1;
928 tstohz_high(struct timespec *ts)
945 kprintf("tstohz_high: negative time difference "
946 "%ld sec %ld nsec\n",
950 } else if (sec <= INT_MAX / hz) {
951 ticks = (int)(sec * hz +
952 ((u_long)nsec + (nstick - 1)) / nstick) + 1;
961 * Compute number of ticks for the specified amount of time, erroring on
962 * the side of it being too low to ensure that sleeping the returned number
963 * of ticks will not result in a late return.
965 * The supplied timeval may not be negative and should be normalized. A
966 * return value of 0 is possible if the timeval converts to less then
969 * If ints have 32 bits, then the maximum value for any timeout in
970 * 10ms ticks is 248 days.
973 tvtohz_low(struct timeval *tv)
979 if (sec <= INT_MAX / hz)
980 ticks = (int)(sec * hz + (u_long)tv->tv_usec / ustick);
987 tstohz_low(struct timespec *ts)
993 if (sec <= INT_MAX / hz)
994 ticks = (int)(sec * hz + (u_long)ts->tv_nsec / nstick);
1001 * Start profiling on a process.
1003 * Kernel profiling passes proc0 which never exits and hence
1004 * keeps the profile clock running constantly.
1007 startprofclock(struct proc *p)
1009 if ((p->p_flags & P_PROFIL) == 0) {
1010 p->p_flags |= P_PROFIL;
1012 if (++profprocs == 1 && stathz != 0) {
1015 setstatclockrate(profhz);
1023 * Stop profiling on a process.
1025 * caller must hold p->p_token
1028 stopprofclock(struct proc *p)
1030 if (p->p_flags & P_PROFIL) {
1031 p->p_flags &= ~P_PROFIL;
1033 if (--profprocs == 0 && stathz != 0) {
1036 setstatclockrate(stathz);
1044 * Return information about system clocks.
1047 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
1049 struct kinfo_clockinfo clkinfo;
1051 * Construct clockinfo structure.
1054 clkinfo.ci_tick = ustick;
1055 clkinfo.ci_tickadj = ntp_default_tick_delta / 1000;
1056 clkinfo.ci_profhz = profhz;
1057 clkinfo.ci_stathz = stathz ? stathz : hz;
1058 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
1061 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
1062 0, 0, sysctl_kern_clockrate, "S,clockinfo","");
1065 * We have eight functions for looking at the clock, four for
1066 * microseconds and four for nanoseconds. For each there is fast
1067 * but less precise version "get{nano|micro}[up]time" which will
1068 * return a time which is up to 1/HZ previous to the call, whereas
1069 * the raw version "{nano|micro}[up]time" will return a timestamp
1070 * which is as precise as possible. The "up" variants return the
1071 * time relative to system boot, these are well suited for time
1072 * interval measurements.
1074 * Each cpu independantly maintains the current time of day, so all
1075 * we need to do to protect ourselves from changes is to do a loop
1076 * check on the seconds field changing out from under us.
1078 * The system timer maintains a 32 bit count and due to various issues
1079 * it is possible for the calculated delta to occassionally exceed
1080 * sys_cputimer->freq. If this occurs the sys_cputimer->freq64_nsec
1081 * multiplication can easily overflow, so we deal with the case. For
1082 * uniformity we deal with the case in the usec case too.
1084 * All the [get][micro,nano][time,uptime]() routines are MPSAFE.
1087 getmicrouptime(struct timeval *tvp)
1089 struct globaldata *gd = mycpu;
1093 tvp->tv_sec = gd->gd_time_seconds;
1094 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1095 } while (tvp->tv_sec != gd->gd_time_seconds);
1097 if (delta >= sys_cputimer->freq) {
1098 tvp->tv_sec += delta / sys_cputimer->freq;
1099 delta %= sys_cputimer->freq;
1101 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1102 if (tvp->tv_usec >= 1000000) {
1103 tvp->tv_usec -= 1000000;
1109 getnanouptime(struct timespec *tsp)
1111 struct globaldata *gd = mycpu;
1115 tsp->tv_sec = gd->gd_time_seconds;
1116 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1117 } while (tsp->tv_sec != gd->gd_time_seconds);
1119 if (delta >= sys_cputimer->freq) {
1120 tsp->tv_sec += delta / sys_cputimer->freq;
1121 delta %= sys_cputimer->freq;
1123 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1127 microuptime(struct timeval *tvp)
1129 struct globaldata *gd = mycpu;
1133 tvp->tv_sec = gd->gd_time_seconds;
1134 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1135 } while (tvp->tv_sec != gd->gd_time_seconds);
1137 if (delta >= sys_cputimer->freq) {
1138 tvp->tv_sec += delta / sys_cputimer->freq;
1139 delta %= sys_cputimer->freq;
1141 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1145 nanouptime(struct timespec *tsp)
1147 struct globaldata *gd = mycpu;
1151 tsp->tv_sec = gd->gd_time_seconds;
1152 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1153 } while (tsp->tv_sec != gd->gd_time_seconds);
1155 if (delta >= sys_cputimer->freq) {
1156 tsp->tv_sec += delta / sys_cputimer->freq;
1157 delta %= sys_cputimer->freq;
1159 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1166 getmicrotime(struct timeval *tvp)
1168 struct globaldata *gd = mycpu;
1169 struct timespec *bt;
1173 tvp->tv_sec = gd->gd_time_seconds;
1174 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1175 } while (tvp->tv_sec != gd->gd_time_seconds);
1177 if (delta >= sys_cputimer->freq) {
1178 tvp->tv_sec += delta / sys_cputimer->freq;
1179 delta %= sys_cputimer->freq;
1181 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1183 bt = &basetime[basetime_index];
1184 tvp->tv_sec += bt->tv_sec;
1185 tvp->tv_usec += bt->tv_nsec / 1000;
1186 while (tvp->tv_usec >= 1000000) {
1187 tvp->tv_usec -= 1000000;
1193 getnanotime(struct timespec *tsp)
1195 struct globaldata *gd = mycpu;
1196 struct timespec *bt;
1200 tsp->tv_sec = gd->gd_time_seconds;
1201 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1202 } while (tsp->tv_sec != gd->gd_time_seconds);
1204 if (delta >= sys_cputimer->freq) {
1205 tsp->tv_sec += delta / sys_cputimer->freq;
1206 delta %= sys_cputimer->freq;
1208 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1210 bt = &basetime[basetime_index];
1211 tsp->tv_sec += bt->tv_sec;
1212 tsp->tv_nsec += bt->tv_nsec;
1213 while (tsp->tv_nsec >= 1000000000) {
1214 tsp->tv_nsec -= 1000000000;
1220 getnanotime_nbt(struct timespec *nbt, struct timespec *tsp)
1222 struct globaldata *gd = mycpu;
1226 tsp->tv_sec = gd->gd_time_seconds;
1227 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1228 } while (tsp->tv_sec != gd->gd_time_seconds);
1230 if (delta >= sys_cputimer->freq) {
1231 tsp->tv_sec += delta / sys_cputimer->freq;
1232 delta %= sys_cputimer->freq;
1234 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1236 tsp->tv_sec += nbt->tv_sec;
1237 tsp->tv_nsec += nbt->tv_nsec;
1238 while (tsp->tv_nsec >= 1000000000) {
1239 tsp->tv_nsec -= 1000000000;
1246 microtime(struct timeval *tvp)
1248 struct globaldata *gd = mycpu;
1249 struct timespec *bt;
1253 tvp->tv_sec = gd->gd_time_seconds;
1254 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1255 } while (tvp->tv_sec != gd->gd_time_seconds);
1257 if (delta >= sys_cputimer->freq) {
1258 tvp->tv_sec += delta / sys_cputimer->freq;
1259 delta %= sys_cputimer->freq;
1261 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1263 bt = &basetime[basetime_index];
1264 tvp->tv_sec += bt->tv_sec;
1265 tvp->tv_usec += bt->tv_nsec / 1000;
1266 while (tvp->tv_usec >= 1000000) {
1267 tvp->tv_usec -= 1000000;
1273 nanotime(struct timespec *tsp)
1275 struct globaldata *gd = mycpu;
1276 struct timespec *bt;
1280 tsp->tv_sec = gd->gd_time_seconds;
1281 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1282 } while (tsp->tv_sec != gd->gd_time_seconds);
1284 if (delta >= sys_cputimer->freq) {
1285 tsp->tv_sec += delta / sys_cputimer->freq;
1286 delta %= sys_cputimer->freq;
1288 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1290 bt = &basetime[basetime_index];
1291 tsp->tv_sec += bt->tv_sec;
1292 tsp->tv_nsec += bt->tv_nsec;
1293 while (tsp->tv_nsec >= 1000000000) {
1294 tsp->tv_nsec -= 1000000000;
1300 * note: this is not exactly synchronized with real time. To do that we
1301 * would have to do what microtime does and check for a nanoseconds overflow.
1304 get_approximate_time_t(void)
1306 struct globaldata *gd = mycpu;
1307 struct timespec *bt;
1309 bt = &basetime[basetime_index];
1310 return(gd->gd_time_seconds + bt->tv_sec);
1314 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1317 struct pps_fetch_args *fapi;
1319 struct pps_kcbind_args *kapi;
1323 case PPS_IOC_CREATE:
1325 case PPS_IOC_DESTROY:
1327 case PPS_IOC_SETPARAMS:
1328 app = (pps_params_t *)data;
1329 if (app->mode & ~pps->ppscap)
1331 pps->ppsparam = *app;
1333 case PPS_IOC_GETPARAMS:
1334 app = (pps_params_t *)data;
1335 *app = pps->ppsparam;
1336 app->api_version = PPS_API_VERS_1;
1338 case PPS_IOC_GETCAP:
1339 *(int*)data = pps->ppscap;
1342 fapi = (struct pps_fetch_args *)data;
1343 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1345 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1346 return (EOPNOTSUPP);
1347 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1348 fapi->pps_info_buf = pps->ppsinfo;
1350 case PPS_IOC_KCBIND:
1352 kapi = (struct pps_kcbind_args *)data;
1353 /* XXX Only root should be able to do this */
1354 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1356 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1358 if (kapi->edge & ~pps->ppscap)
1360 pps->kcmode = kapi->edge;
1363 return (EOPNOTSUPP);
1371 pps_init(struct pps_state *pps)
1373 pps->ppscap |= PPS_TSFMT_TSPEC;
1374 if (pps->ppscap & PPS_CAPTUREASSERT)
1375 pps->ppscap |= PPS_OFFSETASSERT;
1376 if (pps->ppscap & PPS_CAPTURECLEAR)
1377 pps->ppscap |= PPS_OFFSETCLEAR;
1381 pps_event(struct pps_state *pps, sysclock_t count, int event)
1383 struct globaldata *gd;
1384 struct timespec *tsp;
1385 struct timespec *osp;
1386 struct timespec *bt;
1399 /* Things would be easier with arrays... */
1400 if (event == PPS_CAPTUREASSERT) {
1401 tsp = &pps->ppsinfo.assert_timestamp;
1402 osp = &pps->ppsparam.assert_offset;
1403 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1404 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1405 pcount = &pps->ppscount[0];
1406 pseq = &pps->ppsinfo.assert_sequence;
1408 tsp = &pps->ppsinfo.clear_timestamp;
1409 osp = &pps->ppsparam.clear_offset;
1410 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1411 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1412 pcount = &pps->ppscount[1];
1413 pseq = &pps->ppsinfo.clear_sequence;
1416 /* Nothing really happened */
1417 if (*pcount == count)
1423 ts.tv_sec = gd->gd_time_seconds;
1424 delta = count - gd->gd_cpuclock_base;
1425 } while (ts.tv_sec != gd->gd_time_seconds);
1427 if (delta >= sys_cputimer->freq) {
1428 ts.tv_sec += delta / sys_cputimer->freq;
1429 delta %= sys_cputimer->freq;
1431 ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1432 bt = &basetime[basetime_index];
1433 ts.tv_sec += bt->tv_sec;
1434 ts.tv_nsec += bt->tv_nsec;
1435 while (ts.tv_nsec >= 1000000000) {
1436 ts.tv_nsec -= 1000000000;
1444 timespecadd(tsp, osp);
1445 if (tsp->tv_nsec < 0) {
1446 tsp->tv_nsec += 1000000000;
1452 /* magic, at its best... */
1453 tcount = count - pps->ppscount[2];
1454 pps->ppscount[2] = count;
1455 if (tcount >= sys_cputimer->freq) {
1456 delta = (1000000000 * (tcount / sys_cputimer->freq) +
1457 sys_cputimer->freq64_nsec *
1458 (tcount % sys_cputimer->freq)) >> 32;
1460 delta = (sys_cputimer->freq64_nsec * tcount) >> 32;
1462 hardpps(tsp, delta);
1468 * Return the tsc target value for a delay of (ns).
1470 * Returns -1 if the TSC is not supported.
1473 tsc_get_target(int ns)
1475 #if defined(_RDTSC_SUPPORTED_)
1476 if (cpu_feature & CPUID_TSC) {
1477 return (rdtsc() + tsc_frequency * ns / (int64_t)1000000000);
1484 * Compare the tsc against the passed target
1486 * Returns +1 if the target has been reached
1487 * Returns 0 if the target has not yet been reached
1488 * Returns -1 if the TSC is not supported.
1490 * Typical use: while (tsc_test_target(target) == 0) { ...poll... }
1493 tsc_test_target(int64_t target)
1495 #if defined(_RDTSC_SUPPORTED_)
1496 if (cpu_feature & CPUID_TSC) {
1497 if ((int64_t)(target - rdtsc()) <= 0)
1506 * Delay the specified number of nanoseconds using the tsc. This function
1507 * returns immediately if the TSC is not supported. At least one cpu_pause()
1515 clk = tsc_get_target(ns);
1517 while (tsc_test_target(clk) == 0)