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