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