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_pctrack.h"
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>
80 #include <sys/malloc.h>
81 #include <sys/resource.h>
82 #include <sys/resourcevar.h>
83 #include <sys/signalvar.h>
85 #include <sys/timex.h>
86 #include <sys/timepps.h>
87 #include <sys/upmap.h>
89 #include <sys/sysctl.h>
90 #include <sys/kcollect.h>
94 #include <vm/vm_map.h>
95 #include <vm/vm_extern.h>
97 #include <sys/thread2.h>
98 #include <sys/spinlock2.h>
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>
108 static void do_pctrack(struct intrframe *frame, int which);
111 static void initclocks (void *dummy);
112 SYSINIT(clocks, SI_BOOT2_CLOCKS, SI_ORDER_FIRST, initclocks, NULL);
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.
119 struct kinfo_cputime cputime_percpu[MAXCPU];
121 struct kinfo_pcheader cputime_pcheader = { PCTRACK_SIZE, PCTRACK_ARYSIZE };
122 struct kinfo_pctrack cputime_pctrack[MAXCPU][PCTRACK_SIZE];
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 , "");
131 sysctl_cputime(SYSCTL_HANDLER_ARGS)
135 size_t size = sizeof(struct kinfo_cputime);
136 struct kinfo_cputime tmp;
139 * NOTE: For security reasons, only root can sniff %rip
141 root_error = priv_check_cred(curthread->td_ucred, PRIV_ROOT, 0);
143 for (cpu = 0; cpu < ncpus; ++cpu) {
144 tmp = cputime_percpu[cpu];
145 if (root_error == 0) {
147 (int64_t)globaldata_find(cpu)->gd_sample_pc;
149 (int64_t)globaldata_find(cpu)->gd_sample_sp;
151 if ((error = SYSCTL_OUT(req, &tmp, size)) != 0)
155 if (root_error == 0) {
157 int n = sniff_target;
167 SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
168 sysctl_cputime, "S,kinfo_cputime", "CPU time statistics");
171 sysctl_cp_time(SYSCTL_HANDLER_ARGS)
173 long cpu_states[CPUSTATES] = {0};
175 size_t size = sizeof(cpu_states);
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;
185 error = SYSCTL_OUT(req, cpu_states, size);
190 SYSCTL_PROC(_kern, OID_AUTO, cp_time, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
191 sysctl_cp_time, "LU", "CPU time statistics");
194 sysctl_cp_times(SYSCTL_HANDLER_ARGS)
196 long cpu_states[CPUSTATES] = {0};
198 size_t size = sizeof(cpu_states);
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);
212 SYSCTL_PROC(_kern, OID_AUTO, cp_times, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
213 sysctl_cp_times, "LU", "per-CPU time statistics");
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).
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
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.
230 struct timespec boottime; /* boot time (realtime) for reference only */
231 time_t time_second; /* read-only 'passive' realtime in seconds */
232 time_t time_uptime; /* read-only 'passive' uptime in seconds */
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.
239 * Note that frequency corrections can also be made by adjusting
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.
247 __uint32_t time_second;
248 sysclock_t cpuclock_base;
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;
258 sysctl_get_basetime(SYSCTL_HANDLER_ARGS)
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.
269 index = basetime_index;
271 bt = &basetime[index];
272 error = SYSCTL_OUT(req, bt, sizeof(*bt));
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");
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);
286 int ticks; /* system master ticks at hz */
287 int clocks_running; /* tsleep/timeout clocks operational */
288 int64_t nsec_adj; /* ntpd per-tick adjustment in nsec << 32 */
289 int64_t nsec_acc; /* accumulator */
290 int sched_ticks; /* global schedule clock ticks */
292 /* NTPD time correction fields */
293 int64_t ntp_tick_permanent; /* per-tick adjustment in nsec << 32 */
294 int64_t ntp_tick_acc; /* accumulator for per-tick adjustment */
295 int64_t ntp_delta; /* one-time correction in nsec */
296 int64_t ntp_big_delta = 1000000000;
297 int32_t ntp_tick_delta; /* current adjustment rate */
298 int32_t ntp_default_tick_delta; /* adjustment rate for ntp_delta */
299 time_t ntp_leap_second; /* time of next leap second */
300 int ntp_leap_insert; /* whether to insert or remove a second */
301 struct spinlock ntp_spin;
304 * Finish initializing clock frequencies and start all clocks running.
308 initclocks(void *dummy)
310 /*psratio = profhz / stathz;*/
311 spin_init(&ntp_spin, "ntp");
315 kpmap->tsc_freq = tsc_frequency;
316 kpmap->tick_freq = hz;
321 * Called on a per-cpu basis from the idle thread bootstrap on each cpu
322 * during SMP initialization.
324 * This routine is called concurrently during low-level SMP initialization
325 * and may not block in any way. Meaning, among other things, we can't
326 * acquire any tokens.
329 initclocks_pcpu(void)
331 struct globaldata *gd = mycpu;
334 if (gd->gd_cpuid == 0) {
335 gd->gd_time_seconds = 1;
336 gd->gd_cpuclock_base = sys_cputimer->count();
337 hardtime[0].time_second = gd->gd_time_seconds;
338 hardtime[0].cpuclock_base = gd->gd_cpuclock_base;
340 gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
341 gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
344 systimer_intr_enable();
350 * Called on a 10-second interval after the system is operational.
351 * Return the collection data for USERPCT and install the data for
352 * SYSTPCT and IDLEPCT.
356 collect_cputime_callback(int n)
358 static long cpu_base[CPUSTATES];
359 long cpu_states[CPUSTATES];
364 bzero(cpu_states, sizeof(cpu_states));
365 for (n = 0; n < ncpus; ++n) {
366 cpu_states[CP_USER] += cputime_percpu[n].cp_user;
367 cpu_states[CP_NICE] += cputime_percpu[n].cp_nice;
368 cpu_states[CP_SYS] += cputime_percpu[n].cp_sys;
369 cpu_states[CP_INTR] += cputime_percpu[n].cp_intr;
370 cpu_states[CP_IDLE] += cputime_percpu[n].cp_idle;
374 for (n = 0; n < CPUSTATES; ++n) {
375 total = cpu_states[n] - cpu_base[n];
376 cpu_base[n] = cpu_states[n];
377 cpu_states[n] = total;
380 if (acc == 0) /* prevent degenerate divide by 0 */
382 lsb = acc / (10000 * 2);
383 kcollect_setvalue(KCOLLECT_SYSTPCT,
384 (cpu_states[CP_SYS] + lsb) * 10000 / acc);
385 kcollect_setvalue(KCOLLECT_IDLEPCT,
386 (cpu_states[CP_IDLE] + lsb) * 10000 / acc);
387 kcollect_setvalue(KCOLLECT_INTRPCT,
388 (cpu_states[CP_INTR] + lsb) * 10000 / acc);
389 return((cpu_states[CP_USER] + cpu_states[CP_NICE] + lsb) * 10000 / acc);
393 * This routine is called on just the BSP, just after SMP initialization
394 * completes to * finish initializing any clocks that might contend/block
395 * (e.g. like on a token). We can't do this in initclocks_pcpu() because
396 * that function is called from the idle thread bootstrap for each cpu and
397 * not allowed to block at all.
401 initclocks_other(void *dummy)
403 struct globaldata *ogd = mycpu;
404 struct globaldata *gd;
407 for (n = 0; n < ncpus; ++n) {
408 lwkt_setcpu_self(globaldata_find(n));
412 * Use a non-queued periodic systimer to prevent multiple
413 * ticks from building up if the sysclock jumps forward
414 * (8254 gets reset). The sysclock will never jump backwards.
415 * Our time sync is based on the actual sysclock, not the
418 * Install statclock before hardclock to prevent statclock
419 * from misinterpreting gd_flags for tick assignment when
422 systimer_init_periodic_flags(&gd->gd_statclock, statclock,
424 SYSTF_MSSYNC | SYSTF_FIRST);
425 systimer_init_periodic_flags(&gd->gd_hardclock, hardclock,
426 NULL, hz, SYSTF_MSSYNC);
428 lwkt_setcpu_self(ogd);
431 * Regular data collection
433 kcollect_register(KCOLLECT_USERPCT, "user", collect_cputime_callback,
434 KCOLLECT_SCALE(KCOLLECT_USERPCT_FORMAT, 0));
435 kcollect_register(KCOLLECT_SYSTPCT, "syst", NULL,
436 KCOLLECT_SCALE(KCOLLECT_SYSTPCT_FORMAT, 0));
437 kcollect_register(KCOLLECT_IDLEPCT, "idle", NULL,
438 KCOLLECT_SCALE(KCOLLECT_IDLEPCT_FORMAT, 0));
440 SYSINIT(clocks2, SI_BOOT2_POST_SMP, SI_ORDER_ANY, initclocks_other, NULL);
443 * This method is called on just the BSP, after all the usched implementations
444 * are initialized. This avoids races between usched initialization functions
445 * and usched_schedulerclock().
449 initclocks_usched(void *dummy)
451 struct globaldata *ogd = mycpu;
452 struct globaldata *gd;
455 for (n = 0; n < ncpus; ++n) {
456 lwkt_setcpu_self(globaldata_find(n));
459 /* XXX correct the frequency for scheduler / estcpu tests */
460 systimer_init_periodic_flags(&gd->gd_schedclock, schedclock,
461 NULL, ESTCPUFREQ, SYSTF_MSSYNC);
463 lwkt_setcpu_self(ogd);
465 SYSINIT(clocks3, SI_BOOT2_USCHED, SI_ORDER_ANY, initclocks_usched, NULL);
468 * This sets the current real time of day. Timespecs are in seconds and
469 * nanoseconds. We do not mess with gd_time_seconds and gd_cpuclock_base,
470 * instead we adjust basetime so basetime + gd_* results in the current
471 * time of day. This way the gd_* fields are guaranteed to represent
472 * a monotonically increasing 'uptime' value.
474 * When set_timeofday() is called from userland, the system call forces it
475 * onto cpu #0 since only cpu #0 can update basetime_index.
478 set_timeofday(struct timespec *ts)
480 struct timespec *nbt;
484 * XXX SMP / non-atomic basetime updates
487 ni = (basetime_index + 1) & BASETIME_ARYMASK;
491 nbt->tv_sec = ts->tv_sec - nbt->tv_sec;
492 nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec;
493 if (nbt->tv_nsec < 0) {
494 nbt->tv_nsec += 1000000000;
499 * Note that basetime diverges from boottime as the clock drift is
500 * compensated for, so we cannot do away with boottime. When setting
501 * the absolute time of day the drift is 0 (for an instant) and we
502 * can simply assign boottime to basetime.
504 * Note that nanouptime() is based on gd_time_seconds which is drift
505 * compensated up to a point (it is guaranteed to remain monotonically
506 * increasing). gd_time_seconds is thus our best uptime guess and
507 * suitable for use in the boottime calculation. It is already taken
508 * into account in the basetime calculation above.
510 spin_lock(&ntp_spin);
511 boottime.tv_sec = nbt->tv_sec;
515 * We now have a new basetime, make sure all other cpus have it,
516 * then update the index.
520 spin_unlock(&ntp_spin);
526 * Each cpu has its own hardclock, but we only increments ticks and softticks
529 * NOTE! systimer! the MP lock might not be held here. We can only safely
530 * manipulate objects owned by the current cpu.
533 hardclock(systimer_t info, int in_ipi, struct intrframe *frame)
537 struct globaldata *gd = mycpu;
539 if ((gd->gd_reqflags & RQF_IPIQ) == 0 && lwkt_need_ipiq_process(gd)) {
540 /* Defer to doreti on passive IPIQ processing */
545 * We update the compensation base to calculate fine-grained time
546 * from the sys_cputimer on a per-cpu basis in order to avoid
547 * having to mess around with locks. sys_cputimer is assumed to
548 * be consistent across all cpus. CPU N copies the base state from
549 * CPU 0 using the same FIFO trick that we use for basetime (so we
550 * don't catch a CPU 0 update in the middle).
552 * Note that we never allow info->time (aka gd->gd_hardclock.time)
553 * to reverse index gd_cpuclock_base, but that it is possible for
554 * it to temporarily get behind in the seconds if something in the
555 * system locks interrupts for a long period of time. Since periodic
556 * timers count events, though everything should resynch again
559 if (gd->gd_cpuid == 0) {
562 cputicks = info->time - gd->gd_cpuclock_base;
563 if (cputicks >= sys_cputimer->freq) {
564 cputicks /= sys_cputimer->freq;
565 if (cputicks != 0 && cputicks != 1)
566 kprintf("Warning: hardclock missed > 1 sec\n");
567 gd->gd_time_seconds += cputicks;
568 gd->gd_cpuclock_base += sys_cputimer->freq * cputicks;
569 /* uncorrected monotonic 1-sec gran */
570 time_uptime += cputicks;
572 ni = (basetime_index + 1) & BASETIME_ARYMASK;
573 hardtime[ni].time_second = gd->gd_time_seconds;
574 hardtime[ni].cpuclock_base = gd->gd_cpuclock_base;
580 gd->gd_time_seconds = hardtime[ni].time_second;
581 gd->gd_cpuclock_base = hardtime[ni].cpuclock_base;
585 * The system-wide ticks counter and NTP related timedelta/tickdelta
586 * adjustments only occur on cpu #0. NTP adjustments are accomplished
587 * by updating basetime.
589 if (gd->gd_cpuid == 0) {
590 struct timespec *nbt;
598 if (tco->tc_poll_pps)
599 tco->tc_poll_pps(tco);
603 * Calculate the new basetime index. We are in a critical section
604 * on cpu #0 and can safely play with basetime_index. Start
605 * with the current basetime and then make adjustments.
607 ni = (basetime_index + 1) & BASETIME_ARYMASK;
609 *nbt = basetime[basetime_index];
612 * ntp adjustments only occur on cpu 0 and are protected by
613 * ntp_spin. This spinlock virtually never conflicts.
615 spin_lock(&ntp_spin);
618 * Apply adjtime corrections. (adjtime() API)
620 * adjtime() only runs on cpu #0 so our critical section is
621 * sufficient to access these variables.
623 if (ntp_delta != 0) {
624 nbt->tv_nsec += ntp_tick_delta;
625 ntp_delta -= ntp_tick_delta;
626 if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) ||
627 (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) {
628 ntp_tick_delta = ntp_delta;
633 * Apply permanent frequency corrections. (sysctl API)
635 if (ntp_tick_permanent != 0) {
636 ntp_tick_acc += ntp_tick_permanent;
637 if (ntp_tick_acc >= (1LL << 32)) {
638 nbt->tv_nsec += ntp_tick_acc >> 32;
639 ntp_tick_acc -= (ntp_tick_acc >> 32) << 32;
640 } else if (ntp_tick_acc <= -(1LL << 32)) {
641 /* Negate ntp_tick_acc to avoid shifting the sign bit. */
642 nbt->tv_nsec -= (-ntp_tick_acc) >> 32;
643 ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32;
647 if (nbt->tv_nsec >= 1000000000) {
649 nbt->tv_nsec -= 1000000000;
650 } else if (nbt->tv_nsec < 0) {
652 nbt->tv_nsec += 1000000000;
656 * Another per-tick compensation. (for ntp_adjtime() API)
659 nsec_acc += nsec_adj;
660 if (nsec_acc >= 0x100000000LL) {
661 nbt->tv_nsec += nsec_acc >> 32;
662 nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
663 } else if (nsec_acc <= -0x100000000LL) {
664 nbt->tv_nsec -= -nsec_acc >> 32;
665 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
667 if (nbt->tv_nsec >= 1000000000) {
668 nbt->tv_nsec -= 1000000000;
670 } else if (nbt->tv_nsec < 0) {
671 nbt->tv_nsec += 1000000000;
675 spin_unlock(&ntp_spin);
677 /************************************************************
678 * LEAP SECOND CORRECTION *
679 ************************************************************
681 * Taking into account all the corrections made above, figure
682 * out the new real time. If the seconds field has changed
683 * then apply any pending leap-second corrections.
685 getnanotime_nbt(nbt, &nts);
687 if (time_second != nts.tv_sec) {
689 * Apply leap second (sysctl API). Adjust nts for changes
690 * so we do not have to call getnanotime_nbt again.
692 if (ntp_leap_second) {
693 if (ntp_leap_second == nts.tv_sec) {
694 if (ntp_leap_insert) {
706 * Apply leap second (ntp_adjtime() API), calculate a new
707 * nsec_adj field. ntp_update_second() returns nsec_adj
708 * as a per-second value but we need it as a per-tick value.
710 leap = ntp_update_second(time_second, &nsec_adj);
716 * Update the time_second 'approximate time' global.
718 time_second = nts.tv_sec;
722 * Finally, our new basetime is ready to go live!
728 * Update kpmap on each tick. TS updates are integrated with
729 * fences and upticks allowing userland to read the data
735 w = (kpmap->upticks + 1) & 1;
736 getnanouptime(&kpmap->ts_uptime[w]);
737 getnanotime(&kpmap->ts_realtime[w]);
745 * lwkt thread scheduler fair queueing
747 lwkt_schedulerclock(curthread);
750 * softticks are handled for all cpus
752 hardclock_softtick(gd);
755 * Rollup accumulated vmstats, copy-back for critical path checks.
757 vmstats_rollup_cpu(gd);
758 vfscache_rollup_cpu(gd);
759 mycpu->gd_vmstats = vmstats;
762 * ITimer handling is per-tick, per-cpu.
764 * We must acquire the per-process token in order for ksignal()
765 * to be non-blocking. For the moment this requires an AST fault,
766 * the ksignal() cannot be safely issued from this hard interrupt.
768 * XXX Even the trytoken here isn't right, and itimer operation in
769 * a multi threaded environment is going to be weird at the
772 if ((p = curproc) != NULL && lwkt_trytoken(&p->p_token)) {
775 ++p->p_upmap->runticks;
777 if (frame && CLKF_USERMODE(frame) &&
778 timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) &&
779 itimerdecr(&p->p_timer[ITIMER_VIRTUAL], ustick) == 0) {
780 p->p_flags |= P_SIGVTALRM;
783 if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) &&
784 itimerdecr(&p->p_timer[ITIMER_PROF], ustick) == 0) {
785 p->p_flags |= P_SIGPROF;
789 lwkt_reltoken(&p->p_token);
795 * The statistics clock typically runs at a 125Hz rate, and is intended
796 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu.
798 * NOTE! systimer! the MP lock might not be held here. We can only safely
799 * manipulate objects owned by the current cpu.
801 * The stats clock is responsible for grabbing a profiling sample.
802 * Most of the statistics are only used by user-level statistics programs.
803 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
806 * Like the other clocks, the stat clock is called from what is effectively
807 * a fast interrupt, so the context should be the thread/process that got
811 statclock(systimer_t info, int in_ipi, struct intrframe *frame)
813 globaldata_t gd = mycpu;
821 * How big was our timeslice relative to the last time? Calculate
824 * NOTE: Use of microuptime() is typically MPSAFE, but usually not
825 * during early boot. Just use the systimer count to be nice
826 * to e.g. qemu. The systimer has a better chance of being
827 * MPSAFE at early boot.
829 cv = sys_cputimer->count();
830 scv = gd->statint.gd_statcv;
834 bump = (sys_cputimer->freq64_usec * (cv - scv)) >> 32;
840 gd->statint.gd_statcv = cv;
843 stv = &gd->gd_stattv;
844 if (stv->tv_sec == 0) {
847 bump = tv.tv_usec - stv->tv_usec +
848 (tv.tv_sec - stv->tv_sec) * 1000000;
860 if (frame && CLKF_USERMODE(frame)) {
862 * Came from userland, handle user time and deal with
865 if (p && (p->p_flags & P_PROFIL))
866 addupc_intr(p, CLKF_PC(frame), 1);
867 td->td_uticks += bump;
870 * Charge the time as appropriate
872 if (p && p->p_nice > NZERO)
873 cpu_time.cp_nice += bump;
875 cpu_time.cp_user += bump;
877 int intr_nest = gd->gd_intr_nesting_level;
881 * IPI processing code will bump gd_intr_nesting_level
882 * up by one, which breaks following CLKF_INTR testing,
883 * so we subtract it by one here.
888 #define IS_INTR_RUNNING ((frame && CLKF_INTR(intr_nest)) || CLKF_INTR_TD(td))
891 * Came from kernel mode, so we were:
892 * - handling an interrupt,
893 * - doing syscall or trap work on behalf of the current
895 * - spinning in the idle loop.
896 * Whichever it is, charge the time as appropriate.
897 * Note that we charge interrupts to the current process,
898 * regardless of whether they are ``for'' that process,
899 * so that we know how much of its real time was spent
900 * in ``non-process'' (i.e., interrupt) work.
902 * XXX assume system if frame is NULL. A NULL frame
903 * can occur if ipi processing is done from a crit_exit().
905 if (IS_INTR_RUNNING ||
906 (gd->gd_reqflags & RQF_INTPEND)) {
908 * If we interrupted an interrupt thread, well,
909 * count it as interrupt time.
911 td->td_iticks += bump;
914 do_pctrack(frame, PCTRACK_INT);
916 cpu_time.cp_intr += bump;
917 } else if (gd->gd_flags & GDF_VIRTUSER) {
919 * The vkernel doesn't do a good job providing trap
920 * frames that we can test. If the GDF_VIRTUSER
921 * flag is set we probably interrupted user mode.
923 * We also use this flag on the host when entering
926 td->td_uticks += bump;
929 * Charge the time as appropriate
931 if (p && p->p_nice > NZERO)
932 cpu_time.cp_nice += bump;
934 cpu_time.cp_user += bump;
936 td->td_sticks += bump;
937 if (td == &gd->gd_idlethread) {
939 * We want to count token contention as
940 * system time. When token contention occurs
941 * the cpu may only be outside its critical
942 * section while switching through the idle
943 * thread. In this situation, various flags
944 * will be set in gd_reqflags.
946 if (gd->gd_reqflags & RQF_IDLECHECK_WK_MASK)
947 cpu_time.cp_sys += bump;
949 cpu_time.cp_idle += bump;
952 * System thread was running.
956 do_pctrack(frame, PCTRACK_SYS);
958 cpu_time.cp_sys += bump;
962 #undef IS_INTR_RUNNING
968 * Sample the PC when in the kernel or in an interrupt. User code can
969 * retrieve the information and generate a histogram or other output.
973 do_pctrack(struct intrframe *frame, int which)
975 struct kinfo_pctrack *pctrack;
977 pctrack = &cputime_pctrack[mycpu->gd_cpuid][which];
978 pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] =
979 (void *)CLKF_PC(frame);
984 sysctl_pctrack(SYSCTL_HANDLER_ARGS)
986 struct kinfo_pcheader head;
991 head.pc_ntrack = PCTRACK_SIZE;
992 head.pc_arysize = PCTRACK_ARYSIZE;
994 if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0)
997 for (cpu = 0; cpu < ncpus; ++cpu) {
998 for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) {
999 error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack],
1000 sizeof(struct kinfo_pctrack));
1009 SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
1010 sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking");
1015 * The scheduler clock typically runs at a 50Hz rate. NOTE! systimer,
1016 * the MP lock might not be held. We can safely manipulate parts of curproc
1017 * but that's about it.
1019 * Each cpu has its own scheduler clock.
1022 schedclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
1029 if ((lp = lwkt_preempted_proc()) != NULL) {
1031 * Account for cpu time used and hit the scheduler. Note
1032 * that this call MUST BE MP SAFE, and the BGL IS NOT HELD
1036 usched_schedulerclock(lp, info->periodic, info->time);
1038 usched_schedulerclock(NULL, info->periodic, info->time);
1040 if ((lp = curthread->td_lwp) != NULL) {
1042 * Update resource usage integrals and maximums.
1044 if ((ru = &lp->lwp_proc->p_ru) &&
1045 (vm = lp->lwp_proc->p_vmspace) != NULL) {
1046 ru->ru_ixrss += pgtok(btoc(vm->vm_tsize));
1047 ru->ru_idrss += pgtok(btoc(vm->vm_dsize));
1048 ru->ru_isrss += pgtok(btoc(vm->vm_ssize));
1049 if (lwkt_trytoken(&vm->vm_map.token)) {
1050 rss = pgtok(vmspace_resident_count(vm));
1051 if (ru->ru_maxrss < rss)
1052 ru->ru_maxrss = rss;
1053 lwkt_reltoken(&vm->vm_map.token);
1057 /* Increment the global sched_ticks */
1058 if (mycpu->gd_cpuid == 0)
1063 * Compute number of ticks for the specified amount of time. The
1064 * return value is intended to be used in a clock interrupt timed
1065 * operation and guaranteed to meet or exceed the requested time.
1066 * If the representation overflows, return INT_MAX. The minimum return
1067 * value is 1 ticks and the function will average the calculation up.
1068 * If any value greater then 0 microseconds is supplied, a value
1069 * of at least 2 will be returned to ensure that a near-term clock
1070 * interrupt does not cause the timeout to occur (degenerately) early.
1072 * Note that limit checks must take into account microseconds, which is
1073 * done simply by using the smaller signed long maximum instead of
1074 * the unsigned long maximum.
1076 * If ints have 32 bits, then the maximum value for any timeout in
1077 * 10ms ticks is 248 days.
1080 tvtohz_high(struct timeval *tv)
1097 kprintf("tvtohz_high: negative time difference "
1098 "%ld sec %ld usec\n",
1102 } else if (sec <= INT_MAX / hz) {
1103 ticks = (int)(sec * hz +
1104 ((u_long)usec + (ustick - 1)) / ustick) + 1;
1112 tstohz_high(struct timespec *ts)
1129 kprintf("tstohz_high: negative time difference "
1130 "%ld sec %ld nsec\n",
1134 } else if (sec <= INT_MAX / hz) {
1135 ticks = (int)(sec * hz +
1136 ((u_long)nsec + (nstick - 1)) / nstick) + 1;
1145 * Compute number of ticks for the specified amount of time, erroring on
1146 * the side of it being too low to ensure that sleeping the returned number
1147 * of ticks will not result in a late return.
1149 * The supplied timeval may not be negative and should be normalized. A
1150 * return value of 0 is possible if the timeval converts to less then
1153 * If ints have 32 bits, then the maximum value for any timeout in
1154 * 10ms ticks is 248 days.
1157 tvtohz_low(struct timeval *tv)
1163 if (sec <= INT_MAX / hz)
1164 ticks = (int)(sec * hz + (u_long)tv->tv_usec / ustick);
1171 tstohz_low(struct timespec *ts)
1177 if (sec <= INT_MAX / hz)
1178 ticks = (int)(sec * hz + (u_long)ts->tv_nsec / nstick);
1185 * Start profiling on a process.
1187 * Caller must hold p->p_token();
1189 * Kernel profiling passes proc0 which never exits and hence
1190 * keeps the profile clock running constantly.
1193 startprofclock(struct proc *p)
1195 if ((p->p_flags & P_PROFIL) == 0) {
1196 p->p_flags |= P_PROFIL;
1198 if (++profprocs == 1 && stathz != 0) {
1201 setstatclockrate(profhz);
1209 * Stop profiling on a process.
1211 * caller must hold p->p_token
1214 stopprofclock(struct proc *p)
1216 if (p->p_flags & P_PROFIL) {
1217 p->p_flags &= ~P_PROFIL;
1219 if (--profprocs == 0 && stathz != 0) {
1222 setstatclockrate(stathz);
1230 * Return information about system clocks.
1233 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
1235 struct kinfo_clockinfo clkinfo;
1237 * Construct clockinfo structure.
1240 clkinfo.ci_tick = ustick;
1241 clkinfo.ci_tickadj = ntp_default_tick_delta / 1000;
1242 clkinfo.ci_profhz = profhz;
1243 clkinfo.ci_stathz = stathz ? stathz : hz;
1244 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
1247 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
1248 0, 0, sysctl_kern_clockrate, "S,clockinfo","");
1251 * We have eight functions for looking at the clock, four for
1252 * microseconds and four for nanoseconds. For each there is fast
1253 * but less precise version "get{nano|micro}[up]time" which will
1254 * return a time which is up to 1/HZ previous to the call, whereas
1255 * the raw version "{nano|micro}[up]time" will return a timestamp
1256 * which is as precise as possible. The "up" variants return the
1257 * time relative to system boot, these are well suited for time
1258 * interval measurements.
1260 * Each cpu independently maintains the current time of day, so all
1261 * we need to do to protect ourselves from changes is to do a loop
1262 * check on the seconds field changing out from under us.
1264 * The system timer maintains a 32 bit count and due to various issues
1265 * it is possible for the calculated delta to occasionally exceed
1266 * sys_cputimer->freq. If this occurs the sys_cputimer->freq64_nsec
1267 * multiplication can easily overflow, so we deal with the case. For
1268 * uniformity we deal with the case in the usec case too.
1270 * All the [get][micro,nano][time,uptime]() routines are MPSAFE.
1273 getmicrouptime(struct timeval *tvp)
1275 struct globaldata *gd = mycpu;
1279 tvp->tv_sec = gd->gd_time_seconds;
1280 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1281 } while (tvp->tv_sec != gd->gd_time_seconds);
1283 if (delta >= sys_cputimer->freq) {
1284 tvp->tv_sec += delta / sys_cputimer->freq;
1285 delta %= sys_cputimer->freq;
1287 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1288 if (tvp->tv_usec >= 1000000) {
1289 tvp->tv_usec -= 1000000;
1295 getnanouptime(struct timespec *tsp)
1297 struct globaldata *gd = mycpu;
1301 tsp->tv_sec = gd->gd_time_seconds;
1302 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1303 } while (tsp->tv_sec != gd->gd_time_seconds);
1305 if (delta >= sys_cputimer->freq) {
1306 tsp->tv_sec += delta / sys_cputimer->freq;
1307 delta %= sys_cputimer->freq;
1309 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1313 microuptime(struct timeval *tvp)
1315 struct globaldata *gd = mycpu;
1319 tvp->tv_sec = gd->gd_time_seconds;
1320 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1321 } while (tvp->tv_sec != gd->gd_time_seconds);
1323 if (delta >= sys_cputimer->freq) {
1324 tvp->tv_sec += delta / sys_cputimer->freq;
1325 delta %= sys_cputimer->freq;
1327 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1331 nanouptime(struct timespec *tsp)
1333 struct globaldata *gd = mycpu;
1337 tsp->tv_sec = gd->gd_time_seconds;
1338 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1339 } while (tsp->tv_sec != gd->gd_time_seconds);
1341 if (delta >= sys_cputimer->freq) {
1342 tsp->tv_sec += delta / sys_cputimer->freq;
1343 delta %= sys_cputimer->freq;
1345 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1352 getmicrotime(struct timeval *tvp)
1354 struct globaldata *gd = mycpu;
1355 struct timespec *bt;
1359 tvp->tv_sec = gd->gd_time_seconds;
1360 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1361 } while (tvp->tv_sec != gd->gd_time_seconds);
1363 if (delta >= sys_cputimer->freq) {
1364 tvp->tv_sec += delta / sys_cputimer->freq;
1365 delta %= sys_cputimer->freq;
1367 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1369 bt = &basetime[basetime_index];
1371 tvp->tv_sec += bt->tv_sec;
1372 tvp->tv_usec += bt->tv_nsec / 1000;
1373 while (tvp->tv_usec >= 1000000) {
1374 tvp->tv_usec -= 1000000;
1380 getnanotime(struct timespec *tsp)
1382 struct globaldata *gd = mycpu;
1383 struct timespec *bt;
1387 tsp->tv_sec = gd->gd_time_seconds;
1388 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1389 } while (tsp->tv_sec != gd->gd_time_seconds);
1391 if (delta >= sys_cputimer->freq) {
1392 tsp->tv_sec += delta / sys_cputimer->freq;
1393 delta %= sys_cputimer->freq;
1395 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1397 bt = &basetime[basetime_index];
1399 tsp->tv_sec += bt->tv_sec;
1400 tsp->tv_nsec += bt->tv_nsec;
1401 while (tsp->tv_nsec >= 1000000000) {
1402 tsp->tv_nsec -= 1000000000;
1408 getnanotime_nbt(struct timespec *nbt, struct timespec *tsp)
1410 struct globaldata *gd = mycpu;
1414 tsp->tv_sec = gd->gd_time_seconds;
1415 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1416 } while (tsp->tv_sec != gd->gd_time_seconds);
1418 if (delta >= sys_cputimer->freq) {
1419 tsp->tv_sec += delta / sys_cputimer->freq;
1420 delta %= sys_cputimer->freq;
1422 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1424 tsp->tv_sec += nbt->tv_sec;
1425 tsp->tv_nsec += nbt->tv_nsec;
1426 while (tsp->tv_nsec >= 1000000000) {
1427 tsp->tv_nsec -= 1000000000;
1434 microtime(struct timeval *tvp)
1436 struct globaldata *gd = mycpu;
1437 struct timespec *bt;
1441 tvp->tv_sec = gd->gd_time_seconds;
1442 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1443 } while (tvp->tv_sec != gd->gd_time_seconds);
1445 if (delta >= sys_cputimer->freq) {
1446 tvp->tv_sec += delta / sys_cputimer->freq;
1447 delta %= sys_cputimer->freq;
1449 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1451 bt = &basetime[basetime_index];
1453 tvp->tv_sec += bt->tv_sec;
1454 tvp->tv_usec += bt->tv_nsec / 1000;
1455 while (tvp->tv_usec >= 1000000) {
1456 tvp->tv_usec -= 1000000;
1462 nanotime(struct timespec *tsp)
1464 struct globaldata *gd = mycpu;
1465 struct timespec *bt;
1469 tsp->tv_sec = gd->gd_time_seconds;
1470 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1471 } while (tsp->tv_sec != gd->gd_time_seconds);
1473 if (delta >= sys_cputimer->freq) {
1474 tsp->tv_sec += delta / sys_cputimer->freq;
1475 delta %= sys_cputimer->freq;
1477 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1479 bt = &basetime[basetime_index];
1481 tsp->tv_sec += bt->tv_sec;
1482 tsp->tv_nsec += bt->tv_nsec;
1483 while (tsp->tv_nsec >= 1000000000) {
1484 tsp->tv_nsec -= 1000000000;
1490 * Get an approximate time_t. It does not have to be accurate. This
1491 * function is called only from KTR and can be called with the system in
1492 * any state so do not use a critical section or other complex operation
1495 * NOTE: This is not exactly synchronized with real time. To do that we
1496 * would have to do what microtime does and check for a nanoseconds
1500 get_approximate_time_t(void)
1502 struct globaldata *gd = mycpu;
1503 struct timespec *bt;
1505 bt = &basetime[basetime_index];
1506 return(gd->gd_time_seconds + bt->tv_sec);
1510 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1513 struct pps_fetch_args *fapi;
1515 struct pps_kcbind_args *kapi;
1519 case PPS_IOC_CREATE:
1521 case PPS_IOC_DESTROY:
1523 case PPS_IOC_SETPARAMS:
1524 app = (pps_params_t *)data;
1525 if (app->mode & ~pps->ppscap)
1527 pps->ppsparam = *app;
1529 case PPS_IOC_GETPARAMS:
1530 app = (pps_params_t *)data;
1531 *app = pps->ppsparam;
1532 app->api_version = PPS_API_VERS_1;
1534 case PPS_IOC_GETCAP:
1535 *(int*)data = pps->ppscap;
1538 fapi = (struct pps_fetch_args *)data;
1539 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1541 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1542 return (EOPNOTSUPP);
1543 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1544 fapi->pps_info_buf = pps->ppsinfo;
1546 case PPS_IOC_KCBIND:
1548 kapi = (struct pps_kcbind_args *)data;
1549 /* XXX Only root should be able to do this */
1550 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1552 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1554 if (kapi->edge & ~pps->ppscap)
1556 pps->kcmode = kapi->edge;
1559 return (EOPNOTSUPP);
1567 pps_init(struct pps_state *pps)
1569 pps->ppscap |= PPS_TSFMT_TSPEC;
1570 if (pps->ppscap & PPS_CAPTUREASSERT)
1571 pps->ppscap |= PPS_OFFSETASSERT;
1572 if (pps->ppscap & PPS_CAPTURECLEAR)
1573 pps->ppscap |= PPS_OFFSETCLEAR;
1577 pps_event(struct pps_state *pps, sysclock_t count, int event)
1579 struct globaldata *gd;
1580 struct timespec *tsp;
1581 struct timespec *osp;
1582 struct timespec *bt;
1598 /* Things would be easier with arrays... */
1599 if (event == PPS_CAPTUREASSERT) {
1600 tsp = &pps->ppsinfo.assert_timestamp;
1601 osp = &pps->ppsparam.assert_offset;
1602 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1604 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1606 pcount = &pps->ppscount[0];
1607 pseq = &pps->ppsinfo.assert_sequence;
1609 tsp = &pps->ppsinfo.clear_timestamp;
1610 osp = &pps->ppsparam.clear_offset;
1611 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1613 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1615 pcount = &pps->ppscount[1];
1616 pseq = &pps->ppsinfo.clear_sequence;
1619 /* Nothing really happened */
1620 if (*pcount == count)
1626 ts.tv_sec = gd->gd_time_seconds;
1627 delta = count - gd->gd_cpuclock_base;
1628 } while (ts.tv_sec != gd->gd_time_seconds);
1630 if (delta >= sys_cputimer->freq) {
1631 ts.tv_sec += delta / sys_cputimer->freq;
1632 delta %= sys_cputimer->freq;
1634 ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1635 ni = basetime_index;
1638 ts.tv_sec += bt->tv_sec;
1639 ts.tv_nsec += bt->tv_nsec;
1640 while (ts.tv_nsec >= 1000000000) {
1641 ts.tv_nsec -= 1000000000;
1649 timespecadd(tsp, osp);
1650 if (tsp->tv_nsec < 0) {
1651 tsp->tv_nsec += 1000000000;
1657 /* magic, at its best... */
1658 tcount = count - pps->ppscount[2];
1659 pps->ppscount[2] = count;
1660 if (tcount >= sys_cputimer->freq) {
1661 delta = (1000000000 * (tcount / sys_cputimer->freq) +
1662 sys_cputimer->freq64_nsec *
1663 (tcount % sys_cputimer->freq)) >> 32;
1665 delta = (sys_cputimer->freq64_nsec * tcount) >> 32;
1667 hardpps(tsp, delta);
1673 * Return the tsc target value for a delay of (ns).
1675 * Returns -1 if the TSC is not supported.
1678 tsc_get_target(int ns)
1680 #if defined(_RDTSC_SUPPORTED_)
1681 if (cpu_feature & CPUID_TSC) {
1682 return (rdtsc() + tsc_frequency * ns / (int64_t)1000000000);
1689 * Compare the tsc against the passed target
1691 * Returns +1 if the target has been reached
1692 * Returns 0 if the target has not yet been reached
1693 * Returns -1 if the TSC is not supported.
1695 * Typical use: while (tsc_test_target(target) == 0) { ...poll... }
1698 tsc_test_target(int64_t target)
1700 #if defined(_RDTSC_SUPPORTED_)
1701 if (cpu_feature & CPUID_TSC) {
1702 if ((int64_t)(target - rdtsc()) <= 0)
1711 * Delay the specified number of nanoseconds using the tsc. This function
1712 * returns immediately if the TSC is not supported. At least one cpu_pause()
1720 clk = tsc_get_target(ns);
1723 while (tsc_test_target(clk) == 0) {