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