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