Fix a conditional. sdl was not unconditionally being checked for NULL.
[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 $
7c3d1214 73 * $DragonFly: src/sys/kern/kern_clock.c,v 1.26 2004/11/12 17:50:56 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)
fad57d0e
MD
282 * to reverse index gd_cpuclock_base, but that it is possible for
283 * it to temporarily get behind in the seconds if something in the
284 * system locks interrupts for a long period of time. Since periodic
285 * timers count events, though everything should resynch again
286 * immediately.
984263bc 287 */
88c4d2f6 288 cputicks = info->time - gd->gd_cpuclock_base;
fad57d0e 289 if (cputicks >= cputimer_freq) {
88c4d2f6
MD
290 ++gd->gd_time_seconds;
291 gd->gd_cpuclock_base += cputimer_freq;
292 }
984263bc
MD
293
294 /*
92b561b7
MD
295 * The system-wide ticks counter and NTP related timedelta/tickdelta
296 * adjustments only occur on cpu #0. NTP adjustments are accomplished
297 * by updating basetime.
984263bc 298 */
88c4d2f6
MD
299 if (gd->gd_cpuid == 0) {
300 struct timespec nts;
301 int leap;
984263bc 302
88c4d2f6 303 ++ticks;
984263bc 304
88c4d2f6
MD
305#ifdef DEVICE_POLLING
306 hardclock_device_poll(); /* mpsafe, short and quick */
307#endif /* DEVICE_POLLING */
984263bc 308
88c4d2f6
MD
309#if 0
310 if (tco->tc_poll_pps)
311 tco->tc_poll_pps(tco);
312#endif
313 /*
314 * Apply adjtime corrections. At the moment only do this if
315 * we can get the MP lock to interlock with adjtime's modification
316 * of these variables. Note that basetime adjustments are not
317 * MP safe either XXX.
318 */
319 if (timedelta != 0 && try_mplock()) {
320 basetime.tv_nsec += tickdelta * 1000;
321 if (basetime.tv_nsec >= 1000000000) {
322 basetime.tv_nsec -= 1000000000;
323 ++basetime.tv_sec;
324 } else if (basetime.tv_nsec < 0) {
325 basetime.tv_nsec += 1000000000;
326 --basetime.tv_sec;
327 }
328 timedelta -= tickdelta;
329 rel_mplock();
330 }
331
332 /*
333 * Apply per-tick compensation. ticks_adj adjusts for both
334 * offset and frequency, and could be negative.
335 */
336 if (nsec_adj != 0 && try_mplock()) {
337 nsec_acc += nsec_adj;
338 if (nsec_acc >= 0x100000000LL) {
339 basetime.tv_nsec += nsec_acc >> 32;
340 nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
341 } else if (nsec_acc <= -0x100000000LL) {
342 basetime.tv_nsec -= -nsec_acc >> 32;
343 nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
344 }
345 if (basetime.tv_nsec >= 1000000000) {
346 basetime.tv_nsec -= 1000000000;
347 ++basetime.tv_sec;
348 } else if (basetime.tv_nsec < 0) {
349 basetime.tv_nsec += 1000000000;
350 --basetime.tv_sec;
351 }
352 rel_mplock();
353 }
354
355 /*
356 * If the realtime-adjusted seconds hand rolls over then tell
357 * ntp_update_second() what we did in the last second so it can
358 * calculate what to do in the next second. It may also add
359 * or subtract a leap second.
360 */
361 getnanotime(&nts);
362 if (time_second != nts.tv_sec) {
363 leap = ntp_update_second(time_second, &nsec_adj);
364 basetime.tv_sec += leap;
365 time_second = nts.tv_sec + leap;
366 nsec_adj /= hz;
367 }
368 }
369
92b561b7
MD
370 /*
371 * softticks are handled for all cpus
372 */
373 hardclock_softtick(gd);
374
88c4d2f6
MD
375 /*
376 * ITimer handling is per-tick, per-cpu. I don't think psignal()
377 * is mpsafe on curproc, so XXX get the mplock.
378 */
379 if ((p = curproc) != NULL && try_mplock()) {
984263bc 380 pstats = p->p_stats;
88c4d2f6 381 if (frame && CLKF_USERMODE(frame) &&
984263bc
MD
382 timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
383 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
384 psignal(p, SIGVTALRM);
385 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
386 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
387 psignal(p, SIGPROF);
88c4d2f6 388 rel_mplock();
984263bc 389 }
604e1e09 390 setdelayed();
88c4d2f6 391}
984263bc 392
88c4d2f6
MD
393/*
394 * The statistics clock typically runs at a 125Hz rate, and is intended
395 * to be frequency offset from the hardclock (typ 100Hz). It is per-cpu.
396 *
397 * NOTE! systimer! the MP lock might not be held here. We can only safely
398 * manipulate objects owned by the current cpu.
399 *
400 * The stats clock is responsible for grabbing a profiling sample.
401 * Most of the statistics are only used by user-level statistics programs.
402 * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
403 * p->p_estcpu.
404 *
405 * Like the other clocks, the stat clock is called from what is effectively
406 * a fast interrupt, so the context should be the thread/process that got
407 * interrupted.
408 */
409static void
410statclock(systimer_t info, struct intrframe *frame)
411{
412#ifdef GPROF
413 struct gmonparam *g;
414 int i;
984263bc 415#endif
88c4d2f6
MD
416 thread_t td;
417 struct proc *p;
418 int bump;
419 struct timeval tv;
420 struct timeval *stv;
984263bc
MD
421
422 /*
88c4d2f6 423 * How big was our timeslice relative to the last time?
984263bc 424 */
88c4d2f6
MD
425 microuptime(&tv); /* mpsafe */
426 stv = &mycpu->gd_stattv;
427 if (stv->tv_sec == 0) {
428 bump = 1;
429 } else {
430 bump = tv.tv_usec - stv->tv_usec +
431 (tv.tv_sec - stv->tv_sec) * 1000000;
432 if (bump < 0)
433 bump = 0;
434 if (bump > 1000000)
435 bump = 1000000;
436 }
437 *stv = tv;
984263bc 438
88c4d2f6
MD
439 td = curthread;
440 p = td->td_proc;
984263bc 441
88c4d2f6
MD
442 if (frame && CLKF_USERMODE(frame)) {
443 /*
444 * Came from userland, handle user time and deal with
445 * possible process.
446 */
447 if (p && (p->p_flag & P_PROFIL))
448 addupc_intr(p, CLKF_PC(frame), 1);
449 td->td_uticks += bump;
984263bc 450
88c4d2f6
MD
451 /*
452 * Charge the time as appropriate
453 */
454 if (p && p->p_nice > NZERO)
455 cp_time[CP_NICE] += bump;
456 else
457 cp_time[CP_USER] += bump;
458 } else {
459#ifdef GPROF
460 /*
461 * Kernel statistics are just like addupc_intr, only easier.
462 */
463 g = &_gmonparam;
464 if (g->state == GMON_PROF_ON && frame) {
465 i = CLKF_PC(frame) - g->lowpc;
466 if (i < g->textsize) {
467 i /= HISTFRACTION * sizeof(*g->kcount);
468 g->kcount[i]++;
469 }
470 }
471#endif
472 /*
473 * Came from kernel mode, so we were:
474 * - handling an interrupt,
475 * - doing syscall or trap work on behalf of the current
476 * user process, or
477 * - spinning in the idle loop.
478 * Whichever it is, charge the time as appropriate.
479 * Note that we charge interrupts to the current process,
480 * regardless of whether they are ``for'' that process,
481 * so that we know how much of its real time was spent
482 * in ``non-process'' (i.e., interrupt) work.
483 *
484 * XXX assume system if frame is NULL. A NULL frame
485 * can occur if ipi processing is done from an splx().
486 */
487 if (frame && CLKF_INTR(frame))
488 td->td_iticks += bump;
489 else
490 td->td_sticks += bump;
491
492 if (frame && CLKF_INTR(frame)) {
493 cp_time[CP_INTR] += bump;
494 } else {
495 if (td == &mycpu->gd_idlethread)
496 cp_time[CP_IDLE] += bump;
497 else
498 cp_time[CP_SYS] += bump;
499 }
500 }
501}
502
503/*
0a3f9b47 504 * The scheduler clock typically runs at a 20Hz rate. NOTE! systimer,
88c4d2f6
MD
505 * the MP lock might not be held. We can safely manipulate parts of curproc
506 * but that's about it.
507 */
508static void
509schedclock(systimer_t info, struct intrframe *frame)
510{
511 struct proc *p;
512 struct pstats *pstats;
513 struct rusage *ru;
514 struct vmspace *vm;
515 long rss;
516
517 schedulerclock(NULL); /* mpsafe */
518 if ((p = curproc) != NULL) {
519 /* Update resource usage integrals and maximums. */
520 if ((pstats = p->p_stats) != NULL &&
521 (ru = &pstats->p_ru) != NULL &&
522 (vm = p->p_vmspace) != NULL) {
523 ru->ru_ixrss += pgtok(vm->vm_tsize);
524 ru->ru_idrss += pgtok(vm->vm_dsize);
525 ru->ru_isrss += pgtok(vm->vm_ssize);
526 rss = pgtok(vmspace_resident_count(vm));
527 if (ru->ru_maxrss < rss)
528 ru->ru_maxrss = rss;
529 }
b68b7282 530 }
984263bc
MD
531}
532
533/*
a94976ad
MD
534 * Compute number of ticks for the specified amount of time. The
535 * return value is intended to be used in a clock interrupt timed
536 * operation and guarenteed to meet or exceed the requested time.
537 * If the representation overflows, return INT_MAX. The minimum return
538 * value is 1 ticks and the function will average the calculation up.
539 * If any value greater then 0 microseconds is supplied, a value
540 * of at least 2 will be returned to ensure that a near-term clock
541 * interrupt does not cause the timeout to occur (degenerately) early.
542 *
543 * Note that limit checks must take into account microseconds, which is
544 * done simply by using the smaller signed long maximum instead of
545 * the unsigned long maximum.
546 *
547 * If ints have 32 bits, then the maximum value for any timeout in
548 * 10ms ticks is 248 days.
984263bc
MD
549 */
550int
a94976ad 551tvtohz_high(struct timeval *tv)
984263bc 552{
a94976ad 553 int ticks;
1fd87d54 554 long sec, usec;
984263bc 555
984263bc
MD
556 sec = tv->tv_sec;
557 usec = tv->tv_usec;
558 if (usec < 0) {
559 sec--;
560 usec += 1000000;
561 }
562 if (sec < 0) {
563#ifdef DIAGNOSTIC
564 if (usec > 0) {
565 sec++;
566 usec -= 1000000;
567 }
568 printf("tvotohz: negative time difference %ld sec %ld usec\n",
569 sec, usec);
570#endif
571 ticks = 1;
a94976ad
MD
572 } else if (sec <= INT_MAX / hz) {
573 ticks = (int)(sec * hz +
574 ((u_long)usec + (tick - 1)) / tick) + 1;
575 } else {
576 ticks = INT_MAX;
577 }
578 return (ticks);
579}
580
581/*
582 * Compute number of ticks for the specified amount of time, erroring on
583 * the side of it being too low to ensure that sleeping the returned number
584 * of ticks will not result in a late return.
585 *
586 * The supplied timeval may not be negative and should be normalized. A
587 * return value of 0 is possible if the timeval converts to less then
588 * 1 tick.
589 *
590 * If ints have 32 bits, then the maximum value for any timeout in
591 * 10ms ticks is 248 days.
592 */
593int
594tvtohz_low(struct timeval *tv)
595{
596 int ticks;
597 long sec;
598
599 sec = tv->tv_sec;
600 if (sec <= INT_MAX / hz)
601 ticks = (int)(sec * hz + (u_long)tv->tv_usec / tick);
984263bc 602 else
984263bc 603 ticks = INT_MAX;
a94976ad 604 return (ticks);
984263bc
MD
605}
606
a94976ad 607
984263bc
MD
608/*
609 * Start profiling on a process.
610 *
611 * Kernel profiling passes proc0 which never exits and hence
612 * keeps the profile clock running constantly.
613 */
614void
88c4d2f6 615startprofclock(struct proc *p)
984263bc 616{
984263bc
MD
617 if ((p->p_flag & P_PROFIL) == 0) {
618 p->p_flag |= P_PROFIL;
88c4d2f6 619#if 0 /* XXX */
984263bc
MD
620 if (++profprocs == 1 && stathz != 0) {
621 s = splstatclock();
6ad39cae 622 psdiv = psratio;
984263bc
MD
623 setstatclockrate(profhz);
624 splx(s);
625 }
88c4d2f6 626#endif
984263bc
MD
627 }
628}
629
630/*
631 * Stop profiling on a process.
632 */
633void
88c4d2f6 634stopprofclock(struct proc *p)
984263bc 635{
984263bc
MD
636 if (p->p_flag & P_PROFIL) {
637 p->p_flag &= ~P_PROFIL;
88c4d2f6 638#if 0 /* XXX */
984263bc
MD
639 if (--profprocs == 0 && stathz != 0) {
640 s = splstatclock();
6ad39cae 641 psdiv = 1;
984263bc
MD
642 setstatclockrate(stathz);
643 splx(s);
644 }
984263bc 645#endif
984263bc
MD
646 }
647}
648
649/*
650 * Return information about system clocks.
651 */
652static int
653sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
654{
655 struct clockinfo clkinfo;
656 /*
657 * Construct clockinfo structure.
658 */
659 clkinfo.hz = hz;
660 clkinfo.tick = tick;
661 clkinfo.tickadj = tickadj;
662 clkinfo.profhz = profhz;
663 clkinfo.stathz = stathz ? stathz : hz;
664 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
665}
666
667SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
668 0, 0, sysctl_kern_clockrate, "S,clockinfo","");
669
984263bc
MD
670/*
671 * We have eight functions for looking at the clock, four for
672 * microseconds and four for nanoseconds. For each there is fast
673 * but less precise version "get{nano|micro}[up]time" which will
674 * return a time which is up to 1/HZ previous to the call, whereas
675 * the raw version "{nano|micro}[up]time" will return a timestamp
676 * which is as precise as possible. The "up" variants return the
677 * time relative to system boot, these are well suited for time
678 * interval measurements.
88c4d2f6
MD
679 *
680 * Each cpu independantly maintains the current time of day, so all
681 * we need to do to protect ourselves from changes is to do a loop
682 * check on the seconds field changing out from under us.
fad57d0e
MD
683 *
684 * The system timer maintains a 32 bit count and due to various issues
685 * it is possible for the calculated delta to occassionally exceed
686 * cputimer_freq. If this occurs the cputimer_freq64_nsec multiplication
687 * can easily overflow, so we deal with the case. For uniformity we deal
688 * with the case in the usec case too.
984263bc 689 */
984263bc
MD
690void
691getmicrouptime(struct timeval *tvp)
692{
88c4d2f6
MD
693 struct globaldata *gd = mycpu;
694 sysclock_t delta;
695
696 do {
697 tvp->tv_sec = gd->gd_time_seconds;
698 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
699 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
700
701 if (delta >= cputimer_freq) {
702 tvp->tv_sec += delta / cputimer_freq;
703 delta %= cputimer_freq;
704 }
88c4d2f6
MD
705 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
706 if (tvp->tv_usec >= 1000000) {
707 tvp->tv_usec -= 1000000;
708 ++tvp->tv_sec;
984263bc
MD
709 }
710}
711
712void
713getnanouptime(struct timespec *tsp)
714{
88c4d2f6
MD
715 struct globaldata *gd = mycpu;
716 sysclock_t delta;
717
718 do {
719 tsp->tv_sec = gd->gd_time_seconds;
720 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
721 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
722
723 if (delta >= cputimer_freq) {
724 tsp->tv_sec += delta / cputimer_freq;
725 delta %= cputimer_freq;
984263bc 726 }
fad57d0e 727 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
984263bc
MD
728}
729
730void
88c4d2f6 731microuptime(struct timeval *tvp)
984263bc 732{
88c4d2f6
MD
733 struct globaldata *gd = mycpu;
734 sysclock_t delta;
735
736 do {
737 tvp->tv_sec = gd->gd_time_seconds;
738 delta = cputimer_count() - gd->gd_cpuclock_base;
739 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
740
741 if (delta >= cputimer_freq) {
742 tvp->tv_sec += delta / cputimer_freq;
743 delta %= cputimer_freq;
984263bc 744 }
fad57d0e 745 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
984263bc
MD
746}
747
748void
88c4d2f6 749nanouptime(struct timespec *tsp)
984263bc 750{
88c4d2f6
MD
751 struct globaldata *gd = mycpu;
752 sysclock_t delta;
753
754 do {
755 tsp->tv_sec = gd->gd_time_seconds;
756 delta = cputimer_count() - gd->gd_cpuclock_base;
757 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
758
759 if (delta >= cputimer_freq) {
760 tsp->tv_sec += delta / cputimer_freq;
761 delta %= cputimer_freq;
984263bc 762 }
fad57d0e 763 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
984263bc
MD
764}
765
88c4d2f6
MD
766/*
767 * realtime routines
768 */
984263bc
MD
769
770void
88c4d2f6 771getmicrotime(struct timeval *tvp)
984263bc 772{
88c4d2f6
MD
773 struct globaldata *gd = mycpu;
774 sysclock_t delta;
984263bc 775
88c4d2f6
MD
776 do {
777 tvp->tv_sec = gd->gd_time_seconds;
778 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
779 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
780
781 if (delta >= cputimer_freq) {
782 tvp->tv_sec += delta / cputimer_freq;
783 delta %= cputimer_freq;
784 }
88c4d2f6 785 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
984263bc 786
88c4d2f6
MD
787 tvp->tv_sec += basetime.tv_sec;
788 tvp->tv_usec += basetime.tv_nsec / 1000;
789 while (tvp->tv_usec >= 1000000) {
790 tvp->tv_usec -= 1000000;
791 ++tvp->tv_sec;
984263bc 792 }
984263bc
MD
793}
794
795void
88c4d2f6 796getnanotime(struct timespec *tsp)
984263bc 797{
88c4d2f6
MD
798 struct globaldata *gd = mycpu;
799 sysclock_t delta;
984263bc 800
88c4d2f6
MD
801 do {
802 tsp->tv_sec = gd->gd_time_seconds;
803 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
804 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
805
806 if (delta >= cputimer_freq) {
807 tsp->tv_sec += delta / cputimer_freq;
808 delta %= cputimer_freq;
809 }
88c4d2f6 810 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
984263bc 811
88c4d2f6
MD
812 tsp->tv_sec += basetime.tv_sec;
813 tsp->tv_nsec += basetime.tv_nsec;
814 while (tsp->tv_nsec >= 1000000000) {
815 tsp->tv_nsec -= 1000000000;
816 ++tsp->tv_sec;
984263bc 817 }
984263bc
MD
818}
819
88c4d2f6
MD
820void
821microtime(struct timeval *tvp)
984263bc 822{
88c4d2f6
MD
823 struct globaldata *gd = mycpu;
824 sysclock_t delta;
984263bc 825
88c4d2f6
MD
826 do {
827 tvp->tv_sec = gd->gd_time_seconds;
828 delta = cputimer_count() - gd->gd_cpuclock_base;
829 } while (tvp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
830
831 if (delta >= cputimer_freq) {
832 tvp->tv_sec += delta / cputimer_freq;
833 delta %= cputimer_freq;
834 }
88c4d2f6 835 tvp->tv_usec = (cputimer_freq64_usec * delta) >> 32;
984263bc 836
88c4d2f6
MD
837 tvp->tv_sec += basetime.tv_sec;
838 tvp->tv_usec += basetime.tv_nsec / 1000;
839 while (tvp->tv_usec >= 1000000) {
840 tvp->tv_usec -= 1000000;
841 ++tvp->tv_sec;
984263bc 842 }
984263bc
MD
843}
844
88c4d2f6
MD
845void
846nanotime(struct timespec *tsp)
847{
848 struct globaldata *gd = mycpu;
849 sysclock_t delta;
984263bc 850
88c4d2f6
MD
851 do {
852 tsp->tv_sec = gd->gd_time_seconds;
853 delta = cputimer_count() - gd->gd_cpuclock_base;
854 } while (tsp->tv_sec != gd->gd_time_seconds);
fad57d0e
MD
855
856 if (delta >= cputimer_freq) {
857 tsp->tv_sec += delta / cputimer_freq;
858 delta %= cputimer_freq;
859 }
88c4d2f6 860 tsp->tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
984263bc 861
88c4d2f6
MD
862 tsp->tv_sec += basetime.tv_sec;
863 tsp->tv_nsec += basetime.tv_nsec;
864 while (tsp->tv_nsec >= 1000000000) {
865 tsp->tv_nsec -= 1000000000;
866 ++tsp->tv_sec;
984263bc 867 }
984263bc
MD
868}
869
984263bc
MD
870int
871pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
872{
873 pps_params_t *app;
874 struct pps_fetch_args *fapi;
875#ifdef PPS_SYNC
876 struct pps_kcbind_args *kapi;
877#endif
878
879 switch (cmd) {
880 case PPS_IOC_CREATE:
881 return (0);
882 case PPS_IOC_DESTROY:
883 return (0);
884 case PPS_IOC_SETPARAMS:
885 app = (pps_params_t *)data;
886 if (app->mode & ~pps->ppscap)
887 return (EINVAL);
888 pps->ppsparam = *app;
889 return (0);
890 case PPS_IOC_GETPARAMS:
891 app = (pps_params_t *)data;
892 *app = pps->ppsparam;
893 app->api_version = PPS_API_VERS_1;
894 return (0);
895 case PPS_IOC_GETCAP:
896 *(int*)data = pps->ppscap;
897 return (0);
898 case PPS_IOC_FETCH:
899 fapi = (struct pps_fetch_args *)data;
900 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
901 return (EINVAL);
902 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
903 return (EOPNOTSUPP);
904 pps->ppsinfo.current_mode = pps->ppsparam.mode;
905 fapi->pps_info_buf = pps->ppsinfo;
906 return (0);
907 case PPS_IOC_KCBIND:
908#ifdef PPS_SYNC
909 kapi = (struct pps_kcbind_args *)data;
910 /* XXX Only root should be able to do this */
911 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
912 return (EINVAL);
913 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
914 return (EINVAL);
915 if (kapi->edge & ~pps->ppscap)
916 return (EINVAL);
917 pps->kcmode = kapi->edge;
918 return (0);
919#else
920 return (EOPNOTSUPP);
921#endif
922 default:
923 return (ENOTTY);
924 }
925}
926
927void
928pps_init(struct pps_state *pps)
929{
930 pps->ppscap |= PPS_TSFMT_TSPEC;
931 if (pps->ppscap & PPS_CAPTUREASSERT)
932 pps->ppscap |= PPS_OFFSETASSERT;
933 if (pps->ppscap & PPS_CAPTURECLEAR)
934 pps->ppscap |= PPS_OFFSETCLEAR;
935}
936
937void
88c4d2f6 938pps_event(struct pps_state *pps, sysclock_t count, int event)
984263bc 939{
88c4d2f6
MD
940 struct globaldata *gd;
941 struct timespec *tsp;
942 struct timespec *osp;
943 struct timespec ts;
944 sysclock_t *pcount;
945#ifdef PPS_SYNC
946 sysclock_t tcount;
947#endif
948 sysclock_t delta;
949 pps_seq_t *pseq;
950 int foff;
951 int fhard;
952
953 gd = mycpu;
984263bc
MD
954
955 /* Things would be easier with arrays... */
956 if (event == PPS_CAPTUREASSERT) {
957 tsp = &pps->ppsinfo.assert_timestamp;
958 osp = &pps->ppsparam.assert_offset;
959 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
960 fhard = pps->kcmode & PPS_CAPTUREASSERT;
961 pcount = &pps->ppscount[0];
962 pseq = &pps->ppsinfo.assert_sequence;
963 } else {
964 tsp = &pps->ppsinfo.clear_timestamp;
965 osp = &pps->ppsparam.clear_offset;
966 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
967 fhard = pps->kcmode & PPS_CAPTURECLEAR;
968 pcount = &pps->ppscount[1];
969 pseq = &pps->ppsinfo.clear_sequence;
970 }
971
984263bc
MD
972 /* Nothing really happened */
973 if (*pcount == count)
974 return;
975
976 *pcount = count;
977
88c4d2f6
MD
978 do {
979 ts.tv_sec = gd->gd_time_seconds;
980 delta = count - gd->gd_cpuclock_base;
981 } while (ts.tv_sec != gd->gd_time_seconds);
fad57d0e
MD
982
983 if (delta >= cputimer_freq) {
88c4d2f6
MD
984 ts.tv_sec += delta / cputimer_freq;
985 delta %= cputimer_freq;
986 }
987 ts.tv_nsec = (cputimer_freq64_nsec * delta) >> 32;
988 ts.tv_sec += basetime.tv_sec;
989 ts.tv_nsec += basetime.tv_nsec;
990 while (ts.tv_nsec >= 1000000000) {
991 ts.tv_nsec -= 1000000000;
992 ++ts.tv_sec;
984263bc 993 }
984263bc
MD
994
995 (*pseq)++;
996 *tsp = ts;
997
998 if (foff) {
999 timespecadd(tsp, osp);
1000 if (tsp->tv_nsec < 0) {
1001 tsp->tv_nsec += 1000000000;
1002 tsp->tv_sec -= 1;
1003 }
1004 }
1005#ifdef PPS_SYNC
1006 if (fhard) {
1007 /* magic, at its best... */
1008 tcount = count - pps->ppscount[2];
1009 pps->ppscount[2] = count;
fad57d0e
MD
1010 if (tcount >= cputimer_freq) {
1011 delta = 1000000000 * (tcount / cputimer_freq) +
1012 (cputimer_freq64_nsec *
1013 (tcount % cputimer_freq)) >> 32;
1014 } else {
1015 delta = (cputimer_freq64_nsec * tcount) >> 32;
1016 }
984263bc
MD
1017 hardpps(tsp, delta);
1018 }
1019#endif
1020}
88c4d2f6 1021