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