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);
136 struct kinfo_cputime tmp;
138 for (cpu = 0; cpu < ncpus; ++cpu) {
139 tmp = cputime_percpu[cpu];
140 tmp.cp_sample_pc = (int64_t)globaldata_find(cpu)->gd_sample_pc;
141 tmp.cp_sample_sp = (int64_t)globaldata_find(cpu)->gd_sample_sp;
142 if ((error = SYSCTL_OUT(req, &tmp, size)) != 0)
149 SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
150 sysctl_cputime, "S,kinfo_cputime", "CPU time statistics");
153 sysctl_cp_time(SYSCTL_HANDLER_ARGS)
155 long cpu_states[5] = {0};
157 size_t size = sizeof(cpu_states);
159 for (cpu = 0; cpu < ncpus; ++cpu) {
160 cpu_states[CP_USER] += cputime_percpu[cpu].cp_user;
161 cpu_states[CP_NICE] += cputime_percpu[cpu].cp_nice;
162 cpu_states[CP_SYS] += cputime_percpu[cpu].cp_sys;
163 cpu_states[CP_INTR] += cputime_percpu[cpu].cp_intr;
164 cpu_states[CP_IDLE] += cputime_percpu[cpu].cp_idle;
167 error = SYSCTL_OUT(req, cpu_states, size);
172 SYSCTL_PROC(_kern, OID_AUTO, cp_time, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
173 sysctl_cp_time, "LU", "CPU time statistics");
176 * boottime is used to calculate the 'real' uptime. Do not confuse this with
177 * microuptime(). microtime() is not drift compensated. The real uptime
178 * with compensation is nanotime() - bootime. boottime is recalculated
179 * whenever the real time is set based on the compensated elapsed time
180 * in seconds (gd->gd_time_seconds).
182 * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
183 * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
186 * WARNING! time_second can backstep on time corrections. Also, unlike
187 * time_second, time_uptime is not a "real" time_t (seconds
188 * since the Epoch) but seconds since booting.
190 struct timespec boottime; /* boot time (realtime) for reference only */
191 time_t time_second; /* read-only 'passive' realtime in seconds */
192 time_t time_uptime; /* read-only 'passive' uptime in seconds */
195 * basetime is used to calculate the compensated real time of day. The
196 * basetime can be modified on a per-tick basis by the adjtime(),
197 * ntp_adjtime(), and sysctl-based time correction APIs.
199 * Note that frequency corrections can also be made by adjusting
202 * basetime is a tail-chasing FIFO, updated only by cpu #0. The FIFO is
203 * used on both SMP and UP systems to avoid MP races between cpu's and
204 * interrupt races on UP systems.
207 __uint32_t time_second;
208 sysclock_t cpuclock_base;
211 #define BASETIME_ARYSIZE 16
212 #define BASETIME_ARYMASK (BASETIME_ARYSIZE - 1)
213 static struct timespec basetime[BASETIME_ARYSIZE];
214 static struct hardtime hardtime[BASETIME_ARYSIZE];
215 static volatile int basetime_index;
218 sysctl_get_basetime(SYSCTL_HANDLER_ARGS)
225 * Because basetime data and index may be updated by another cpu,
226 * a load fence is required to ensure that the data we read has
227 * not been speculatively read relative to a possibly updated index.
229 index = basetime_index;
231 bt = &basetime[index];
232 error = SYSCTL_OUT(req, bt, sizeof(*bt));
236 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
237 &boottime, timespec, "System boottime");
238 SYSCTL_PROC(_kern, OID_AUTO, basetime, CTLTYPE_STRUCT|CTLFLAG_RD, 0, 0,
239 sysctl_get_basetime, "S,timespec", "System basetime");
241 static void hardclock(systimer_t info, int, struct intrframe *frame);
242 static void statclock(systimer_t info, int, struct intrframe *frame);
243 static void schedclock(systimer_t info, int, struct intrframe *frame);
244 static void getnanotime_nbt(struct timespec *nbt, struct timespec *tsp);
246 int ticks; /* system master ticks at hz */
247 int clocks_running; /* tsleep/timeout clocks operational */
248 int64_t nsec_adj; /* ntpd per-tick adjustment in nsec << 32 */
249 int64_t nsec_acc; /* accumulator */
250 int sched_ticks; /* global schedule clock ticks */
252 /* NTPD time correction fields */
253 int64_t ntp_tick_permanent; /* per-tick adjustment in nsec << 32 */
254 int64_t ntp_tick_acc; /* accumulator for per-tick adjustment */
255 int64_t ntp_delta; /* one-time correction in nsec */
256 int64_t ntp_big_delta = 1000000000;
257 int32_t ntp_tick_delta; /* current adjustment rate */
258 int32_t ntp_default_tick_delta; /* adjustment rate for ntp_delta */
259 time_t ntp_leap_second; /* time of next leap second */
260 int ntp_leap_insert; /* whether to insert or remove a second */
263 * Finish initializing clock frequencies and start all clocks running.
267 initclocks(void *dummy)
269 /*psratio = profhz / stathz;*/
273 kpmap->tsc_freq = (uint64_t)tsc_frequency;
274 kpmap->tick_freq = hz;
279 * Called on a per-cpu basis from the idle thread bootstrap on each cpu
280 * during SMP initialization.
282 * This routine is called concurrently during low-level SMP initialization
283 * and may not block in any way. Meaning, among other things, we can't
284 * acquire any tokens.
287 initclocks_pcpu(void)
289 struct globaldata *gd = mycpu;
292 if (gd->gd_cpuid == 0) {
293 gd->gd_time_seconds = 1;
294 gd->gd_cpuclock_base = sys_cputimer->count();
295 hardtime[0].time_second = gd->gd_time_seconds;
296 hardtime[0].cpuclock_base = gd->gd_cpuclock_base;
298 gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
299 gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
302 systimer_intr_enable();
308 * This routine is called on just the BSP, just after SMP initialization
309 * completes to * finish initializing any clocks that might contend/block
310 * (e.g. like on a token). We can't do this in initclocks_pcpu() because
311 * that function is called from the idle thread bootstrap for each cpu and
312 * not allowed to block at all.
316 initclocks_other(void *dummy)
318 struct globaldata *ogd = mycpu;
319 struct globaldata *gd;
322 for (n = 0; n < ncpus; ++n) {
323 lwkt_setcpu_self(globaldata_find(n));
327 * Use a non-queued periodic systimer to prevent multiple
328 * ticks from building up if the sysclock jumps forward
329 * (8254 gets reset). The sysclock will never jump backwards.
330 * Our time sync is based on the actual sysclock, not the
333 systimer_init_periodic_nq(&gd->gd_hardclock, hardclock,
335 systimer_init_periodic_nq(&gd->gd_statclock, statclock,
337 /* XXX correct the frequency for scheduler / estcpu tests */
338 systimer_init_periodic_nq(&gd->gd_schedclock, schedclock,
341 ifpoll_init_pcpu(gd->gd_cpuid);
344 lwkt_setcpu_self(ogd);
346 SYSINIT(clocks2, SI_BOOT2_POST_SMP, SI_ORDER_ANY, initclocks_other, NULL);
349 * This sets the current real time of day. Timespecs are in seconds and
350 * nanoseconds. We do not mess with gd_time_seconds and gd_cpuclock_base,
351 * instead we adjust basetime so basetime + gd_* results in the current
352 * time of day. This way the gd_* fields are guaranteed to represent
353 * a monotonically increasing 'uptime' value.
355 * When set_timeofday() is called from userland, the system call forces it
356 * onto cpu #0 since only cpu #0 can update basetime_index.
359 set_timeofday(struct timespec *ts)
361 struct timespec *nbt;
365 * XXX SMP / non-atomic basetime updates
368 ni = (basetime_index + 1) & BASETIME_ARYMASK;
372 nbt->tv_sec = ts->tv_sec - nbt->tv_sec;
373 nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec;
374 if (nbt->tv_nsec < 0) {
375 nbt->tv_nsec += 1000000000;
380 * Note that basetime diverges from boottime as the clock drift is
381 * compensated for, so we cannot do away with boottime. When setting
382 * the absolute time of day the drift is 0 (for an instant) and we
383 * can simply assign boottime to basetime.
385 * Note that nanouptime() is based on gd_time_seconds which is drift
386 * compensated up to a point (it is guaranteed to remain monotonically
387 * increasing). gd_time_seconds is thus our best uptime guess and
388 * suitable for use in the boottime calculation. It is already taken
389 * into account in the basetime calculation above.
391 boottime.tv_sec = nbt->tv_sec;
395 * We now have a new basetime, make sure all other cpus have it,
396 * then update the index.
405 * Each cpu has its own hardclock, but we only increments ticks and softticks
408 * NOTE! systimer! the MP lock might not be held here. We can only safely
409 * manipulate objects owned by the current cpu.
412 hardclock(systimer_t info, int in_ipi, struct intrframe *frame)
416 struct globaldata *gd = mycpu;
418 if ((gd->gd_reqflags & RQF_IPIQ) == 0 && lwkt_need_ipiq_process(gd)) {
419 /* Defer to doreti on passive IPIQ processing */
424 * We update the compensation base to calculate fine-grained time
425 * from the sys_cputimer on a per-cpu basis in order to avoid
426 * having to mess around with locks. sys_cputimer is assumed to
427 * be consistent across all cpus. CPU N copies the base state from
428 * CPU 0 using the same FIFO trick that we use for basetime (so we
429 * don't catch a CPU 0 update in the middle).
431 * Note that we never allow info->time (aka gd->gd_hardclock.time)
432 * to reverse index gd_cpuclock_base, but that it is possible for
433 * it to temporarily get behind in the seconds if something in the
434 * system locks interrupts for a long period of time. Since periodic
435 * timers count events, though everything should resynch again
438 if (gd->gd_cpuid == 0) {
441 cputicks = info->time - gd->gd_cpuclock_base;
442 if (cputicks >= sys_cputimer->freq) {
443 cputicks /= sys_cputimer->freq;
444 if (cputicks != 0 && cputicks != 1)
445 kprintf("Warning: hardclock missed > 1 sec\n");
446 gd->gd_time_seconds += cputicks;
447 gd->gd_cpuclock_base += sys_cputimer->freq * cputicks;
448 /* uncorrected monotonic 1-sec gran */
449 time_uptime += cputicks;
451 ni = (basetime_index + 1) & BASETIME_ARYMASK;
452 hardtime[ni].time_second = gd->gd_time_seconds;
453 hardtime[ni].cpuclock_base = gd->gd_cpuclock_base;
459 gd->gd_time_seconds = hardtime[ni].time_second;
460 gd->gd_cpuclock_base = hardtime[ni].cpuclock_base;
464 * The system-wide ticks counter and NTP related timedelta/tickdelta
465 * adjustments only occur on cpu #0. NTP adjustments are accomplished
466 * by updating basetime.
468 if (gd->gd_cpuid == 0) {
469 struct timespec *nbt;
477 if (tco->tc_poll_pps)
478 tco->tc_poll_pps(tco);
482 * Calculate the new basetime index. We are in a critical section
483 * on cpu #0 and can safely play with basetime_index. Start
484 * with the current basetime and then make adjustments.
486 ni = (basetime_index + 1) & BASETIME_ARYMASK;
488 *nbt = basetime[basetime_index];
491 * Apply adjtime corrections. (adjtime() API)
493 * adjtime() only runs on cpu #0 so our critical section is
494 * sufficient to access these variables.
496 if (ntp_delta != 0) {
497 nbt->tv_nsec += ntp_tick_delta;
498 ntp_delta -= ntp_tick_delta;
499 if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) ||
500 (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) {
501 ntp_tick_delta = ntp_delta;
506 * Apply permanent frequency corrections. (sysctl API)
508 if (ntp_tick_permanent != 0) {
509 ntp_tick_acc += ntp_tick_permanent;
510 if (ntp_tick_acc >= (1LL << 32)) {
511 nbt->tv_nsec += ntp_tick_acc >> 32;
512 ntp_tick_acc -= (ntp_tick_acc >> 32) << 32;
513 } else if (ntp_tick_acc <= -(1LL << 32)) {
514 /* Negate ntp_tick_acc to avoid shifting the sign bit. */
515 nbt->tv_nsec -= (-ntp_tick_acc) >> 32;
516 ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32;
520 if (nbt->tv_nsec >= 1000000000) {
522 nbt->tv_nsec -= 1000000000;
523 } else if (nbt->tv_nsec < 0) {
525 nbt->tv_nsec += 1000000000;
529 * Another per-tick compensation. (for ntp_adjtime() API)
532 nsec_acc += nsec_adj;
533 if (nsec_acc >= 0x100000000LL) {
534 nbt->tv_nsec += nsec_acc >> 32;
535 nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
536 } else if (nsec_acc <= -0x100000000LL) {
537 nbt->tv_nsec -= -nsec_acc >> 32;
538 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
540 if (nbt->tv_nsec >= 1000000000) {
541 nbt->tv_nsec -= 1000000000;
543 } else if (nbt->tv_nsec < 0) {
544 nbt->tv_nsec += 1000000000;
549 /************************************************************
550 * LEAP SECOND CORRECTION *
551 ************************************************************
553 * Taking into account all the corrections made above, figure
554 * out the new real time. If the seconds field has changed
555 * then apply any pending leap-second corrections.
557 getnanotime_nbt(nbt, &nts);
559 if (time_second != nts.tv_sec) {
561 * Apply leap second (sysctl API). Adjust nts for changes
562 * so we do not have to call getnanotime_nbt again.
564 if (ntp_leap_second) {
565 if (ntp_leap_second == nts.tv_sec) {
566 if (ntp_leap_insert) {
578 * Apply leap second (ntp_adjtime() API), calculate a new
579 * nsec_adj field. ntp_update_second() returns nsec_adj
580 * as a per-second value but we need it as a per-tick value.
582 leap = ntp_update_second(time_second, &nsec_adj);
588 * Update the time_second 'approximate time' global.
590 time_second = nts.tv_sec;
594 * Finally, our new basetime is ready to go live!
600 * Update kpmap on each tick. TS updates are integrated with
601 * fences and upticks allowing userland to read the data
607 w = (kpmap->upticks + 1) & 1;
608 getnanouptime(&kpmap->ts_uptime[w]);
609 getnanotime(&kpmap->ts_realtime[w]);
617 * lwkt thread scheduler fair queueing
619 lwkt_schedulerclock(curthread);
622 * softticks are handled for all cpus
624 hardclock_softtick(gd);
627 * ITimer handling is per-tick, per-cpu.
629 * We must acquire the per-process token in order for ksignal()
630 * to be non-blocking. For the moment this requires an AST fault,
631 * the ksignal() cannot be safely issued from this hard interrupt.
633 * XXX Even the trytoken here isn't right, and itimer operation in
634 * a multi threaded environment is going to be weird at the
637 if ((p = curproc) != NULL && lwkt_trytoken(&p->p_token)) {
640 ++p->p_upmap->runticks;
642 if (frame && CLKF_USERMODE(frame) &&
643 timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) &&
644 itimerdecr(&p->p_timer[ITIMER_VIRTUAL], ustick) == 0) {
645 p->p_flags |= P_SIGVTALRM;
648 if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) &&
649 itimerdecr(&p->p_timer[ITIMER_PROF], ustick) == 0) {
650 p->p_flags |= P_SIGPROF;
654 lwkt_reltoken(&p->p_token);
660 * The statistics clock typically runs at a 125Hz rate, and is intended
661 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu.
663 * NOTE! systimer! the MP lock might not be held here. We can only safely
664 * manipulate objects owned by the current cpu.
666 * The stats clock is responsible for grabbing a profiling sample.
667 * Most of the statistics are only used by user-level statistics programs.
668 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
671 * Like the other clocks, the stat clock is called from what is effectively
672 * a fast interrupt, so the context should be the thread/process that got
676 statclock(systimer_t info, int in_ipi, struct intrframe *frame)
689 * How big was our timeslice relative to the last time? Calculate
692 * NOTE: Use of microuptime() is typically MPSAFE, but usually not
693 * during early boot. Just use the systimer count to be nice
694 * to e.g. qemu. The systimer has a better chance of being
695 * MPSAFE at early boot.
697 cv = sys_cputimer->count();
698 scv = mycpu->statint.gd_statcv;
702 bump = (sys_cputimer->freq64_usec * (cv - scv)) >> 32;
708 mycpu->statint.gd_statcv = cv;
711 stv = &mycpu->gd_stattv;
712 if (stv->tv_sec == 0) {
715 bump = tv.tv_usec - stv->tv_usec +
716 (tv.tv_sec - stv->tv_sec) * 1000000;
728 if (frame && CLKF_USERMODE(frame)) {
730 * Came from userland, handle user time and deal with
733 if (p && (p->p_flags & P_PROFIL))
734 addupc_intr(p, CLKF_PC(frame), 1);
735 td->td_uticks += bump;
738 * Charge the time as appropriate
740 if (p && p->p_nice > NZERO)
741 cpu_time.cp_nice += bump;
743 cpu_time.cp_user += bump;
745 int intr_nest = mycpu->gd_intr_nesting_level;
749 * IPI processing code will bump gd_intr_nesting_level
750 * up by one, which breaks following CLKF_INTR testing,
751 * so we subtract it by one here.
757 * Kernel statistics are just like addupc_intr, only easier.
760 if (g->state == GMON_PROF_ON && frame) {
761 i = CLKF_PC(frame) - g->lowpc;
762 if (i < g->textsize) {
763 i /= HISTFRACTION * sizeof(*g->kcount);
769 #define IS_INTR_RUNNING ((frame && CLKF_INTR(intr_nest)) || CLKF_INTR_TD(td))
772 * Came from kernel mode, so we were:
773 * - handling an interrupt,
774 * - doing syscall or trap work on behalf of the current
776 * - spinning in the idle loop.
777 * Whichever it is, charge the time as appropriate.
778 * Note that we charge interrupts to the current process,
779 * regardless of whether they are ``for'' that process,
780 * so that we know how much of its real time was spent
781 * in ``non-process'' (i.e., interrupt) work.
783 * XXX assume system if frame is NULL. A NULL frame
784 * can occur if ipi processing is done from a crit_exit().
787 td->td_iticks += bump;
789 td->td_sticks += bump;
791 if (IS_INTR_RUNNING) {
793 * If we interrupted an interrupt thread, well,
794 * count it as interrupt time.
798 do_pctrack(frame, PCTRACK_INT);
800 cpu_time.cp_intr += bump;
802 if (td == &mycpu->gd_idlethread) {
804 * Even if the current thread is the idle
805 * thread it could be due to token contention
806 * in the LWKT scheduler. Count such as
809 if (mycpu->gd_reqflags & RQF_IDLECHECK_WK_MASK)
810 cpu_time.cp_sys += bump;
812 cpu_time.cp_idle += bump;
815 * System thread was running.
819 do_pctrack(frame, PCTRACK_SYS);
821 cpu_time.cp_sys += bump;
825 #undef IS_INTR_RUNNING
831 * Sample the PC when in the kernel or in an interrupt. User code can
832 * retrieve the information and generate a histogram or other output.
836 do_pctrack(struct intrframe *frame, int which)
838 struct kinfo_pctrack *pctrack;
840 pctrack = &cputime_pctrack[mycpu->gd_cpuid][which];
841 pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] =
842 (void *)CLKF_PC(frame);
847 sysctl_pctrack(SYSCTL_HANDLER_ARGS)
849 struct kinfo_pcheader head;
854 head.pc_ntrack = PCTRACK_SIZE;
855 head.pc_arysize = PCTRACK_ARYSIZE;
857 if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0)
860 for (cpu = 0; cpu < ncpus; ++cpu) {
861 for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) {
862 error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack],
863 sizeof(struct kinfo_pctrack));
872 SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
873 sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking");
878 * The scheduler clock typically runs at a 50Hz rate. NOTE! systimer,
879 * the MP lock might not be held. We can safely manipulate parts of curproc
880 * but that's about it.
882 * Each cpu has its own scheduler clock.
885 schedclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
892 if ((lp = lwkt_preempted_proc()) != NULL) {
894 * Account for cpu time used and hit the scheduler. Note
895 * that this call MUST BE MP SAFE, and the BGL IS NOT HELD
899 usched_schedulerclock(lp, info->periodic, info->time);
901 usched_schedulerclock(NULL, info->periodic, info->time);
903 if ((lp = curthread->td_lwp) != NULL) {
905 * Update resource usage integrals and maximums.
907 if ((ru = &lp->lwp_proc->p_ru) &&
908 (vm = lp->lwp_proc->p_vmspace) != NULL) {
909 ru->ru_ixrss += pgtok(vm->vm_tsize);
910 ru->ru_idrss += pgtok(vm->vm_dsize);
911 ru->ru_isrss += pgtok(vm->vm_ssize);
912 if (lwkt_trytoken(&vm->vm_map.token)) {
913 rss = pgtok(vmspace_resident_count(vm));
914 if (ru->ru_maxrss < rss)
916 lwkt_reltoken(&vm->vm_map.token);
920 /* Increment the global sched_ticks */
921 if (mycpu->gd_cpuid == 0)
926 * Compute number of ticks for the specified amount of time. The
927 * return value is intended to be used in a clock interrupt timed
928 * operation and guaranteed to meet or exceed the requested time.
929 * If the representation overflows, return INT_MAX. The minimum return
930 * value is 1 ticks and the function will average the calculation up.
931 * If any value greater then 0 microseconds is supplied, a value
932 * of at least 2 will be returned to ensure that a near-term clock
933 * interrupt does not cause the timeout to occur (degenerately) early.
935 * Note that limit checks must take into account microseconds, which is
936 * done simply by using the smaller signed long maximum instead of
937 * the unsigned long maximum.
939 * If ints have 32 bits, then the maximum value for any timeout in
940 * 10ms ticks is 248 days.
943 tvtohz_high(struct timeval *tv)
960 kprintf("tvtohz_high: negative time difference "
961 "%ld sec %ld usec\n",
965 } else if (sec <= INT_MAX / hz) {
966 ticks = (int)(sec * hz +
967 ((u_long)usec + (ustick - 1)) / ustick) + 1;
975 tstohz_high(struct timespec *ts)
992 kprintf("tstohz_high: negative time difference "
993 "%ld sec %ld nsec\n",
997 } else if (sec <= INT_MAX / hz) {
998 ticks = (int)(sec * hz +
999 ((u_long)nsec + (nstick - 1)) / nstick) + 1;
1008 * Compute number of ticks for the specified amount of time, erroring on
1009 * the side of it being too low to ensure that sleeping the returned number
1010 * of ticks will not result in a late return.
1012 * The supplied timeval may not be negative and should be normalized. A
1013 * return value of 0 is possible if the timeval converts to less then
1016 * If ints have 32 bits, then the maximum value for any timeout in
1017 * 10ms ticks is 248 days.
1020 tvtohz_low(struct timeval *tv)
1026 if (sec <= INT_MAX / hz)
1027 ticks = (int)(sec * hz + (u_long)tv->tv_usec / ustick);
1034 tstohz_low(struct timespec *ts)
1040 if (sec <= INT_MAX / hz)
1041 ticks = (int)(sec * hz + (u_long)ts->tv_nsec / nstick);
1048 * Start profiling on a process.
1050 * Kernel profiling passes proc0 which never exits and hence
1051 * keeps the profile clock running constantly.
1054 startprofclock(struct proc *p)
1056 if ((p->p_flags & P_PROFIL) == 0) {
1057 p->p_flags |= P_PROFIL;
1059 if (++profprocs == 1 && stathz != 0) {
1062 setstatclockrate(profhz);
1070 * Stop profiling on a process.
1072 * caller must hold p->p_token
1075 stopprofclock(struct proc *p)
1077 if (p->p_flags & P_PROFIL) {
1078 p->p_flags &= ~P_PROFIL;
1080 if (--profprocs == 0 && stathz != 0) {
1083 setstatclockrate(stathz);
1091 * Return information about system clocks.
1094 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
1096 struct kinfo_clockinfo clkinfo;
1098 * Construct clockinfo structure.
1101 clkinfo.ci_tick = ustick;
1102 clkinfo.ci_tickadj = ntp_default_tick_delta / 1000;
1103 clkinfo.ci_profhz = profhz;
1104 clkinfo.ci_stathz = stathz ? stathz : hz;
1105 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
1108 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
1109 0, 0, sysctl_kern_clockrate, "S,clockinfo","");
1112 * We have eight functions for looking at the clock, four for
1113 * microseconds and four for nanoseconds. For each there is fast
1114 * but less precise version "get{nano|micro}[up]time" which will
1115 * return a time which is up to 1/HZ previous to the call, whereas
1116 * the raw version "{nano|micro}[up]time" will return a timestamp
1117 * which is as precise as possible. The "up" variants return the
1118 * time relative to system boot, these are well suited for time
1119 * interval measurements.
1121 * Each cpu independently maintains the current time of day, so all
1122 * we need to do to protect ourselves from changes is to do a loop
1123 * check on the seconds field changing out from under us.
1125 * The system timer maintains a 32 bit count and due to various issues
1126 * it is possible for the calculated delta to occasionally exceed
1127 * sys_cputimer->freq. If this occurs the sys_cputimer->freq64_nsec
1128 * multiplication can easily overflow, so we deal with the case. For
1129 * uniformity we deal with the case in the usec case too.
1131 * All the [get][micro,nano][time,uptime]() routines are MPSAFE.
1134 getmicrouptime(struct timeval *tvp)
1136 struct globaldata *gd = mycpu;
1140 tvp->tv_sec = gd->gd_time_seconds;
1141 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1142 } while (tvp->tv_sec != gd->gd_time_seconds);
1144 if (delta >= sys_cputimer->freq) {
1145 tvp->tv_sec += delta / sys_cputimer->freq;
1146 delta %= sys_cputimer->freq;
1148 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1149 if (tvp->tv_usec >= 1000000) {
1150 tvp->tv_usec -= 1000000;
1156 getnanouptime(struct timespec *tsp)
1158 struct globaldata *gd = mycpu;
1162 tsp->tv_sec = gd->gd_time_seconds;
1163 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1164 } while (tsp->tv_sec != gd->gd_time_seconds);
1166 if (delta >= sys_cputimer->freq) {
1167 tsp->tv_sec += delta / sys_cputimer->freq;
1168 delta %= sys_cputimer->freq;
1170 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1174 microuptime(struct timeval *tvp)
1176 struct globaldata *gd = mycpu;
1180 tvp->tv_sec = gd->gd_time_seconds;
1181 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1182 } while (tvp->tv_sec != gd->gd_time_seconds);
1184 if (delta >= sys_cputimer->freq) {
1185 tvp->tv_sec += delta / sys_cputimer->freq;
1186 delta %= sys_cputimer->freq;
1188 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1192 nanouptime(struct timespec *tsp)
1194 struct globaldata *gd = mycpu;
1198 tsp->tv_sec = gd->gd_time_seconds;
1199 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1200 } while (tsp->tv_sec != gd->gd_time_seconds);
1202 if (delta >= sys_cputimer->freq) {
1203 tsp->tv_sec += delta / sys_cputimer->freq;
1204 delta %= sys_cputimer->freq;
1206 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1213 getmicrotime(struct timeval *tvp)
1215 struct globaldata *gd = mycpu;
1216 struct timespec *bt;
1220 tvp->tv_sec = gd->gd_time_seconds;
1221 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1222 } while (tvp->tv_sec != gd->gd_time_seconds);
1224 if (delta >= sys_cputimer->freq) {
1225 tvp->tv_sec += delta / sys_cputimer->freq;
1226 delta %= sys_cputimer->freq;
1228 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1230 bt = &basetime[basetime_index];
1232 tvp->tv_sec += bt->tv_sec;
1233 tvp->tv_usec += bt->tv_nsec / 1000;
1234 while (tvp->tv_usec >= 1000000) {
1235 tvp->tv_usec -= 1000000;
1241 getnanotime(struct timespec *tsp)
1243 struct globaldata *gd = mycpu;
1244 struct timespec *bt;
1248 tsp->tv_sec = gd->gd_time_seconds;
1249 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1250 } while (tsp->tv_sec != gd->gd_time_seconds);
1252 if (delta >= sys_cputimer->freq) {
1253 tsp->tv_sec += delta / sys_cputimer->freq;
1254 delta %= sys_cputimer->freq;
1256 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1258 bt = &basetime[basetime_index];
1260 tsp->tv_sec += bt->tv_sec;
1261 tsp->tv_nsec += bt->tv_nsec;
1262 while (tsp->tv_nsec >= 1000000000) {
1263 tsp->tv_nsec -= 1000000000;
1269 getnanotime_nbt(struct timespec *nbt, struct timespec *tsp)
1271 struct globaldata *gd = mycpu;
1275 tsp->tv_sec = gd->gd_time_seconds;
1276 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1277 } while (tsp->tv_sec != gd->gd_time_seconds);
1279 if (delta >= sys_cputimer->freq) {
1280 tsp->tv_sec += delta / sys_cputimer->freq;
1281 delta %= sys_cputimer->freq;
1283 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1285 tsp->tv_sec += nbt->tv_sec;
1286 tsp->tv_nsec += nbt->tv_nsec;
1287 while (tsp->tv_nsec >= 1000000000) {
1288 tsp->tv_nsec -= 1000000000;
1295 microtime(struct timeval *tvp)
1297 struct globaldata *gd = mycpu;
1298 struct timespec *bt;
1302 tvp->tv_sec = gd->gd_time_seconds;
1303 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1304 } while (tvp->tv_sec != gd->gd_time_seconds);
1306 if (delta >= sys_cputimer->freq) {
1307 tvp->tv_sec += delta / sys_cputimer->freq;
1308 delta %= sys_cputimer->freq;
1310 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1312 bt = &basetime[basetime_index];
1314 tvp->tv_sec += bt->tv_sec;
1315 tvp->tv_usec += bt->tv_nsec / 1000;
1316 while (tvp->tv_usec >= 1000000) {
1317 tvp->tv_usec -= 1000000;
1323 nanotime(struct timespec *tsp)
1325 struct globaldata *gd = mycpu;
1326 struct timespec *bt;
1330 tsp->tv_sec = gd->gd_time_seconds;
1331 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1332 } while (tsp->tv_sec != gd->gd_time_seconds);
1334 if (delta >= sys_cputimer->freq) {
1335 tsp->tv_sec += delta / sys_cputimer->freq;
1336 delta %= sys_cputimer->freq;
1338 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1340 bt = &basetime[basetime_index];
1342 tsp->tv_sec += bt->tv_sec;
1343 tsp->tv_nsec += bt->tv_nsec;
1344 while (tsp->tv_nsec >= 1000000000) {
1345 tsp->tv_nsec -= 1000000000;
1351 * Get an approximate time_t. It does not have to be accurate. This
1352 * function is called only from KTR and can be called with the system in
1353 * any state so do not use a critical section or other complex operation
1356 * NOTE: This is not exactly synchronized with real time. To do that we
1357 * would have to do what microtime does and check for a nanoseconds
1361 get_approximate_time_t(void)
1363 struct globaldata *gd = mycpu;
1364 struct timespec *bt;
1366 bt = &basetime[basetime_index];
1367 return(gd->gd_time_seconds + bt->tv_sec);
1371 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1374 struct pps_fetch_args *fapi;
1376 struct pps_kcbind_args *kapi;
1380 case PPS_IOC_CREATE:
1382 case PPS_IOC_DESTROY:
1384 case PPS_IOC_SETPARAMS:
1385 app = (pps_params_t *)data;
1386 if (app->mode & ~pps->ppscap)
1388 pps->ppsparam = *app;
1390 case PPS_IOC_GETPARAMS:
1391 app = (pps_params_t *)data;
1392 *app = pps->ppsparam;
1393 app->api_version = PPS_API_VERS_1;
1395 case PPS_IOC_GETCAP:
1396 *(int*)data = pps->ppscap;
1399 fapi = (struct pps_fetch_args *)data;
1400 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1402 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1403 return (EOPNOTSUPP);
1404 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1405 fapi->pps_info_buf = pps->ppsinfo;
1407 case PPS_IOC_KCBIND:
1409 kapi = (struct pps_kcbind_args *)data;
1410 /* XXX Only root should be able to do this */
1411 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1413 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1415 if (kapi->edge & ~pps->ppscap)
1417 pps->kcmode = kapi->edge;
1420 return (EOPNOTSUPP);
1428 pps_init(struct pps_state *pps)
1430 pps->ppscap |= PPS_TSFMT_TSPEC;
1431 if (pps->ppscap & PPS_CAPTUREASSERT)
1432 pps->ppscap |= PPS_OFFSETASSERT;
1433 if (pps->ppscap & PPS_CAPTURECLEAR)
1434 pps->ppscap |= PPS_OFFSETCLEAR;
1438 pps_event(struct pps_state *pps, sysclock_t count, int event)
1440 struct globaldata *gd;
1441 struct timespec *tsp;
1442 struct timespec *osp;
1443 struct timespec *bt;
1461 /* Things would be easier with arrays... */
1462 if (event == PPS_CAPTUREASSERT) {
1463 tsp = &pps->ppsinfo.assert_timestamp;
1464 osp = &pps->ppsparam.assert_offset;
1465 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1466 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1467 pcount = &pps->ppscount[0];
1468 pseq = &pps->ppsinfo.assert_sequence;
1470 tsp = &pps->ppsinfo.clear_timestamp;
1471 osp = &pps->ppsparam.clear_offset;
1472 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1473 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1474 pcount = &pps->ppscount[1];
1475 pseq = &pps->ppsinfo.clear_sequence;
1478 /* Nothing really happened */
1479 if (*pcount == count)
1485 ts.tv_sec = gd->gd_time_seconds;
1486 delta = count - gd->gd_cpuclock_base;
1487 } while (ts.tv_sec != gd->gd_time_seconds);
1489 if (delta >= sys_cputimer->freq) {
1490 ts.tv_sec += delta / sys_cputimer->freq;
1491 delta %= sys_cputimer->freq;
1493 ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1494 ni = basetime_index;
1497 ts.tv_sec += bt->tv_sec;
1498 ts.tv_nsec += bt->tv_nsec;
1499 while (ts.tv_nsec >= 1000000000) {
1500 ts.tv_nsec -= 1000000000;
1508 timespecadd(tsp, osp);
1509 if (tsp->tv_nsec < 0) {
1510 tsp->tv_nsec += 1000000000;
1516 /* magic, at its best... */
1517 tcount = count - pps->ppscount[2];
1518 pps->ppscount[2] = count;
1519 if (tcount >= sys_cputimer->freq) {
1520 delta = (1000000000 * (tcount / sys_cputimer->freq) +
1521 sys_cputimer->freq64_nsec *
1522 (tcount % sys_cputimer->freq)) >> 32;
1524 delta = (sys_cputimer->freq64_nsec * tcount) >> 32;
1526 hardpps(tsp, delta);
1532 * Return the tsc target value for a delay of (ns).
1534 * Returns -1 if the TSC is not supported.
1537 tsc_get_target(int ns)
1539 #if defined(_RDTSC_SUPPORTED_)
1540 if (cpu_feature & CPUID_TSC) {
1541 return (rdtsc() + tsc_frequency * ns / (int64_t)1000000000);
1548 * Compare the tsc against the passed target
1550 * Returns +1 if the target has been reached
1551 * Returns 0 if the target has not yet been reached
1552 * Returns -1 if the TSC is not supported.
1554 * Typical use: while (tsc_test_target(target) == 0) { ...poll... }
1557 tsc_test_target(int64_t target)
1559 #if defined(_RDTSC_SUPPORTED_)
1560 if (cpu_feature & CPUID_TSC) {
1561 if ((int64_t)(target - rdtsc()) <= 0)
1570 * Delay the specified number of nanoseconds using the tsc. This function
1571 * returns immediately if the TSC is not supported. At least one cpu_pause()
1579 clk = tsc_get_target(ns);
1581 while (tsc_test_target(clk) == 0)