kernel - Add kern.cp_time sysctl.
[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.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 *
71 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
72 * $FreeBSD: src/sys/kern/kern_clock.c,v 1.105.2.10 2002/10/17 13:19:40 maxim Exp $
c730be20 73 * $DragonFly: src/sys/kern/kern_clock.c,v 1.62 2008/09/09 04:06:13 dillon Exp $
984263bc
MD
74 */
75
76#include "opt_ntp.h"
2b71c8f1 77#include "opt_polling.h"
b3a7093f 78#include "opt_ifpoll.h"
07522099 79#include "opt_pctrack.h"
984263bc
MD
80
81#include <sys/param.h>
82#include <sys/systm.h>
984263bc
MD
83#include <sys/callout.h>
84#include <sys/kernel.h>
f5d21610 85#include <sys/kinfo.h>
984263bc
MD
86#include <sys/proc.h>
87#include <sys/malloc.h>
88#include <sys/resourcevar.h>
89#include <sys/signalvar.h>
90#include <sys/timex.h>
91#include <sys/timepps.h>
92#include <vm/vm.h>
93#include <sys/lock.h>
94#include <vm/pmap.h>
95#include <vm/vm_map.h>
5ffd1608 96#include <vm/vm_extern.h>
984263bc 97#include <sys/sysctl.h>
684a93c4 98
2689779e 99#include <sys/thread2.h>
984263bc
MD
100
101#include <machine/cpu.h>
102#include <machine/limits.h>
103#include <machine/smp.h>
d2412a2e
MD
104#include <machine/cpufunc.h>
105#include <machine/specialreg.h>
106#include <machine/clock.h>
984263bc
MD
107
108#ifdef GPROF
109#include <sys/gmon.h>
110#endif
111
112#ifdef DEVICE_POLLING
94ebffcd 113extern void init_device_poll_pcpu(int);
3e61f60e 114#endif
984263bc 115
b3a7093f
SZ
116#ifdef IFPOLL_ENABLE
117extern void ifpoll_init_pcpu(int);
118#endif
119
07522099
MD
120#ifdef DEBUG_PCTRACK
121static void do_pctrack(struct intrframe *frame, int which);
122#endif
123
402ed7e1 124static void initclocks (void *dummy);
ba39e2e0 125SYSINIT(clocks, SI_BOOT2_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
984263bc 126
6ad39cae
MD
127/*
128 * Some of these don't belong here, but it's easiest to concentrate them.
9eea7f0c 129 * Note that cpu_time counts in microseconds, but most userland programs
6ad39cae
MD
130 * just compare relative times against the total by delta.
131 */
9eea7f0c 132struct kinfo_cputime cputime_percpu[MAXCPU];
07522099
MD
133#ifdef DEBUG_PCTRACK
134struct kinfo_pcheader cputime_pcheader = { PCTRACK_SIZE, PCTRACK_ARYSIZE };
135struct kinfo_pctrack cputime_pctrack[MAXCPU][PCTRACK_SIZE];
136#endif
137
9eea7f0c
HP
138#ifdef SMP
139static int
140sysctl_cputime(SYSCTL_HANDLER_ARGS)
141{
142 int cpu, error = 0;
143 size_t size = sizeof(struct kinfo_cputime);
144
145 for (cpu = 0; cpu < ncpus; ++cpu) {
146 if ((error = SYSCTL_OUT(req, &cputime_percpu[cpu], size)))
147 break;
148 }
984263bc 149
9eea7f0c
HP
150 return (error);
151}
152SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
153 sysctl_cputime, "S,kinfo_cputime", "CPU time statistics");
154#else
155SYSCTL_STRUCT(_kern, OID_AUTO, cputime, CTLFLAG_RD, &cpu_time, kinfo_cputime,
156 "CPU time statistics");
157#endif
984263bc 158
06636a8e
AHJ
159static int
160sysctl_cp_time(SYSCTL_HANDLER_ARGS)
161{
162 long cpu_states[5] = {0};
163 int cpu, error = 0;
164 size_t size = sizeof(cpu_states);
165
166 for (cpu = 0; cpu < ncpus; ++cpu) {
167 cpu_states[0] += cputime_percpu[cpu].cp_user;
168 cpu_states[1] += cputime_percpu[cpu].cp_nice;
169 cpu_states[2] += cputime_percpu[cpu].cp_sys;
170 cpu_states[3] += cputime_percpu[cpu].cp_intr;
171 cpu_states[4] += cputime_percpu[cpu].cp_idle;
172 }
173
174 error = SYSCTL_OUT(req, cpu_states, size);
175
176 return (error);
177}
178
179SYSCTL_PROC(_kern, OID_AUTO, cp_time, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
180 sysctl_cp_time, "LU", "CPU time statistics");
181
88c4d2f6
MD
182/*
183 * boottime is used to calculate the 'real' uptime. Do not confuse this with
184 * microuptime(). microtime() is not drift compensated. The real uptime
60b2809b
MD
185 * with compensation is nanotime() - bootime. boottime is recalculated
186 * whenever the real time is set based on the compensated elapsed time
187 * in seconds (gd->gd_time_seconds).
88c4d2f6 188 *
88c4d2f6
MD
189 * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
190 * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
191 * the real time.
192 */
193struct timespec boottime; /* boot time (realtime) for reference only */
88c4d2f6 194time_t time_second; /* read-only 'passive' uptime in seconds */
984263bc 195
5eb5a6bc
MD
196/*
197 * basetime is used to calculate the compensated real time of day. The
198 * basetime can be modified on a per-tick basis by the adjtime(),
199 * ntp_adjtime(), and sysctl-based time correction APIs.
200 *
201 * Note that frequency corrections can also be made by adjusting
202 * gd_cpuclock_base.
203 *
204 * basetime is a tail-chasing FIFO, updated only by cpu #0. The FIFO is
205 * used on both SMP and UP systems to avoid MP races between cpu's and
206 * interrupt races on UP systems.
207 */
208#define BASETIME_ARYSIZE 16
209#define BASETIME_ARYMASK (BASETIME_ARYSIZE - 1)
210static struct timespec basetime[BASETIME_ARYSIZE];
211static volatile int basetime_index;
212
213static int
214sysctl_get_basetime(SYSCTL_HANDLER_ARGS)
215{
216 struct timespec *bt;
217 int error;
35238fa5 218 int index;
5eb5a6bc 219
35238fa5
MD
220 /*
221 * Because basetime data and index may be updated by another cpu,
222 * a load fence is required to ensure that the data we read has
223 * not been speculatively read relative to a possibly updated index.
224 */
225 index = basetime_index;
226 cpu_lfence();
227 bt = &basetime[index];
08f95c49 228 error = SYSCTL_OUT(req, bt, sizeof(*bt));
5eb5a6bc
MD
229 return (error);
230}
231
984263bc 232SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
08f95c49 233 &boottime, timespec, "System boottime");
5eb5a6bc 234SYSCTL_PROC(_kern, OID_AUTO, basetime, CTLTYPE_STRUCT|CTLFLAG_RD, 0, 0,
08f95c49 235 sysctl_get_basetime, "S,timespec", "System basetime");
984263bc 236
88c4d2f6
MD
237static void hardclock(systimer_t info, struct intrframe *frame);
238static void statclock(systimer_t info, struct intrframe *frame);
239static void schedclock(systimer_t info, struct intrframe *frame);
5eb5a6bc 240static void getnanotime_nbt(struct timespec *nbt, struct timespec *tsp);
88c4d2f6
MD
241
242int ticks; /* system master ticks at hz */
da3639ef 243int clocks_running; /* tsleep/timeout clocks operational */
88c4d2f6
MD
244int64_t nsec_adj; /* ntpd per-tick adjustment in nsec << 32 */
245int64_t nsec_acc; /* accumulator */
984263bc 246
4026c000
JS
247/* NTPD time correction fields */
248int64_t ntp_tick_permanent; /* per-tick adjustment in nsec << 32 */
249int64_t ntp_tick_acc; /* accumulator for per-tick adjustment */
250int64_t ntp_delta; /* one-time correction in nsec */
251int64_t ntp_big_delta = 1000000000;
252int32_t ntp_tick_delta; /* current adjustment rate */
253int32_t ntp_default_tick_delta; /* adjustment rate for ntp_delta */
48590578
JS
254time_t ntp_leap_second; /* time of next leap second */
255int ntp_leap_insert; /* whether to insert or remove a second */
4026c000 256
984263bc 257/*
88c4d2f6 258 * Finish initializing clock frequencies and start all clocks running.
984263bc 259 */
88c4d2f6
MD
260/* ARGSUSED*/
261static void
262initclocks(void *dummy)
984263bc 263{
88c4d2f6
MD
264 /*psratio = profhz / stathz;*/
265 initclocks_pcpu();
da3639ef 266 clocks_running = 1;
984263bc
MD
267}
268
88c4d2f6
MD
269/*
270 * Called on a per-cpu basis
271 */
272void
273initclocks_pcpu(void)
274{
275 struct globaldata *gd = mycpu;
984263bc 276
88c4d2f6
MD
277 crit_enter();
278 if (gd->gd_cpuid == 0) {
279 gd->gd_time_seconds = 1;
044ee7c4 280 gd->gd_cpuclock_base = sys_cputimer->count();
88c4d2f6
MD
281 } else {
282 /* XXX */
283 gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
284 gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
285 }
0d1dffdf 286
43adde98
SZ
287 systimer_intr_enable();
288
94ebffcd
SZ
289#ifdef DEVICE_POLLING
290 init_device_poll_pcpu(gd->gd_cpuid);
291#endif
292
b3a7093f
SZ
293#ifdef IFPOLL_ENABLE
294 ifpoll_init_pcpu(gd->gd_cpuid);
295#endif
296
0d1dffdf
MD
297 /*
298 * Use a non-queued periodic systimer to prevent multiple ticks from
299 * building up if the sysclock jumps forward (8254 gets reset). The
300 * sysclock will never jump backwards. Our time sync is based on
301 * the actual sysclock, not the ticks count.
302 */
303 systimer_init_periodic_nq(&gd->gd_hardclock, hardclock, NULL, hz);
304 systimer_init_periodic_nq(&gd->gd_statclock, statclock, NULL, stathz);
88c4d2f6 305 /* XXX correct the frequency for scheduler / estcpu tests */
0d1dffdf 306 systimer_init_periodic_nq(&gd->gd_schedclock, schedclock,
8478264a 307 NULL, ESTCPUFREQ);
88c4d2f6
MD
308 crit_exit();
309}
984263bc
MD
310
311/*
88c4d2f6
MD
312 * This sets the current real time of day. Timespecs are in seconds and
313 * nanoseconds. We do not mess with gd_time_seconds and gd_cpuclock_base,
314 * instead we adjust basetime so basetime + gd_* results in the current
315 * time of day. This way the gd_* fields are guarenteed to represent
316 * a monotonically increasing 'uptime' value.
5eb5a6bc
MD
317 *
318 * When set_timeofday() is called from userland, the system call forces it
319 * onto cpu #0 since only cpu #0 can update basetime_index.
984263bc 320 */
88c4d2f6
MD
321void
322set_timeofday(struct timespec *ts)
323{
5eb5a6bc
MD
324 struct timespec *nbt;
325 int ni;
984263bc 326
88c4d2f6
MD
327 /*
328 * XXX SMP / non-atomic basetime updates
329 */
330 crit_enter();
5eb5a6bc
MD
331 ni = (basetime_index + 1) & BASETIME_ARYMASK;
332 nbt = &basetime[ni];
333 nanouptime(nbt);
334 nbt->tv_sec = ts->tv_sec - nbt->tv_sec;
335 nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec;
336 if (nbt->tv_nsec < 0) {
337 nbt->tv_nsec += 1000000000;
338 --nbt->tv_sec;
88c4d2f6 339 }
a81931cc
MD
340
341 /*
342 * Note that basetime diverges from boottime as the clock drift is
343 * compensated for, so we cannot do away with boottime. When setting
344 * the absolute time of day the drift is 0 (for an instant) and we
345 * can simply assign boottime to basetime.
346 *
347 * Note that nanouptime() is based on gd_time_seconds which is drift
348 * compensated up to a point (it is guarenteed to remain monotonically
349 * increasing). gd_time_seconds is thus our best uptime guess and
350 * suitable for use in the boottime calculation. It is already taken
351 * into account in the basetime calculation above.
352 */
5eb5a6bc 353 boottime.tv_sec = nbt->tv_sec;
4026c000 354 ntp_delta = 0;
5eb5a6bc
MD
355
356 /*
35238fa5
MD
357 * We now have a new basetime, make sure all other cpus have it,
358 * then update the index.
5eb5a6bc 359 */
35238fa5 360 cpu_sfence();
5eb5a6bc
MD
361 basetime_index = ni;
362
88c4d2f6
MD
363 crit_exit();
364}
365
984263bc 366/*
88c4d2f6
MD
367 * Each cpu has its own hardclock, but we only increments ticks and softticks
368 * on cpu #0.
369 *
370 * NOTE! systimer! the MP lock might not be held here. We can only safely
371 * manipulate objects owned by the current cpu.
984263bc 372 */
984263bc 373static void
88c4d2f6 374hardclock(systimer_t info, struct intrframe *frame)
984263bc 375{
88c4d2f6
MD
376 sysclock_t cputicks;
377 struct proc *p;
88c4d2f6 378 struct globaldata *gd = mycpu;
984263bc
MD
379
380 /*
88c4d2f6
MD
381 * Realtime updates are per-cpu. Note that timer corrections as
382 * returned by microtime() and friends make an additional adjustment
383 * using a system-wise 'basetime', but the running time is always
384 * taken from the per-cpu globaldata area. Since the same clock
385 * is distributing (XXX SMP) to all cpus, the per-cpu timebases
386 * stay in synch.
387 *
388 * Note that we never allow info->time (aka gd->gd_hardclock.time)
fad57d0e
MD
389 * to reverse index gd_cpuclock_base, but that it is possible for
390 * it to temporarily get behind in the seconds if something in the
391 * system locks interrupts for a long period of time. Since periodic
392 * timers count events, though everything should resynch again
393 * immediately.
984263bc 394 */
88c4d2f6 395 cputicks = info->time - gd->gd_cpuclock_base;
044ee7c4 396 if (cputicks >= sys_cputimer->freq) {
88c4d2f6 397 ++gd->gd_time_seconds;
044ee7c4 398 gd->gd_cpuclock_base += sys_cputimer->freq;
88c4d2f6 399 }
984263bc
MD
400
401 /*
92b561b7
MD
402 * The system-wide ticks counter and NTP related timedelta/tickdelta
403 * adjustments only occur on cpu #0. NTP adjustments are accomplished
404 * by updating basetime.
984263bc 405 */
88c4d2f6 406 if (gd->gd_cpuid == 0) {
5eb5a6bc 407 struct timespec *nbt;
88c4d2f6
MD
408 struct timespec nts;
409 int leap;
5eb5a6bc 410 int ni;
984263bc 411
88c4d2f6 412 ++ticks;
984263bc 413
88c4d2f6
MD
414#if 0
415 if (tco->tc_poll_pps)
416 tco->tc_poll_pps(tco);
417#endif
5eb5a6bc 418
88c4d2f6 419 /*
5eb5a6bc
MD
420 * Calculate the new basetime index. We are in a critical section
421 * on cpu #0 and can safely play with basetime_index. Start
422 * with the current basetime and then make adjustments.
423 */
424 ni = (basetime_index + 1) & BASETIME_ARYMASK;
425 nbt = &basetime[ni];
426 *nbt = basetime[basetime_index];
427
428 /*
429 * Apply adjtime corrections. (adjtime() API)
430 *
431 * adjtime() only runs on cpu #0 so our critical section is
432 * sufficient to access these variables.
88c4d2f6 433 */
4026c000 434 if (ntp_delta != 0) {
5eb5a6bc 435 nbt->tv_nsec += ntp_tick_delta;
4026c000
JS
436 ntp_delta -= ntp_tick_delta;
437 if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) ||
438 (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) {
5eb5a6bc 439 ntp_tick_delta = ntp_delta;
4026c000
JS
440 }
441 }
442
5eb5a6bc
MD
443 /*
444 * Apply permanent frequency corrections. (sysctl API)
445 */
4026c000
JS
446 if (ntp_tick_permanent != 0) {
447 ntp_tick_acc += ntp_tick_permanent;
448 if (ntp_tick_acc >= (1LL << 32)) {
5eb5a6bc 449 nbt->tv_nsec += ntp_tick_acc >> 32;
331bc6f8 450 ntp_tick_acc -= (ntp_tick_acc >> 32) << 32;
4026c000 451 } else if (ntp_tick_acc <= -(1LL << 32)) {
331bc6f8 452 /* Negate ntp_tick_acc to avoid shifting the sign bit. */
5eb5a6bc 453 nbt->tv_nsec -= (-ntp_tick_acc) >> 32;
331bc6f8 454 ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32;
4026c000
JS
455 }
456 }
457
5eb5a6bc
MD
458 if (nbt->tv_nsec >= 1000000000) {
459 nbt->tv_sec++;
460 nbt->tv_nsec -= 1000000000;
461 } else if (nbt->tv_nsec < 0) {
462 nbt->tv_sec--;
463 nbt->tv_nsec += 1000000000;
88c4d2f6
MD
464 }
465
466 /*
5eb5a6bc 467 * Another per-tick compensation. (for ntp_adjtime() API)
88c4d2f6 468 */
5eb5a6bc 469 if (nsec_adj != 0) {
88c4d2f6
MD
470 nsec_acc += nsec_adj;
471 if (nsec_acc >= 0x100000000LL) {
5eb5a6bc 472 nbt->tv_nsec += nsec_acc >> 32;
88c4d2f6
MD
473 nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
474 } else if (nsec_acc <= -0x100000000LL) {
5eb5a6bc 475 nbt->tv_nsec -= -nsec_acc >> 32;
88c4d2f6
MD
476 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
477 }
5eb5a6bc
MD
478 if (nbt->tv_nsec >= 1000000000) {
479 nbt->tv_nsec -= 1000000000;
480 ++nbt->tv_sec;
481 } else if (nbt->tv_nsec < 0) {
482 nbt->tv_nsec += 1000000000;
483 --nbt->tv_sec;
484 }
485 }
486
487 /************************************************************
488 * LEAP SECOND CORRECTION *
489 ************************************************************
490 *
491 * Taking into account all the corrections made above, figure
492 * out the new real time. If the seconds field has changed
493 * then apply any pending leap-second corrections.
494 */
495 getnanotime_nbt(nbt, &nts);
496
32040d57
MD
497 if (time_second != nts.tv_sec) {
498 /*
499 * Apply leap second (sysctl API). Adjust nts for changes
500 * so we do not have to call getnanotime_nbt again.
501 */
502 if (ntp_leap_second) {
503 if (ntp_leap_second == nts.tv_sec) {
504 if (ntp_leap_insert) {
505 nbt->tv_sec++;
506 nts.tv_sec++;
507 } else {
508 nbt->tv_sec--;
509 nts.tv_sec--;
510 }
5eb5a6bc 511 ntp_leap_second--;
32040d57 512 }
88c4d2f6 513 }
88c4d2f6 514
32040d57
MD
515 /*
516 * Apply leap second (ntp_adjtime() API), calculate a new
517 * nsec_adj field. ntp_update_second() returns nsec_adj
518 * as a per-second value but we need it as a per-tick value.
519 */
88c4d2f6 520 leap = ntp_update_second(time_second, &nsec_adj);
88c4d2f6 521 nsec_adj /= hz;
32040d57
MD
522 nbt->tv_sec += leap;
523 nts.tv_sec += leap;
524
525 /*
526 * Update the time_second 'approximate time' global.
527 */
528 time_second = nts.tv_sec;
88c4d2f6 529 }
5eb5a6bc
MD
530
531 /*
532 * Finally, our new basetime is ready to go live!
533 */
35238fa5 534 cpu_sfence();
5eb5a6bc 535 basetime_index = ni;
5ffd1608
MD
536
537 /*
538 * Figure out how badly the system is starved for memory
539 */
540 vm_fault_ratecheck();
88c4d2f6
MD
541 }
542
f9235b6d
MD
543 /*
544 * lwkt thread scheduler fair queueing
545 */
546 lwkt_fairq_schedulerclock(curthread);
547
92b561b7
MD
548 /*
549 * softticks are handled for all cpus
550 */
551 hardclock_softtick(gd);
552
c730be20
MD
553 /*
554 * The LWKT scheduler will generally allow the current process to
555 * return to user mode even if there are other runnable LWKT threads
556 * running in kernel mode on behalf of a user process. This will
557 * ensure that those other threads have an opportunity to run in
558 * fairly short order (but not instantly).
559 */
560 need_lwkt_resched();
561
88c4d2f6 562 /*
8582ec21
MD
563 * ITimer handling is per-tick, per-cpu.
564 *
565 * We must acquire the per-process token in order for ksignal()
566 * to be non-blocking.
88c4d2f6 567 */
8582ec21 568 if ((p = curproc) != NULL && lwkt_trytoken(&p->p_token)) {
3dbbd6dd 569 crit_enter_hard();
88c4d2f6 570 if (frame && CLKF_USERMODE(frame) &&
93328593 571 timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) &&
a591f597 572 itimerdecr(&p->p_timer[ITIMER_VIRTUAL], ustick) == 0)
84204577 573 ksignal(p, SIGVTALRM);
93328593 574 if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) &&
a591f597 575 itimerdecr(&p->p_timer[ITIMER_PROF], ustick) == 0)
84204577 576 ksignal(p, SIGPROF);
3dbbd6dd 577 crit_exit_hard();
8582ec21 578 lwkt_reltoken(&p->p_token);
984263bc 579 }
604e1e09 580 setdelayed();
88c4d2f6 581}
984263bc 582
88c4d2f6
MD
583/*
584 * The statistics clock typically runs at a 125Hz rate, and is intended
585 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu.
586 *
587 * NOTE! systimer! the MP lock might not be held here. We can only safely
588 * manipulate objects owned by the current cpu.
589 *
590 * The stats clock is responsible for grabbing a profiling sample.
591 * Most of the statistics are only used by user-level statistics programs.
592 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
593 * p->p_estcpu.
594 *
595 * Like the other clocks, the stat clock is called from what is effectively
596 * a fast interrupt, so the context should be the thread/process that got
597 * interrupted.
598 */
599static void
600statclock(systimer_t info, struct intrframe *frame)
601{
602#ifdef GPROF
603 struct gmonparam *g;
604 int i;
984263bc 605#endif
88c4d2f6
MD
606 thread_t td;
607 struct proc *p;
608 int bump;
609 struct timeval tv;
610 struct timeval *stv;
984263bc
MD
611
612 /*
88c4d2f6 613 * How big was our timeslice relative to the last time?
984263bc 614 */
88c4d2f6
MD
615 microuptime(&tv); /* mpsafe */
616 stv = &mycpu->gd_stattv;
617 if (stv->tv_sec == 0) {
618 bump = 1;
619 } else {
620 bump = tv.tv_usec - stv->tv_usec +
621 (tv.tv_sec - stv->tv_sec) * 1000000;
622 if (bump < 0)
623 bump = 0;
624 if (bump > 1000000)
625 bump = 1000000;
626 }
627 *stv = tv;
984263bc 628
88c4d2f6
MD
629 td = curthread;
630 p = td->td_proc;
984263bc 631
88c4d2f6
MD
632 if (frame && CLKF_USERMODE(frame)) {
633 /*
634 * Came from userland, handle user time and deal with
635 * possible process.
636 */
637 if (p && (p->p_flag & P_PROFIL))
638 addupc_intr(p, CLKF_PC(frame), 1);
639 td->td_uticks += bump;
984263bc 640
88c4d2f6
MD
641 /*
642 * Charge the time as appropriate
643 */
644 if (p && p->p_nice > NZERO)
9eea7f0c 645 cpu_time.cp_nice += bump;
88c4d2f6 646 else
9eea7f0c 647 cpu_time.cp_user += bump;
88c4d2f6
MD
648 } else {
649#ifdef GPROF
650 /*
651 * Kernel statistics are just like addupc_intr, only easier.
652 */
653 g = &_gmonparam;
654 if (g->state == GMON_PROF_ON && frame) {
655 i = CLKF_PC(frame) - g->lowpc;
656 if (i < g->textsize) {
657 i /= HISTFRACTION * sizeof(*g->kcount);
658 g->kcount[i]++;
659 }
660 }
661#endif
662 /*
663 * Came from kernel mode, so we were:
664 * - handling an interrupt,
665 * - doing syscall or trap work on behalf of the current
666 * user process, or
667 * - spinning in the idle loop.
668 * Whichever it is, charge the time as appropriate.
669 * Note that we charge interrupts to the current process,
670 * regardless of whether they are ``for'' that process,
671 * so that we know how much of its real time was spent
672 * in ``non-process'' (i.e., interrupt) work.
673 *
674 * XXX assume system if frame is NULL. A NULL frame
e43a034f 675 * can occur if ipi processing is done from a crit_exit().
88c4d2f6
MD
676 */
677 if (frame && CLKF_INTR(frame))
678 td->td_iticks += bump;
679 else
680 td->td_sticks += bump;
681
682 if (frame && CLKF_INTR(frame)) {
07522099
MD
683#ifdef DEBUG_PCTRACK
684 do_pctrack(frame, PCTRACK_INT);
685#endif
9eea7f0c 686 cpu_time.cp_intr += bump;
88c4d2f6 687 } else {
07522099 688 if (td == &mycpu->gd_idlethread) {
9eea7f0c 689 cpu_time.cp_idle += bump;
07522099
MD
690 } else {
691#ifdef DEBUG_PCTRACK
692 if (frame)
693 do_pctrack(frame, PCTRACK_SYS);
694#endif
9eea7f0c 695 cpu_time.cp_sys += bump;
07522099 696 }
88c4d2f6
MD
697 }
698 }
699}
700
07522099
MD
701#ifdef DEBUG_PCTRACK
702/*
703 * Sample the PC when in the kernel or in an interrupt. User code can
704 * retrieve the information and generate a histogram or other output.
705 */
706
707static void
708do_pctrack(struct intrframe *frame, int which)
709{
710 struct kinfo_pctrack *pctrack;
711
712 pctrack = &cputime_pctrack[mycpu->gd_cpuid][which];
713 pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] =
714 (void *)CLKF_PC(frame);
715 ++pctrack->pc_index;
716}
717
718static int
719sysctl_pctrack(SYSCTL_HANDLER_ARGS)
720{
721 struct kinfo_pcheader head;
722 int error;
723 int cpu;
724 int ntrack;
725
726 head.pc_ntrack = PCTRACK_SIZE;
727 head.pc_arysize = PCTRACK_ARYSIZE;
728
729 if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0)
730 return (error);
731
732 for (cpu = 0; cpu < ncpus; ++cpu) {
733 for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) {
734 error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack],
735 sizeof(struct kinfo_pctrack));
736 if (error)
737 break;
738 }
739 if (error)
740 break;
741 }
742 return (error);
743}
744SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
745 sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking");
746
747#endif
748
88c4d2f6 749/*
dcc99b62 750 * The scheduler clock typically runs at a 50Hz rate. NOTE! systimer,
88c4d2f6
MD
751 * the MP lock might not be held. We can safely manipulate parts of curproc
752 * but that's about it.
dcc99b62
MD
753 *
754 * Each cpu has its own scheduler clock.
88c4d2f6
MD
755 */
756static void
757schedclock(systimer_t info, struct intrframe *frame)
758{
553ea3c8 759 struct lwp *lp;
88c4d2f6
MD
760 struct rusage *ru;
761 struct vmspace *vm;
762 long rss;
763
553ea3c8 764 if ((lp = lwkt_preempted_proc()) != NULL) {
dcc99b62
MD
765 /*
766 * Account for cpu time used and hit the scheduler. Note
767 * that this call MUST BE MP SAFE, and the BGL IS NOT HELD
768 * HERE.
769 */
553ea3c8 770 ++lp->lwp_cpticks;
5681a38a
MD
771 lp->lwp_proc->p_usched->schedulerclock(lp, info->periodic,
772 info->time);
dcc99b62 773 }
553ea3c8 774 if ((lp = curthread->td_lwp) != NULL) {
dcc99b62
MD
775 /*
776 * Update resource usage integrals and maximums.
777 */
fde7ac71 778 if ((ru = &lp->lwp_proc->p_ru) &&
553ea3c8 779 (vm = lp->lwp_proc->p_vmspace) != NULL) {
88c4d2f6
MD
780 ru->ru_ixrss += pgtok(vm->vm_tsize);
781 ru->ru_idrss += pgtok(vm->vm_dsize);
782 ru->ru_isrss += pgtok(vm->vm_ssize);
783 rss = pgtok(vmspace_resident_count(vm));
784 if (ru->ru_maxrss < rss)
785 ru->ru_maxrss = rss;
786 }
b68b7282 787 }
984263bc
MD
788}
789
790/*
a94976ad
MD
791 * Compute number of ticks for the specified amount of time. The
792 * return value is intended to be used in a clock interrupt timed
793 * operation and guarenteed to meet or exceed the requested time.
794 * If the representation overflows, return INT_MAX. The minimum return
795 * value is 1 ticks and the function will average the calculation up.
796 * If any value greater then 0 microseconds is supplied, a value
797 * of at least 2 will be returned to ensure that a near-term clock
798 * interrupt does not cause the timeout to occur (degenerately) early.
799 *
800 * Note that limit checks must take into account microseconds, which is
801 * done simply by using the smaller signed long maximum instead of
802 * the unsigned long maximum.
803 *
804 * If ints have 32 bits, then the maximum value for any timeout in
805 * 10ms ticks is 248 days.
984263bc
MD
806 */
807int
a94976ad 808tvtohz_high(struct timeval *tv)
984263bc 809{
a94976ad 810 int ticks;
1fd87d54 811 long sec, usec;
984263bc 812
984263bc
MD
813 sec = tv->tv_sec;
814 usec = tv->tv_usec;
815 if (usec < 0) {
816 sec--;
817 usec += 1000000;
818 }
819 if (sec < 0) {
820#ifdef DIAGNOSTIC
821 if (usec > 0) {
822 sec++;
823 usec -= 1000000;
824 }
a591f597
MD
825 kprintf("tvtohz_high: negative time difference "
826 "%ld sec %ld usec\n",
827 sec, usec);
984263bc
MD
828#endif
829 ticks = 1;
a94976ad
MD
830 } else if (sec <= INT_MAX / hz) {
831 ticks = (int)(sec * hz +
a591f597 832 ((u_long)usec + (ustick - 1)) / ustick) + 1;
a94976ad
MD
833 } else {
834 ticks = INT_MAX;
835 }
836 return (ticks);
837}
838
a591f597
MD
839int
840tstohz_high(struct timespec *ts)
841{
842 int ticks;
843 long sec, nsec;
844
845 sec = ts->tv_sec;
846 nsec = ts->tv_nsec;
847 if (nsec < 0) {
848 sec--;
849 nsec += 1000000000;
850 }
851 if (sec < 0) {
852#ifdef DIAGNOSTIC
853 if (nsec > 0) {
854 sec++;
855 nsec -= 1000000000;
856 }
857 kprintf("tstohz_high: negative time difference "
858 "%ld sec %ld nsec\n",
859 sec, nsec);
860#endif
861 ticks = 1;
862 } else if (sec <= INT_MAX / hz) {
863 ticks = (int)(sec * hz +
864 ((u_long)nsec + (nstick - 1)) / nstick) + 1;
865 } else {
866 ticks = INT_MAX;
867 }
868 return (ticks);
869}
870
871
a94976ad
MD
872/*
873 * Compute number of ticks for the specified amount of time, erroring on
874 * the side of it being too low to ensure that sleeping the returned number
875 * of ticks will not result in a late return.
876 *
877 * The supplied timeval may not be negative and should be normalized. A
878 * return value of 0 is possible if the timeval converts to less then
879 * 1 tick.
880 *
881 * If ints have 32 bits, then the maximum value for any timeout in
882 * 10ms ticks is 248 days.
883 */
884int
885tvtohz_low(struct timeval *tv)
886{
887 int ticks;
888 long sec;
889
890 sec = tv->tv_sec;
891 if (sec <= INT_MAX / hz)
a591f597 892 ticks = (int)(sec * hz + (u_long)tv->tv_usec / ustick);
984263bc 893 else
984263bc 894 ticks = INT_MAX;
a94976ad 895 return (ticks);
984263bc
MD
896}
897
a591f597
MD
898int
899tstohz_low(struct timespec *ts)
900{
901 int ticks;
902 long sec;
903
904 sec = ts->tv_sec;
905 if (sec <= INT_MAX / hz)
906 ticks = (int)(sec * hz + (u_long)ts->tv_nsec / nstick);
907 else
908 ticks = INT_MAX;
909 return (ticks);
910}
a94976ad 911
984263bc
MD
912/*
913 * Start profiling on a process.
914 *
915 * Kernel profiling passes proc0 which never exits and hence
916 * keeps the profile clock running constantly.
917 */
918void
88c4d2f6 919startprofclock(struct proc *p)
984263bc 920{
984263bc
MD
921 if ((p->p_flag & P_PROFIL) == 0) {
922 p->p_flag |= P_PROFIL;
88c4d2f6 923#if 0 /* XXX */
984263bc 924 if (++profprocs == 1 && stathz != 0) {
e43a034f 925 crit_enter();
6ad39cae 926 psdiv = psratio;
984263bc 927 setstatclockrate(profhz);
e43a034f 928 crit_exit();
984263bc 929 }
88c4d2f6 930#endif
984263bc
MD
931 }
932}
933
934/*
935 * Stop profiling on a process.
936 */
937void
88c4d2f6 938stopprofclock(struct proc *p)
984263bc 939{
984263bc
MD
940 if (p->p_flag & P_PROFIL) {
941 p->p_flag &= ~P_PROFIL;
88c4d2f6 942#if 0 /* XXX */
984263bc 943 if (--profprocs == 0 && stathz != 0) {
e43a034f 944 crit_enter();
6ad39cae 945 psdiv = 1;
984263bc 946 setstatclockrate(stathz);
e43a034f 947 crit_exit();
984263bc 948 }
984263bc 949#endif
984263bc
MD
950 }
951}
952
953/*
954 * Return information about system clocks.
955 */
956static int
957sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
958{
f5d21610 959 struct kinfo_clockinfo clkinfo;
984263bc
MD
960 /*
961 * Construct clockinfo structure.
962 */
f5d21610 963 clkinfo.ci_hz = hz;
a591f597 964 clkinfo.ci_tick = ustick;
4026c000 965 clkinfo.ci_tickadj = ntp_default_tick_delta / 1000;
f5d21610
JS
966 clkinfo.ci_profhz = profhz;
967 clkinfo.ci_stathz = stathz ? stathz : hz;
984263bc
MD
968 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
969}
970
971SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
972 0, 0, sysctl_kern_clockrate, "S,clockinfo","");
973
984263bc
MD
974/*
975 * We have eight functions for looking at the clock, four for
976 * microseconds and four for nanoseconds. For each there is fast
977 * but less precise version "get{nano|micro}[up]time" which will
978 * return a time which is up to 1/HZ previous to the call, whereas
979 * the raw version "{nano|micro}[up]time" will return a timestamp
980 * which is as precise as possible. The "up" variants return the
981 * time relative to system boot, these are well suited for time
982 * interval measurements.
88c4d2f6
MD
983 *
984 * Each cpu independantly maintains the current time of day, so all
985 * we need to do to protect ourselves from changes is to do a loop
986 * check on the seconds field changing out from under us.
fad57d0e
MD
987 *
988 * The system timer maintains a 32 bit count and due to various issues
989 * it is possible for the calculated delta to occassionally exceed
044ee7c4
MD
990 * sys_cputimer->freq. If this occurs the sys_cputimer->freq64_nsec
991 * multiplication can easily overflow, so we deal with the case. For
992 * uniformity we deal with the case in the usec case too.
627531fa
MD
993 *
994 * All the [get][micro,nano][time,uptime]() routines are MPSAFE.
984263bc 995 */
984263bc
MD
996void
997getmicrouptime(struct timeval *tvp)
998{
88c4d2f6
MD
999 struct globaldata *gd = mycpu;
1000 sysclock_t delta;
1001
1002 do {
1003 tvp->tv_sec = gd->gd_time_seconds;
1004 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1005 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e 1006
044ee7c4
MD
1007 if (delta >= sys_cputimer->freq) {
1008 tvp->tv_sec += delta / sys_cputimer->freq;
1009 delta %= sys_cputimer->freq;
fad57d0e 1010 }
044ee7c4 1011 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
88c4d2f6
MD
1012 if (tvp->tv_usec >= 1000000) {
1013 tvp->tv_usec -= 1000000;
1014 ++tvp->tv_sec;
984263bc
MD
1015 }
1016}
1017
1018void
1019getnanouptime(struct timespec *tsp)
1020{
88c4d2f6
MD
1021 struct globaldata *gd = mycpu;
1022 sysclock_t delta;
1023
1024 do {
1025 tsp->tv_sec = gd->gd_time_seconds;
1026 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1027 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e 1028
044ee7c4
MD
1029 if (delta >= sys_cputimer->freq) {
1030 tsp->tv_sec += delta / sys_cputimer->freq;
1031 delta %= sys_cputimer->freq;
984263bc 1032 }
044ee7c4 1033 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
984263bc
MD
1034}
1035
1036void
88c4d2f6 1037microuptime(struct timeval *tvp)
984263bc 1038{
88c4d2f6
MD
1039 struct globaldata *gd = mycpu;
1040 sysclock_t delta;
1041
1042 do {
1043 tvp->tv_sec = gd->gd_time_seconds;
044ee7c4 1044 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
88c4d2f6 1045 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e 1046
044ee7c4
MD
1047 if (delta >= sys_cputimer->freq) {
1048 tvp->tv_sec += delta / sys_cputimer->freq;
1049 delta %= sys_cputimer->freq;
984263bc 1050 }
044ee7c4 1051 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
984263bc
MD
1052}
1053
1054void
88c4d2f6 1055nanouptime(struct timespec *tsp)
984263bc 1056{
88c4d2f6
MD
1057 struct globaldata *gd = mycpu;
1058 sysclock_t delta;
1059
1060 do {
1061 tsp->tv_sec = gd->gd_time_seconds;
044ee7c4 1062 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
88c4d2f6 1063 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e 1064
044ee7c4
MD
1065 if (delta >= sys_cputimer->freq) {
1066 tsp->tv_sec += delta / sys_cputimer->freq;
1067 delta %= sys_cputimer->freq;
984263bc 1068 }
044ee7c4 1069 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
984263bc
MD
1070}
1071
88c4d2f6
MD
1072/*
1073 * realtime routines
1074 */
984263bc 1075void
88c4d2f6 1076getmicrotime(struct timeval *tvp)
984263bc 1077{
88c4d2f6 1078 struct globaldata *gd = mycpu;
5eb5a6bc 1079 struct timespec *bt;
88c4d2f6 1080 sysclock_t delta;
984263bc 1081
88c4d2f6
MD
1082 do {
1083 tvp->tv_sec = gd->gd_time_seconds;
1084 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1085 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e 1086
044ee7c4
MD
1087 if (delta >= sys_cputimer->freq) {
1088 tvp->tv_sec += delta / sys_cputimer->freq;
1089 delta %= sys_cputimer->freq;
fad57d0e 1090 }
044ee7c4 1091 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
984263bc 1092
5eb5a6bc
MD
1093 bt = &basetime[basetime_index];
1094 tvp->tv_sec += bt->tv_sec;
1095 tvp->tv_usec += bt->tv_nsec / 1000;
88c4d2f6
MD
1096 while (tvp->tv_usec >= 1000000) {
1097 tvp->tv_usec -= 1000000;
1098 ++tvp->tv_sec;
984263bc 1099 }
984263bc
MD
1100}
1101
1102void
88c4d2f6 1103getnanotime(struct timespec *tsp)
984263bc 1104{
88c4d2f6 1105 struct globaldata *gd = mycpu;
5eb5a6bc 1106 struct timespec *bt;
88c4d2f6 1107 sysclock_t delta;
984263bc 1108
88c4d2f6
MD
1109 do {
1110 tsp->tv_sec = gd->gd_time_seconds;
1111 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1112 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e 1113
044ee7c4
MD
1114 if (delta >= sys_cputimer->freq) {
1115 tsp->tv_sec += delta / sys_cputimer->freq;
1116 delta %= sys_cputimer->freq;
fad57d0e 1117 }
044ee7c4 1118 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
984263bc 1119
5eb5a6bc
MD
1120 bt = &basetime[basetime_index];
1121 tsp->tv_sec += bt->tv_sec;
1122 tsp->tv_nsec += bt->tv_nsec;
88c4d2f6
MD
1123 while (tsp->tv_nsec >= 1000000000) {
1124 tsp->tv_nsec -= 1000000000;
1125 ++tsp->tv_sec;
984263bc 1126 }
984263bc
MD
1127}
1128
5eb5a6bc
MD
1129static void
1130getnanotime_nbt(struct timespec *nbt, struct timespec *tsp)
1131{
1132 struct globaldata *gd = mycpu;
1133 sysclock_t delta;
1134
1135 do {
1136 tsp->tv_sec = gd->gd_time_seconds;
1137 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1138 } while (tsp->tv_sec != gd->gd_time_seconds);
1139
044ee7c4
MD
1140 if (delta >= sys_cputimer->freq) {
1141 tsp->tv_sec += delta / sys_cputimer->freq;
1142 delta %= sys_cputimer->freq;
5eb5a6bc 1143 }
044ee7c4 1144 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
5eb5a6bc
MD
1145
1146 tsp->tv_sec += nbt->tv_sec;
1147 tsp->tv_nsec += nbt->tv_nsec;
1148 while (tsp->tv_nsec >= 1000000000) {
1149 tsp->tv_nsec -= 1000000000;
1150 ++tsp->tv_sec;
1151 }
1152}
1153
1154
88c4d2f6
MD
1155void
1156microtime(struct timeval *tvp)
984263bc 1157{
88c4d2f6 1158 struct globaldata *gd = mycpu;
5eb5a6bc 1159 struct timespec *bt;
88c4d2f6 1160 sysclock_t delta;
984263bc 1161
88c4d2f6
MD
1162 do {
1163 tvp->tv_sec = gd->gd_time_seconds;
044ee7c4 1164 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
88c4d2f6 1165 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e 1166
044ee7c4
MD
1167 if (delta >= sys_cputimer->freq) {
1168 tvp->tv_sec += delta / sys_cputimer->freq;
1169 delta %= sys_cputimer->freq;
fad57d0e 1170 }
044ee7c4 1171 tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
984263bc 1172
5eb5a6bc
MD
1173 bt = &basetime[basetime_index];
1174 tvp->tv_sec += bt->tv_sec;
1175 tvp->tv_usec += bt->tv_nsec / 1000;
88c4d2f6
MD
1176 while (tvp->tv_usec >= 1000000) {
1177 tvp->tv_usec -= 1000000;
1178 ++tvp->tv_sec;
984263bc 1179 }
984263bc
MD
1180}
1181
88c4d2f6
MD
1182void
1183nanotime(struct timespec *tsp)
1184{
1185 struct globaldata *gd = mycpu;
5eb5a6bc 1186 struct timespec *bt;
88c4d2f6 1187 sysclock_t delta;
984263bc 1188
88c4d2f6
MD
1189 do {
1190 tsp->tv_sec = gd->gd_time_seconds;
044ee7c4 1191 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
88c4d2f6 1192 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e 1193
044ee7c4
MD
1194 if (delta >= sys_cputimer->freq) {
1195 tsp->tv_sec += delta / sys_cputimer->freq;
1196 delta %= sys_cputimer->freq;
fad57d0e 1197 }
044ee7c4 1198 tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
984263bc 1199
5eb5a6bc
MD
1200 bt = &basetime[basetime_index];
1201 tsp->tv_sec += bt->tv_sec;
1202 tsp->tv_nsec += bt->tv_nsec;
88c4d2f6
MD
1203 while (tsp->tv_nsec >= 1000000000) {
1204 tsp->tv_nsec -= 1000000000;
1205 ++tsp->tv_sec;
984263bc 1206 }
984263bc
MD
1207}
1208
25b804e7
MD
1209/*
1210 * note: this is not exactly synchronized with real time. To do that we
1211 * would have to do what microtime does and check for a nanoseconds overflow.
1212 */
1213time_t
1214get_approximate_time_t(void)
1215{
1216 struct globaldata *gd = mycpu;
5eb5a6bc
MD
1217 struct timespec *bt;
1218
1219 bt = &basetime[basetime_index];
1220 return(gd->gd_time_seconds + bt->tv_sec);
25b804e7
MD
1221}
1222
984263bc
MD
1223int
1224pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1225{
1226 pps_params_t *app;
1227 struct pps_fetch_args *fapi;
1228#ifdef PPS_SYNC
1229 struct pps_kcbind_args *kapi;
1230#endif
1231
1232 switch (cmd) {
1233 case PPS_IOC_CREATE:
1234 return (0);
1235 case PPS_IOC_DESTROY:
1236 return (0);
1237 case PPS_IOC_SETPARAMS:
1238 app = (pps_params_t *)data;
1239 if (app->mode & ~pps->ppscap)
1240 return (EINVAL);
1241 pps->ppsparam = *app;
1242 return (0);
1243 case PPS_IOC_GETPARAMS:
1244 app = (pps_params_t *)data;
1245 *app = pps->ppsparam;
1246 app->api_version = PPS_API_VERS_1;
1247 return (0);
1248 case PPS_IOC_GETCAP:
1249 *(int*)data = pps->ppscap;
1250 return (0);
1251 case PPS_IOC_FETCH:
1252 fapi = (struct pps_fetch_args *)data;
1253 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1254 return (EINVAL);
1255 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1256 return (EOPNOTSUPP);
1257 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1258 fapi->pps_info_buf = pps->ppsinfo;
1259 return (0);
1260 case PPS_IOC_KCBIND:
1261#ifdef PPS_SYNC
1262 kapi = (struct pps_kcbind_args *)data;
1263 /* XXX Only root should be able to do this */
1264 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1265 return (EINVAL);
1266 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1267 return (EINVAL);
1268 if (kapi->edge & ~pps->ppscap)
1269 return (EINVAL);
1270 pps->kcmode = kapi->edge;
1271 return (0);
1272#else
1273 return (EOPNOTSUPP);
1274#endif
1275 default:
1276 return (ENOTTY);
1277 }
1278}
1279
1280void
1281pps_init(struct pps_state *pps)
1282{
1283 pps->ppscap |= PPS_TSFMT_TSPEC;
1284 if (pps->ppscap & PPS_CAPTUREASSERT)
1285 pps->ppscap |= PPS_OFFSETASSERT;
1286 if (pps->ppscap & PPS_CAPTURECLEAR)
1287 pps->ppscap |= PPS_OFFSETCLEAR;
1288}
1289
1290void
88c4d2f6 1291pps_event(struct pps_state *pps, sysclock_t count, int event)
984263bc 1292{
88c4d2f6
MD
1293 struct globaldata *gd;
1294 struct timespec *tsp;
1295 struct timespec *osp;
5eb5a6bc 1296 struct timespec *bt;
88c4d2f6
MD
1297 struct timespec ts;
1298 sysclock_t *pcount;
1299#ifdef PPS_SYNC
1300 sysclock_t tcount;
1301#endif
1302 sysclock_t delta;
1303 pps_seq_t *pseq;
1304 int foff;
1305 int fhard;
1306
1307 gd = mycpu;
984263bc
MD
1308
1309 /* Things would be easier with arrays... */
1310 if (event == PPS_CAPTUREASSERT) {
1311 tsp = &pps->ppsinfo.assert_timestamp;
1312 osp = &pps->ppsparam.assert_offset;
1313 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1314 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1315 pcount = &pps->ppscount[0];
1316 pseq = &pps->ppsinfo.assert_sequence;
1317 } else {
1318 tsp = &pps->ppsinfo.clear_timestamp;
1319 osp = &pps->ppsparam.clear_offset;
1320 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1321 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1322 pcount = &pps->ppscount[1];
1323 pseq = &pps->ppsinfo.clear_sequence;
1324 }
1325
984263bc
MD
1326 /* Nothing really happened */
1327 if (*pcount == count)
1328 return;
1329
1330 *pcount = count;
1331
88c4d2f6
MD
1332 do {
1333 ts.tv_sec = gd->gd_time_seconds;
1334 delta = count - gd->gd_cpuclock_base;
1335 } while (ts.tv_sec != gd->gd_time_seconds);
fad57d0e 1336
044ee7c4
MD
1337 if (delta >= sys_cputimer->freq) {
1338 ts.tv_sec += delta / sys_cputimer->freq;
1339 delta %= sys_cputimer->freq;
88c4d2f6 1340 }
044ee7c4 1341 ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
5eb5a6bc
MD
1342 bt = &basetime[basetime_index];
1343 ts.tv_sec += bt->tv_sec;
1344 ts.tv_nsec += bt->tv_nsec;
88c4d2f6
MD
1345 while (ts.tv_nsec >= 1000000000) {
1346 ts.tv_nsec -= 1000000000;
1347 ++ts.tv_sec;
984263bc 1348 }
984263bc
MD
1349
1350 (*pseq)++;
1351 *tsp = ts;
1352
1353 if (foff) {
1354 timespecadd(tsp, osp);
1355 if (tsp->tv_nsec < 0) {
1356 tsp->tv_nsec += 1000000000;
1357 tsp->tv_sec -= 1;
1358 }
1359 }
1360#ifdef PPS_SYNC
1361 if (fhard) {
1362 /* magic, at its best... */
1363 tcount = count - pps->ppscount[2];
1364 pps->ppscount[2] = count;
044ee7c4
MD
1365 if (tcount >= sys_cputimer->freq) {
1366 delta = (1000000000 * (tcount / sys_cputimer->freq) +
1367 sys_cputimer->freq64_nsec *
1368 (tcount % sys_cputimer->freq)) >> 32;
fad57d0e 1369 } else {
044ee7c4 1370 delta = (sys_cputimer->freq64_nsec * tcount) >> 32;
fad57d0e 1371 }
984263bc
MD
1372 hardpps(tsp, delta);
1373 }
1374#endif
1375}
88c4d2f6 1376
d2412a2e
MD
1377/*
1378 * Return the tsc target value for a delay of (ns).
1379 *
1380 * Returns -1 if the TSC is not supported.
1381 */
1382int64_t
1383tsc_get_target(int ns)
1384{
1385#if defined(_RDTSC_SUPPORTED_)
1386 if (cpu_feature & CPUID_TSC) {
1387 return (rdtsc() + tsc_frequency * ns / (int64_t)1000000000);
1388 }
1389#endif
1390 return(-1);
1391}
1392
1393/*
1394 * Compare the tsc against the passed target
1395 *
1396 * Returns +1 if the target has been reached
1397 * Returns 0 if the target has not yet been reached
1398 * Returns -1 if the TSC is not supported.
1399 *
1400 * Typical use: while (tsc_test_target(target) == 0) { ...poll... }
1401 */
1402int
1403tsc_test_target(int64_t target)
1404{
1405#if defined(_RDTSC_SUPPORTED_)
1406 if (cpu_feature & CPUID_TSC) {
1407 if ((int64_t)(target - rdtsc()) <= 0)
1408 return(1);
1409 return(0);
1410 }
d2412a2e 1411#endif
2e537993 1412 return(-1);
d2412a2e 1413}