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