Style(9):
[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 $
92b561b7 73 * $DragonFly: src/sys/kern/kern_clock.c,v 1.24 2004/09/17 00:18:09 dillon Exp $
984263bc
MD
74 */
75
76#include "opt_ntp.h"
77
78#include <sys/param.h>
79#include <sys/systm.h>
80#include <sys/dkstat.h>
81#include <sys/callout.h>
82#include <sys/kernel.h>
83#include <sys/proc.h>
84#include <sys/malloc.h>
85#include <sys/resourcevar.h>
86#include <sys/signalvar.h>
87#include <sys/timex.h>
88#include <sys/timepps.h>
89#include <vm/vm.h>
90#include <sys/lock.h>
91#include <vm/pmap.h>
92#include <vm/vm_map.h>
93#include <sys/sysctl.h>
2689779e 94#include <sys/thread2.h>
984263bc
MD
95
96#include <machine/cpu.h>
97#include <machine/limits.h>
98#include <machine/smp.h>
99
100#ifdef GPROF
101#include <sys/gmon.h>
102#endif
103
104#ifdef DEVICE_POLLING
105extern void init_device_poll(void);
106extern void hardclock_device_poll(void);
107#endif /* DEVICE_POLLING */
108
402ed7e1 109static void initclocks (void *dummy);
984263bc
MD
110SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
111
6ad39cae
MD
112/*
113 * Some of these don't belong here, but it's easiest to concentrate them.
114 * Note that cp_time[] counts in microseconds, but most userland programs
115 * just compare relative times against the total by delta.
116 */
984263bc
MD
117long cp_time[CPUSTATES];
118
119SYSCTL_OPAQUE(_kern, OID_AUTO, cp_time, CTLFLAG_RD, &cp_time, sizeof(cp_time),
120 "LU", "CPU time statistics");
121
122long tk_cancc;
123long tk_nin;
124long tk_nout;
125long tk_rawcc;
126
88c4d2f6
MD
127/*
128 * boottime is used to calculate the 'real' uptime. Do not confuse this with
129 * microuptime(). microtime() is not drift compensated. The real uptime
60b2809b
MD
130 * with compensation is nanotime() - bootime. boottime is recalculated
131 * whenever the real time is set based on the compensated elapsed time
132 * in seconds (gd->gd_time_seconds).
88c4d2f6
MD
133 *
134 * basetime is used to calculate the compensated real time of day. Chunky
135 * changes to the time, aka settimeofday(), are made by modifying basetime.
136 *
137 * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
138 * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
139 * the real time.
140 */
141struct timespec boottime; /* boot time (realtime) for reference only */
142struct timespec basetime; /* base time adjusts uptime -> realtime */
143time_t time_second; /* read-only 'passive' uptime in seconds */
984263bc 144
984263bc
MD
145SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
146 &boottime, timeval, "System boottime");
88c4d2f6
MD
147SYSCTL_STRUCT(_kern, OID_AUTO, basetime, CTLFLAG_RD,
148 &basetime, timeval, "System basetime");
984263bc 149
88c4d2f6
MD
150static void hardclock(systimer_t info, struct intrframe *frame);
151static void statclock(systimer_t info, struct intrframe *frame);
152static void schedclock(systimer_t info, struct intrframe *frame);
153
154int ticks; /* system master ticks at hz */
da3639ef 155int clocks_running; /* tsleep/timeout clocks operational */
88c4d2f6
MD
156int64_t nsec_adj; /* ntpd per-tick adjustment in nsec << 32 */
157int64_t nsec_acc; /* accumulator */
984263bc
MD
158
159/*
88c4d2f6 160 * Finish initializing clock frequencies and start all clocks running.
984263bc 161 */
88c4d2f6
MD
162/* ARGSUSED*/
163static void
164initclocks(void *dummy)
984263bc 165{
88c4d2f6
MD
166 cpu_initclocks();
167#ifdef DEVICE_POLLING
168 init_device_poll();
169#endif
170 /*psratio = profhz / stathz;*/
171 initclocks_pcpu();
da3639ef 172 clocks_running = 1;
984263bc
MD
173}
174
88c4d2f6
MD
175/*
176 * Called on a per-cpu basis
177 */
178void
179initclocks_pcpu(void)
180{
181 struct globaldata *gd = mycpu;
984263bc 182
88c4d2f6
MD
183 crit_enter();
184 if (gd->gd_cpuid == 0) {
185 gd->gd_time_seconds = 1;
186 gd->gd_cpuclock_base = cputimer_count();
187 } else {
188 /* XXX */
189 gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
190 gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
191 }
192 systimer_init_periodic(&gd->gd_hardclock, hardclock, NULL, hz);
193 systimer_init_periodic(&gd->gd_statclock, statclock, NULL, stathz);
194 /* XXX correct the frequency for scheduler / estcpu tests */
8478264a
MD
195 systimer_init_periodic(&gd->gd_schedclock, schedclock,
196 NULL, ESTCPUFREQ);
88c4d2f6
MD
197 crit_exit();
198}
984263bc 199
0284027e
MD
200/*
201 * Resynchronize gd_cpuclock_base after the system has been woken up from
202 * a sleep. It is absolutely essential that all the cpus be properly
203 * synchronized. Resynching is required because nanouptime() and friends
204 * will overflow intermediate multiplications if more then 2 seconds
205 * worth of cputimer_cont() delta has built up.
206 */
207#ifdef SMP
208
209static
210void
211restoreclocks_remote(lwkt_cpusync_t poll)
212{
213 mycpu->gd_cpuclock_base = *(sysclock_t *)poll->cs_data;
214 mycpu->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
215}
216
217#endif
218
219void
220restoreclocks(void)
221{
222 sysclock_t base = cputimer_count();
223#ifdef SMP
224 lwkt_cpusync_simple(-1, restoreclocks_remote, &base);
225#else
226 mycpu->gd_cpuclock_base = base;
227#endif
228}
229
984263bc 230/*
88c4d2f6
MD
231 * This sets the current real time of day. Timespecs are in seconds and
232 * nanoseconds. We do not mess with gd_time_seconds and gd_cpuclock_base,
233 * instead we adjust basetime so basetime + gd_* results in the current
234 * time of day. This way the gd_* fields are guarenteed to represent
235 * a monotonically increasing 'uptime' value.
984263bc 236 */
88c4d2f6
MD
237void
238set_timeofday(struct timespec *ts)
239{
240 struct timespec ts2;
984263bc 241
88c4d2f6
MD
242 /*
243 * XXX SMP / non-atomic basetime updates
244 */
245 crit_enter();
246 nanouptime(&ts2);
247 basetime.tv_sec = ts->tv_sec - ts2.tv_sec;
248 basetime.tv_nsec = ts->tv_nsec - ts2.tv_nsec;
249 if (basetime.tv_nsec < 0) {
250 basetime.tv_nsec += 1000000000;
251 --basetime.tv_sec;
252 }
60b2809b 253 boottime.tv_sec = basetime.tv_sec - mycpu->gd_time_seconds;
88c4d2f6
MD
254 timedelta = 0;
255 crit_exit();
256}
257
984263bc 258/*
88c4d2f6
MD
259 * Each cpu has its own hardclock, but we only increments ticks and softticks
260 * on cpu #0.
261 *
262 * NOTE! systimer! the MP lock might not be held here. We can only safely
263 * manipulate objects owned by the current cpu.
984263bc 264 */
984263bc 265static void
88c4d2f6 266hardclock(systimer_t info, struct intrframe *frame)
984263bc 267{
88c4d2f6
MD
268 sysclock_t cputicks;
269 struct proc *p;
270 struct pstats *pstats;
271 struct globaldata *gd = mycpu;
984263bc
MD
272
273 /*
88c4d2f6
MD
274 * Realtime updates are per-cpu. Note that timer corrections as
275 * returned by microtime() and friends make an additional adjustment
276 * using a system-wise 'basetime', but the running time is always
277 * taken from the per-cpu globaldata area. Since the same clock
278 * is distributing (XXX SMP) to all cpus, the per-cpu timebases
279 * stay in synch.
280 *
281 * Note that we never allow info->time (aka gd->gd_hardclock.time)
282 * to reverse index gd_cpuclock_base.
984263bc 283 */
88c4d2f6
MD
284 cputicks = info->time - gd->gd_cpuclock_base;
285 if (cputicks > cputimer_freq) {
286 ++gd->gd_time_seconds;
287 gd->gd_cpuclock_base += cputimer_freq;
288 }
984263bc
MD
289
290 /*
92b561b7
MD
291 * The system-wide ticks counter and NTP related timedelta/tickdelta
292 * adjustments only occur on cpu #0. NTP adjustments are accomplished
293 * by updating basetime.
984263bc 294 */
88c4d2f6
MD
295 if (gd->gd_cpuid == 0) {
296 struct timespec nts;
297 int leap;
984263bc 298
88c4d2f6 299 ++ticks;
984263bc 300
88c4d2f6
MD
301#ifdef DEVICE_POLLING
302 hardclock_device_poll(); /* mpsafe, short and quick */
303#endif /* DEVICE_POLLING */
984263bc 304
88c4d2f6
MD
305#if 0
306 if (tco->tc_poll_pps)
307 tco->tc_poll_pps(tco);
308#endif
309 /*
310 * Apply adjtime corrections. At the moment only do this if
311 * we can get the MP lock to interlock with adjtime's modification
312 * of these variables. Note that basetime adjustments are not
313 * MP safe either XXX.
314 */
315 if (timedelta != 0 && try_mplock()) {
316 basetime.tv_nsec += tickdelta * 1000;
317 if (basetime.tv_nsec >= 1000000000) {
318 basetime.tv_nsec -= 1000000000;
319 ++basetime.tv_sec;
320 } else if (basetime.tv_nsec < 0) {
321 basetime.tv_nsec += 1000000000;
322 --basetime.tv_sec;
323 }
324 timedelta -= tickdelta;
325 rel_mplock();
326 }
327
328 /*
329 * Apply per-tick compensation. ticks_adj adjusts for both
330 * offset and frequency, and could be negative.
331 */
332 if (nsec_adj != 0 && try_mplock()) {
333 nsec_acc += nsec_adj;
334 if (nsec_acc >= 0x100000000LL) {
335 basetime.tv_nsec += nsec_acc >> 32;
336 nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
337 } else if (nsec_acc <= -0x100000000LL) {
338 basetime.tv_nsec -= -nsec_acc >> 32;
339 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
340 }
341 if (basetime.tv_nsec >= 1000000000) {
342 basetime.tv_nsec -= 1000000000;
343 ++basetime.tv_sec;
344 } else if (basetime.tv_nsec < 0) {
345 basetime.tv_nsec += 1000000000;
346 --basetime.tv_sec;
347 }
348 rel_mplock();
349 }
350
351 /*
352 * If the realtime-adjusted seconds hand rolls over then tell
353 * ntp_update_second() what we did in the last second so it can
354 * calculate what to do in the next second. It may also add
355 * or subtract a leap second.
356 */
357 getnanotime(&nts);
358 if (time_second != nts.tv_sec) {
359 leap = ntp_update_second(time_second, &nsec_adj);
360 basetime.tv_sec += leap;
361 time_second = nts.tv_sec + leap;
362 nsec_adj /= hz;
363 }
364 }
365
92b561b7
MD
366 /*
367 * softticks are handled for all cpus
368 */
369 hardclock_softtick(gd);
370
88c4d2f6
MD
371 /*
372 * ITimer handling is per-tick, per-cpu. I don't think psignal()
373 * is mpsafe on curproc, so XXX get the mplock.
374 */
375 if ((p = curproc) != NULL && try_mplock()) {
984263bc 376 pstats = p->p_stats;
88c4d2f6 377 if (frame && CLKF_USERMODE(frame) &&
984263bc
MD
378 timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
379 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
380 psignal(p, SIGVTALRM);
381 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
382 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
383 psignal(p, SIGPROF);
88c4d2f6 384 rel_mplock();
984263bc 385 }
604e1e09 386 setdelayed();
88c4d2f6 387}
984263bc 388
88c4d2f6
MD
389/*
390 * The statistics clock typically runs at a 125Hz rate, and is intended
391 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu.
392 *
393 * NOTE! systimer! the MP lock might not be held here. We can only safely
394 * manipulate objects owned by the current cpu.
395 *
396 * The stats clock is responsible for grabbing a profiling sample.
397 * Most of the statistics are only used by user-level statistics programs.
398 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
399 * p->p_estcpu.
400 *
401 * Like the other clocks, the stat clock is called from what is effectively
402 * a fast interrupt, so the context should be the thread/process that got
403 * interrupted.
404 */
405static void
406statclock(systimer_t info, struct intrframe *frame)
407{
408#ifdef GPROF
409 struct gmonparam *g;
410 int i;
984263bc 411#endif
88c4d2f6
MD
412 thread_t td;
413 struct proc *p;
414 int bump;
415 struct timeval tv;
416 struct timeval *stv;
984263bc
MD
417
418 /*
88c4d2f6 419 * How big was our timeslice relative to the last time?
984263bc 420 */
88c4d2f6
MD
421 microuptime(&tv); /* mpsafe */
422 stv = &mycpu->gd_stattv;
423 if (stv->tv_sec == 0) {
424 bump = 1;
425 } else {
426 bump = tv.tv_usec - stv->tv_usec +
427 (tv.tv_sec - stv->tv_sec) * 1000000;
428 if (bump < 0)
429 bump = 0;
430 if (bump > 1000000)
431 bump = 1000000;
432 }
433 *stv = tv;
984263bc 434
88c4d2f6
MD
435 td = curthread;
436 p = td->td_proc;
984263bc 437
88c4d2f6
MD
438 if (frame && CLKF_USERMODE(frame)) {
439 /*
440 * Came from userland, handle user time and deal with
441 * possible process.
442 */
443 if (p && (p->p_flag & P_PROFIL))
444 addupc_intr(p, CLKF_PC(frame), 1);
445 td->td_uticks += bump;
984263bc 446
88c4d2f6
MD
447 /*
448 * Charge the time as appropriate
449 */
450 if (p && p->p_nice > NZERO)
451 cp_time[CP_NICE] += bump;
452 else
453 cp_time[CP_USER] += bump;
454 } else {
455#ifdef GPROF
456 /*
457 * Kernel statistics are just like addupc_intr, only easier.
458 */
459 g = &_gmonparam;
460 if (g->state == GMON_PROF_ON && frame) {
461 i = CLKF_PC(frame) - g->lowpc;
462 if (i < g->textsize) {
463 i /= HISTFRACTION * sizeof(*g->kcount);
464 g->kcount[i]++;
465 }
466 }
467#endif
468 /*
469 * Came from kernel mode, so we were:
470 * - handling an interrupt,
471 * - doing syscall or trap work on behalf of the current
472 * user process, or
473 * - spinning in the idle loop.
474 * Whichever it is, charge the time as appropriate.
475 * Note that we charge interrupts to the current process,
476 * regardless of whether they are ``for'' that process,
477 * so that we know how much of its real time was spent
478 * in ``non-process'' (i.e., interrupt) work.
479 *
480 * XXX assume system if frame is NULL. A NULL frame
481 * can occur if ipi processing is done from an splx().
482 */
483 if (frame && CLKF_INTR(frame))
484 td->td_iticks += bump;
485 else
486 td->td_sticks += bump;
487
488 if (frame && CLKF_INTR(frame)) {
489 cp_time[CP_INTR] += bump;
490 } else {
491 if (td == &mycpu->gd_idlethread)
492 cp_time[CP_IDLE] += bump;
493 else
494 cp_time[CP_SYS] += bump;
495 }
496 }
497}
498
499/*
0a3f9b47 500 * The scheduler clock typically runs at a 20Hz rate. NOTE! systimer,
88c4d2f6
MD
501 * the MP lock might not be held. We can safely manipulate parts of curproc
502 * but that's about it.
503 */
504static void
505schedclock(systimer_t info, struct intrframe *frame)
506{
507 struct proc *p;
508 struct pstats *pstats;
509 struct rusage *ru;
510 struct vmspace *vm;
511 long rss;
512
513 schedulerclock(NULL); /* mpsafe */
514 if ((p = curproc) != NULL) {
515 /* Update resource usage integrals and maximums. */
516 if ((pstats = p->p_stats) != NULL &&
517 (ru = &pstats->p_ru) != NULL &&
518 (vm = p->p_vmspace) != NULL) {
519 ru->ru_ixrss += pgtok(vm->vm_tsize);
520 ru->ru_idrss += pgtok(vm->vm_dsize);
521 ru->ru_isrss += pgtok(vm->vm_ssize);
522 rss = pgtok(vmspace_resident_count(vm));
523 if (ru->ru_maxrss < rss)
524 ru->ru_maxrss = rss;
525 }
b68b7282 526 }
984263bc
MD
527}
528
529/*
a94976ad
MD
530 * Compute number of ticks for the specified amount of time. The
531 * return value is intended to be used in a clock interrupt timed
532 * operation and guarenteed to meet or exceed the requested time.
533 * If the representation overflows, return INT_MAX. The minimum return
534 * value is 1 ticks and the function will average the calculation up.
535 * If any value greater then 0 microseconds is supplied, a value
536 * of at least 2 will be returned to ensure that a near-term clock
537 * interrupt does not cause the timeout to occur (degenerately) early.
538 *
539 * Note that limit checks must take into account microseconds, which is
540 * done simply by using the smaller signed long maximum instead of
541 * the unsigned long maximum.
542 *
543 * If ints have 32 bits, then the maximum value for any timeout in
544 * 10ms ticks is 248 days.
984263bc
MD
545 */
546int
a94976ad 547tvtohz_high(struct timeval *tv)
984263bc 548{
a94976ad 549 int ticks;
1fd87d54 550 long sec, usec;
984263bc 551
984263bc
MD
552 sec = tv->tv_sec;
553 usec = tv->tv_usec;
554 if (usec < 0) {
555 sec--;
556 usec += 1000000;
557 }
558 if (sec < 0) {
559#ifdef DIAGNOSTIC
560 if (usec > 0) {
561 sec++;
562 usec -= 1000000;
563 }
564 printf("tvotohz: negative time difference %ld sec %ld usec\n",
565 sec, usec);
566#endif
567 ticks = 1;
a94976ad
MD
568 } else if (sec <= INT_MAX / hz) {
569 ticks = (int)(sec * hz +
570 ((u_long)usec + (tick - 1)) / tick) + 1;
571 } else {
572 ticks = INT_MAX;
573 }
574 return (ticks);
575}
576
577/*
578 * Compute number of ticks for the specified amount of time, erroring on
579 * the side of it being too low to ensure that sleeping the returned number
580 * of ticks will not result in a late return.
581 *
582 * The supplied timeval may not be negative and should be normalized. A
583 * return value of 0 is possible if the timeval converts to less then
584 * 1 tick.
585 *
586 * If ints have 32 bits, then the maximum value for any timeout in
587 * 10ms ticks is 248 days.
588 */
589int
590tvtohz_low(struct timeval *tv)
591{
592 int ticks;
593 long sec;
594
595 sec = tv->tv_sec;
596 if (sec <= INT_MAX / hz)
597 ticks = (int)(sec * hz + (u_long)tv->tv_usec / tick);
984263bc 598 else
984263bc 599 ticks = INT_MAX;
a94976ad 600 return (ticks);
984263bc
MD
601}
602
a94976ad 603
984263bc
MD
604/*
605 * Start profiling on a process.
606 *
607 * Kernel profiling passes proc0 which never exits and hence
608 * keeps the profile clock running constantly.
609 */
610void
88c4d2f6 611startprofclock(struct proc *p)
984263bc 612{
984263bc
MD
613 if ((p->p_flag & P_PROFIL) == 0) {
614 p->p_flag |= P_PROFIL;
88c4d2f6 615#if 0 /* XXX */
984263bc
MD
616 if (++profprocs == 1 && stathz != 0) {
617 s = splstatclock();
6ad39cae 618 psdiv = psratio;
984263bc
MD
619 setstatclockrate(profhz);
620 splx(s);
621 }
88c4d2f6 622#endif
984263bc
MD
623 }
624}
625
626/*
627 * Stop profiling on a process.
628 */
629void
88c4d2f6 630stopprofclock(struct proc *p)
984263bc 631{
984263bc
MD
632 if (p->p_flag & P_PROFIL) {
633 p->p_flag &= ~P_PROFIL;
88c4d2f6 634#if 0 /* XXX */
984263bc
MD
635 if (--profprocs == 0 && stathz != 0) {
636 s = splstatclock();
6ad39cae 637 psdiv = 1;
984263bc
MD
638 setstatclockrate(stathz);
639 splx(s);
640 }
984263bc 641#endif
984263bc
MD
642 }
643}
644
645/*
646 * Return information about system clocks.
647 */
648static int
649sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
650{
651 struct clockinfo clkinfo;
652 /*
653 * Construct clockinfo structure.
654 */
655 clkinfo.hz = hz;
656 clkinfo.tick = tick;
657 clkinfo.tickadj = tickadj;
658 clkinfo.profhz = profhz;
659 clkinfo.stathz = stathz ? stathz : hz;
660 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
661}
662
663SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
664 0, 0, sysctl_kern_clockrate, "S,clockinfo","");
665
984263bc
MD
666/*
667 * We have eight functions for looking at the clock, four for
668 * microseconds and four for nanoseconds. For each there is fast
669 * but less precise version "get{nano|micro}[up]time" which will
670 * return a time which is up to 1/HZ previous to the call, whereas
671 * the raw version "{nano|micro}[up]time" will return a timestamp
672 * which is as precise as possible. The "up" variants return the
673 * time relative to system boot, these are well suited for time
674 * interval measurements.
88c4d2f6
MD
675 *
676 * Each cpu independantly maintains the current time of day, so all
677 * we need to do to protect ourselves from changes is to do a loop
678 * check on the seconds field changing out from under us.
984263bc 679 */
984263bc
MD
680void
681getmicrouptime(struct timeval *tvp)
682{
88c4d2f6
MD
683 struct globaldata *gd = mycpu;
684 sysclock_t delta;
685
686 do {
687 tvp->tv_sec = gd->gd_time_seconds;
688 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
689 } while (tvp->tv_sec != gd->gd_time_seconds);
690 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
691 if (tvp->tv_usec >= 1000000) {
692 tvp->tv_usec -= 1000000;
693 ++tvp->tv_sec;
984263bc
MD
694 }
695}
696
697void
698getnanouptime(struct timespec *tsp)
699{
88c4d2f6
MD
700 struct globaldata *gd = mycpu;
701 sysclock_t delta;
702
703 do {
704 tsp->tv_sec = gd->gd_time_seconds;
705 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
706 } while (tsp->tv_sec != gd->gd_time_seconds);
707 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
708 if (tsp->tv_nsec >= 1000000000) {
709 tsp->tv_nsec -= 1000000000;
710 ++tsp->tv_sec;
984263bc
MD
711 }
712}
713
714void
88c4d2f6 715microuptime(struct timeval *tvp)
984263bc 716{
88c4d2f6
MD
717 struct globaldata *gd = mycpu;
718 sysclock_t delta;
719
720 do {
721 tvp->tv_sec = gd->gd_time_seconds;
722 delta = cputimer_count() - gd->gd_cpuclock_base;
723 } while (tvp->tv_sec != gd->gd_time_seconds);
724 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
725 if (tvp->tv_usec >= 1000000) {
726 tvp->tv_usec -= 1000000;
727 ++tvp->tv_sec;
984263bc
MD
728 }
729}
730
731void
88c4d2f6 732nanouptime(struct timespec *tsp)
984263bc 733{
88c4d2f6
MD
734 struct globaldata *gd = mycpu;
735 sysclock_t delta;
736
737 do {
738 tsp->tv_sec = gd->gd_time_seconds;
739 delta = cputimer_count() - gd->gd_cpuclock_base;
740 } while (tsp->tv_sec != gd->gd_time_seconds);
741 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
742 if (tsp->tv_nsec >= 1000000000) {
743 tsp->tv_nsec -= 1000000000;
744 ++tsp->tv_sec;
984263bc 745 }
984263bc
MD
746}
747
88c4d2f6
MD
748/*
749 * realtime routines
750 */
984263bc
MD
751
752void
88c4d2f6 753getmicrotime(struct timeval *tvp)
984263bc 754{
88c4d2f6
MD
755 struct globaldata *gd = mycpu;
756 sysclock_t delta;
984263bc 757
88c4d2f6
MD
758 do {
759 tvp->tv_sec = gd->gd_time_seconds;
760 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
761 } while (tvp->tv_sec != gd->gd_time_seconds);
762 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
984263bc 763
88c4d2f6
MD
764 tvp->tv_sec += basetime.tv_sec;
765 tvp->tv_usec += basetime.tv_nsec / 1000;
766 while (tvp->tv_usec >= 1000000) {
767 tvp->tv_usec -= 1000000;
768 ++tvp->tv_sec;
984263bc 769 }
984263bc
MD
770}
771
772void
88c4d2f6 773getnanotime(struct timespec *tsp)
984263bc 774{
88c4d2f6
MD
775 struct globaldata *gd = mycpu;
776 sysclock_t delta;
984263bc 777
88c4d2f6
MD
778 do {
779 tsp->tv_sec = gd->gd_time_seconds;
780 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
781 } while (tsp->tv_sec != gd->gd_time_seconds);
782 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
984263bc 783
88c4d2f6
MD
784 tsp->tv_sec += basetime.tv_sec;
785 tsp->tv_nsec += basetime.tv_nsec;
786 while (tsp->tv_nsec >= 1000000000) {
787 tsp->tv_nsec -= 1000000000;
788 ++tsp->tv_sec;
984263bc 789 }
984263bc
MD
790}
791
88c4d2f6
MD
792void
793microtime(struct timeval *tvp)
984263bc 794{
88c4d2f6
MD
795 struct globaldata *gd = mycpu;
796 sysclock_t delta;
984263bc 797
88c4d2f6
MD
798 do {
799 tvp->tv_sec = gd->gd_time_seconds;
800 delta = cputimer_count() - gd->gd_cpuclock_base;
801 } while (tvp->tv_sec != gd->gd_time_seconds);
802 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
984263bc 803
88c4d2f6
MD
804 tvp->tv_sec += basetime.tv_sec;
805 tvp->tv_usec += basetime.tv_nsec / 1000;
806 while (tvp->tv_usec >= 1000000) {
807 tvp->tv_usec -= 1000000;
808 ++tvp->tv_sec;
984263bc 809 }
984263bc
MD
810}
811
88c4d2f6
MD
812void
813nanotime(struct timespec *tsp)
814{
815 struct globaldata *gd = mycpu;
816 sysclock_t delta;
984263bc 817
88c4d2f6
MD
818 do {
819 tsp->tv_sec = gd->gd_time_seconds;
820 delta = cputimer_count() - gd->gd_cpuclock_base;
821 } while (tsp->tv_sec != gd->gd_time_seconds);
822 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
984263bc 823
88c4d2f6
MD
824 tsp->tv_sec += basetime.tv_sec;
825 tsp->tv_nsec += basetime.tv_nsec;
826 while (tsp->tv_nsec >= 1000000000) {
827 tsp->tv_nsec -= 1000000000;
828 ++tsp->tv_sec;
984263bc 829 }
984263bc
MD
830}
831
984263bc
MD
832int
833pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
834{
835 pps_params_t *app;
836 struct pps_fetch_args *fapi;
837#ifdef PPS_SYNC
838 struct pps_kcbind_args *kapi;
839#endif
840
841 switch (cmd) {
842 case PPS_IOC_CREATE:
843 return (0);
844 case PPS_IOC_DESTROY:
845 return (0);
846 case PPS_IOC_SETPARAMS:
847 app = (pps_params_t *)data;
848 if (app->mode & ~pps->ppscap)
849 return (EINVAL);
850 pps->ppsparam = *app;
851 return (0);
852 case PPS_IOC_GETPARAMS:
853 app = (pps_params_t *)data;
854 *app = pps->ppsparam;
855 app->api_version = PPS_API_VERS_1;
856 return (0);
857 case PPS_IOC_GETCAP:
858 *(int*)data = pps->ppscap;
859 return (0);
860 case PPS_IOC_FETCH:
861 fapi = (struct pps_fetch_args *)data;
862 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
863 return (EINVAL);
864 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
865 return (EOPNOTSUPP);
866 pps->ppsinfo.current_mode = pps->ppsparam.mode;
867 fapi->pps_info_buf = pps->ppsinfo;
868 return (0);
869 case PPS_IOC_KCBIND:
870#ifdef PPS_SYNC
871 kapi = (struct pps_kcbind_args *)data;
872 /* XXX Only root should be able to do this */
873 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
874 return (EINVAL);
875 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
876 return (EINVAL);
877 if (kapi->edge & ~pps->ppscap)
878 return (EINVAL);
879 pps->kcmode = kapi->edge;
880 return (0);
881#else
882 return (EOPNOTSUPP);
883#endif
884 default:
885 return (ENOTTY);
886 }
887}
888
889void
890pps_init(struct pps_state *pps)
891{
892 pps->ppscap |= PPS_TSFMT_TSPEC;
893 if (pps->ppscap & PPS_CAPTUREASSERT)
894 pps->ppscap |= PPS_OFFSETASSERT;
895 if (pps->ppscap & PPS_CAPTURECLEAR)
896 pps->ppscap |= PPS_OFFSETCLEAR;
897}
898
899void
88c4d2f6 900pps_event(struct pps_state *pps, sysclock_t count, int event)
984263bc 901{
88c4d2f6
MD
902 struct globaldata *gd;
903 struct timespec *tsp;
904 struct timespec *osp;
905 struct timespec ts;
906 sysclock_t *pcount;
907#ifdef PPS_SYNC
908 sysclock_t tcount;
909#endif
910 sysclock_t delta;
911 pps_seq_t *pseq;
912 int foff;
913 int fhard;
914
915 gd = mycpu;
984263bc
MD
916
917 /* Things would be easier with arrays... */
918 if (event == PPS_CAPTUREASSERT) {
919 tsp = &pps->ppsinfo.assert_timestamp;
920 osp = &pps->ppsparam.assert_offset;
921 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
922 fhard = pps->kcmode & PPS_CAPTUREASSERT;
923 pcount = &pps->ppscount[0];
924 pseq = &pps->ppsinfo.assert_sequence;
925 } else {
926 tsp = &pps->ppsinfo.clear_timestamp;
927 osp = &pps->ppsparam.clear_offset;
928 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
929 fhard = pps->kcmode & PPS_CAPTURECLEAR;
930 pcount = &pps->ppscount[1];
931 pseq = &pps->ppsinfo.clear_sequence;
932 }
933
984263bc
MD
934 /* Nothing really happened */
935 if (*pcount == count)
936 return;
937
938 *pcount = count;
939
88c4d2f6
MD
940 do {
941 ts.tv_sec = gd->gd_time_seconds;
942 delta = count - gd->gd_cpuclock_base;
943 } while (ts.tv_sec != gd->gd_time_seconds);
944 if (delta > cputimer_freq) {
945 ts.tv_sec += delta / cputimer_freq;
946 delta %= cputimer_freq;
947 }
948 ts.tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
949 ts.tv_sec += basetime.tv_sec;
950 ts.tv_nsec += basetime.tv_nsec;
951 while (ts.tv_nsec >= 1000000000) {
952 ts.tv_nsec -= 1000000000;
953 ++ts.tv_sec;
984263bc 954 }
984263bc
MD
955
956 (*pseq)++;
957 *tsp = ts;
958
959 if (foff) {
960 timespecadd(tsp, osp);
961 if (tsp->tv_nsec < 0) {
962 tsp->tv_nsec += 1000000000;
963 tsp->tv_sec -= 1;
964 }
965 }
966#ifdef PPS_SYNC
967 if (fhard) {
968 /* magic, at its best... */
969 tcount = count - pps->ppscount[2];
970 pps->ppscount[2] = count;
88c4d2f6 971 delta = (cputimer_freq64_nsec * tcount) >> 32;
984263bc
MD
972 hardpps(tsp, delta);
973 }
974#endif
975}
88c4d2f6 976