hammer2 / kern_dmsg - Fix bugs
[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. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  *
67  *      @(#)kern_clock.c        8.5 (Berkeley) 1/21/94
68  * $FreeBSD: src/sys/kern/kern_clock.c,v 1.105.2.10 2002/10/17 13:19:40 maxim Exp $
69  */
70
71 #include "opt_ntp.h"
72 #include "opt_ifpoll.h"
73 #include "opt_pctrack.h"
74
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/callout.h>
78 #include <sys/kernel.h>
79 #include <sys/kinfo.h>
80 #include <sys/proc.h>
81 #include <sys/malloc.h>
82 #include <sys/resource.h>
83 #include <sys/resourcevar.h>
84 #include <sys/signalvar.h>
85 #include <sys/timex.h>
86 #include <sys/timepps.h>
87 #include <sys/upmap.h>
88 #include <vm/vm.h>
89 #include <sys/lock.h>
90 #include <vm/pmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_extern.h>
93 #include <sys/sysctl.h>
94
95 #include <sys/thread2.h>
96 #include <sys/mplock2.h>
97
98 #include <machine/cpu.h>
99 #include <machine/limits.h>
100 #include <machine/smp.h>
101 #include <machine/cpufunc.h>
102 #include <machine/specialreg.h>
103 #include <machine/clock.h>
104
105 #ifdef GPROF
106 #include <sys/gmon.h>
107 #endif
108
109 #ifdef IFPOLL_ENABLE
110 extern void ifpoll_init_pcpu(int);
111 #endif
112
113 #ifdef DEBUG_PCTRACK
114 static void do_pctrack(struct intrframe *frame, int which);
115 #endif
116
117 static void initclocks (void *dummy);
118 SYSINIT(clocks, SI_BOOT2_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
119
120 /*
121  * Some of these don't belong here, but it's easiest to concentrate them.
122  * Note that cpu_time counts in microseconds, but most userland programs
123  * just compare relative times against the total by delta.
124  */
125 struct kinfo_cputime cputime_percpu[MAXCPU];
126 #ifdef DEBUG_PCTRACK
127 struct kinfo_pcheader cputime_pcheader = { PCTRACK_SIZE, PCTRACK_ARYSIZE };
128 struct kinfo_pctrack cputime_pctrack[MAXCPU][PCTRACK_SIZE];
129 #endif
130
131 static int
132 sysctl_cputime(SYSCTL_HANDLER_ARGS)
133 {
134         int cpu, error = 0;
135         size_t size = sizeof(struct kinfo_cputime);
136
137         for (cpu = 0; cpu < ncpus; ++cpu) {
138                 if ((error = SYSCTL_OUT(req, &cputime_percpu[cpu], size)))
139                         break;
140         }
141
142         return (error);
143 }
144 SYSCTL_PROC(_kern, OID_AUTO, cputime, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
145         sysctl_cputime, "S,kinfo_cputime", "CPU time statistics");
146
147 static int
148 sysctl_cp_time(SYSCTL_HANDLER_ARGS)
149 {
150         long cpu_states[5] = {0};
151         int cpu, error = 0;
152         size_t size = sizeof(cpu_states);
153
154         for (cpu = 0; cpu < ncpus; ++cpu) {
155                 cpu_states[CP_USER] += cputime_percpu[cpu].cp_user;
156                 cpu_states[CP_NICE] += cputime_percpu[cpu].cp_nice;
157                 cpu_states[CP_SYS] += cputime_percpu[cpu].cp_sys;
158                 cpu_states[CP_INTR] += cputime_percpu[cpu].cp_intr;
159                 cpu_states[CP_IDLE] += cputime_percpu[cpu].cp_idle;
160         }
161
162         error = SYSCTL_OUT(req, cpu_states, size);
163
164         return (error);
165 }
166
167 SYSCTL_PROC(_kern, OID_AUTO, cp_time, (CTLTYPE_LONG|CTLFLAG_RD), 0, 0,
168         sysctl_cp_time, "LU", "CPU time statistics");
169
170 /*
171  * boottime is used to calculate the 'real' uptime.  Do not confuse this with
172  * microuptime().  microtime() is not drift compensated.  The real uptime
173  * with compensation is nanotime() - bootime.  boottime is recalculated
174  * whenever the real time is set based on the compensated elapsed time
175  * in seconds (gd->gd_time_seconds).
176  *
177  * The gd_time_seconds and gd_cpuclock_base fields remain fairly monotonic.
178  * Slight adjustments to gd_cpuclock_base are made to phase-lock it to
179  * the real time.
180  *
181  * WARNING! time_second can backstep on time corrections. Also, unlike
182  *          time second, time_uptime is not a "real" time_t (seconds
183  *          since the Epoch) but seconds since booting.
184  */
185 struct timespec boottime;       /* boot time (realtime) for reference only */
186 time_t time_second;             /* read-only 'passive' realtime in seconds */
187 time_t time_uptime;             /* read-only 'passive' uptime in seconds */
188
189 /*
190  * basetime is used to calculate the compensated real time of day.  The
191  * basetime can be modified on a per-tick basis by the adjtime(), 
192  * ntp_adjtime(), and sysctl-based time correction APIs.
193  *
194  * Note that frequency corrections can also be made by adjusting
195  * gd_cpuclock_base.
196  *
197  * basetime is a tail-chasing FIFO, updated only by cpu #0.  The FIFO is
198  * used on both SMP and UP systems to avoid MP races between cpu's and
199  * interrupt races on UP systems.
200  */
201 #define BASETIME_ARYSIZE        16
202 #define BASETIME_ARYMASK        (BASETIME_ARYSIZE - 1)
203 static struct timespec basetime[BASETIME_ARYSIZE];
204 static volatile int basetime_index;
205
206 static int
207 sysctl_get_basetime(SYSCTL_HANDLER_ARGS)
208 {
209         struct timespec *bt;
210         int error;
211         int index;
212
213         /*
214          * Because basetime data and index may be updated by another cpu,
215          * a load fence is required to ensure that the data we read has
216          * not been speculatively read relative to a possibly updated index.
217          */
218         index = basetime_index;
219         cpu_lfence();
220         bt = &basetime[index];
221         error = SYSCTL_OUT(req, bt, sizeof(*bt));
222         return (error);
223 }
224
225 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime, CTLFLAG_RD,
226     &boottime, timespec, "System boottime");
227 SYSCTL_PROC(_kern, OID_AUTO, basetime, CTLTYPE_STRUCT|CTLFLAG_RD, 0, 0,
228     sysctl_get_basetime, "S,timespec", "System basetime");
229
230 static void hardclock(systimer_t info, int, struct intrframe *frame);
231 static void statclock(systimer_t info, int, struct intrframe *frame);
232 static void schedclock(systimer_t info, int, struct intrframe *frame);
233 static void getnanotime_nbt(struct timespec *nbt, struct timespec *tsp);
234
235 int     ticks;                  /* system master ticks at hz */
236 int     clocks_running;         /* tsleep/timeout clocks operational */
237 int64_t nsec_adj;               /* ntpd per-tick adjustment in nsec << 32 */
238 int64_t nsec_acc;               /* accumulator */
239 int     sched_ticks;            /* global schedule clock ticks */
240
241 /* NTPD time correction fields */
242 int64_t ntp_tick_permanent;     /* per-tick adjustment in nsec << 32 */
243 int64_t ntp_tick_acc;           /* accumulator for per-tick adjustment */
244 int64_t ntp_delta;              /* one-time correction in nsec */
245 int64_t ntp_big_delta = 1000000000;
246 int32_t ntp_tick_delta;         /* current adjustment rate */
247 int32_t ntp_default_tick_delta; /* adjustment rate for ntp_delta */
248 time_t  ntp_leap_second;        /* time of next leap second */
249 int     ntp_leap_insert;        /* whether to insert or remove a second */
250
251 /*
252  * Finish initializing clock frequencies and start all clocks running.
253  */
254 /* ARGSUSED*/
255 static void
256 initclocks(void *dummy)
257 {
258         /*psratio = profhz / stathz;*/
259         initclocks_pcpu();
260         clocks_running = 1;
261         if (kpmap) {
262             kpmap->tsc_freq = (uint64_t)tsc_frequency;
263             kpmap->tick_freq = hz;
264         }
265 }
266
267 /*
268  * Called on a per-cpu basis from the idle thread bootstrap on each cpu
269  * during SMP initialization.
270  *
271  * This routine is called concurrently during low-level SMP initialization
272  * and may not block in any way.  Meaning, among other things, we can't
273  * acquire any tokens.
274  */
275 void
276 initclocks_pcpu(void)
277 {
278         struct globaldata *gd = mycpu;
279
280         crit_enter();
281         if (gd->gd_cpuid == 0) {
282             gd->gd_time_seconds = 1;
283             gd->gd_cpuclock_base = sys_cputimer->count();
284         } else {
285             /* XXX */
286             gd->gd_time_seconds = globaldata_find(0)->gd_time_seconds;
287             gd->gd_cpuclock_base = globaldata_find(0)->gd_cpuclock_base;
288         }
289
290         systimer_intr_enable();
291
292         crit_exit();
293 }
294
295 /*
296  * This routine is called on just the BSP, just after SMP initialization
297  * completes to * finish initializing any clocks that might contend/block
298  * (e.g. like on a token).  We can't do this in initclocks_pcpu() because
299  * that function is called from the idle thread bootstrap for each cpu and
300  * not allowed to block at all.
301  */
302 static
303 void
304 initclocks_other(void *dummy)
305 {
306         struct globaldata *ogd = mycpu;
307         struct globaldata *gd;
308         int n;
309
310         for (n = 0; n < ncpus; ++n) {
311                 lwkt_setcpu_self(globaldata_find(n));
312                 gd = mycpu;
313
314                 /*
315                  * Use a non-queued periodic systimer to prevent multiple
316                  * ticks from building up if the sysclock jumps forward
317                  * (8254 gets reset).  The sysclock will never jump backwards.
318                  * Our time sync is based on the actual sysclock, not the
319                  * ticks count.
320                  */
321                 systimer_init_periodic_nq(&gd->gd_hardclock, hardclock,
322                                           NULL, hz);
323                 systimer_init_periodic_nq(&gd->gd_statclock, statclock,
324                                           NULL, stathz);
325                 /* XXX correct the frequency for scheduler / estcpu tests */
326                 systimer_init_periodic_nq(&gd->gd_schedclock, schedclock,
327                                           NULL, ESTCPUFREQ);
328 #ifdef IFPOLL_ENABLE
329                 ifpoll_init_pcpu(gd->gd_cpuid);
330 #endif
331         }
332         lwkt_setcpu_self(ogd);
333 }
334 SYSINIT(clocks2, SI_BOOT2_POST_SMP, SI_ORDER_ANY, initclocks_other, NULL)
335
336 /*
337  * This sets the current real time of day.  Timespecs are in seconds and
338  * nanoseconds.  We do not mess with gd_time_seconds and gd_cpuclock_base,
339  * instead we adjust basetime so basetime + gd_* results in the current
340  * time of day.  This way the gd_* fields are guaranteed to represent
341  * a monotonically increasing 'uptime' value.
342  *
343  * When set_timeofday() is called from userland, the system call forces it
344  * onto cpu #0 since only cpu #0 can update basetime_index.
345  */
346 void
347 set_timeofday(struct timespec *ts)
348 {
349         struct timespec *nbt;
350         int ni;
351
352         /*
353          * XXX SMP / non-atomic basetime updates
354          */
355         crit_enter();
356         ni = (basetime_index + 1) & BASETIME_ARYMASK;
357         nbt = &basetime[ni];
358         nanouptime(nbt);
359         nbt->tv_sec = ts->tv_sec - nbt->tv_sec;
360         nbt->tv_nsec = ts->tv_nsec - nbt->tv_nsec;
361         if (nbt->tv_nsec < 0) {
362             nbt->tv_nsec += 1000000000;
363             --nbt->tv_sec;
364         }
365
366         /*
367          * Note that basetime diverges from boottime as the clock drift is
368          * compensated for, so we cannot do away with boottime.  When setting
369          * the absolute time of day the drift is 0 (for an instant) and we
370          * can simply assign boottime to basetime.  
371          *
372          * Note that nanouptime() is based on gd_time_seconds which is drift
373          * compensated up to a point (it is guaranteed to remain monotonically
374          * increasing).  gd_time_seconds is thus our best uptime guess and
375          * suitable for use in the boottime calculation.  It is already taken
376          * into account in the basetime calculation above.
377          */
378         boottime.tv_sec = nbt->tv_sec;
379         ntp_delta = 0;
380
381         /*
382          * We now have a new basetime, make sure all other cpus have it,
383          * then update the index.
384          */
385         cpu_sfence();
386         basetime_index = ni;
387
388         crit_exit();
389 }
390         
391 /*
392  * Each cpu has its own hardclock, but we only increments ticks and softticks
393  * on cpu #0.
394  *
395  * NOTE! systimer! the MP lock might not be held here.  We can only safely
396  * manipulate objects owned by the current cpu.
397  */
398 static void
399 hardclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
400 {
401         sysclock_t cputicks;
402         struct proc *p;
403         struct globaldata *gd = mycpu;
404
405         /*
406          * Realtime updates are per-cpu.  Note that timer corrections as
407          * returned by microtime() and friends make an additional adjustment
408          * using a system-wise 'basetime', but the running time is always
409          * taken from the per-cpu globaldata area.  Since the same clock
410          * is distributing (XXX SMP) to all cpus, the per-cpu timebases
411          * stay in synch.
412          *
413          * Note that we never allow info->time (aka gd->gd_hardclock.time)
414          * to reverse index gd_cpuclock_base, but that it is possible for
415          * it to temporarily get behind in the seconds if something in the
416          * system locks interrupts for a long period of time.  Since periodic
417          * timers count events, though everything should resynch again
418          * immediately.
419          */
420         cputicks = info->time - gd->gd_cpuclock_base;
421         if (cputicks >= sys_cputimer->freq) {
422                 ++gd->gd_time_seconds;
423                 gd->gd_cpuclock_base += sys_cputimer->freq;
424                 if (gd->gd_cpuid == 0)
425                         ++time_uptime;  /* uncorrected monotonic 1-sec gran */
426         }
427
428         /*
429          * The system-wide ticks counter and NTP related timedelta/tickdelta
430          * adjustments only occur on cpu #0.  NTP adjustments are accomplished
431          * by updating basetime.
432          */
433         if (gd->gd_cpuid == 0) {
434             struct timespec *nbt;
435             struct timespec nts;
436             int leap;
437             int ni;
438
439             ++ticks;
440
441 #if 0
442             if (tco->tc_poll_pps) 
443                 tco->tc_poll_pps(tco);
444 #endif
445
446             /*
447              * Calculate the new basetime index.  We are in a critical section
448              * on cpu #0 and can safely play with basetime_index.  Start
449              * with the current basetime and then make adjustments.
450              */
451             ni = (basetime_index + 1) & BASETIME_ARYMASK;
452             nbt = &basetime[ni];
453             *nbt = basetime[basetime_index];
454
455             /*
456              * Apply adjtime corrections.  (adjtime() API)
457              *
458              * adjtime() only runs on cpu #0 so our critical section is
459              * sufficient to access these variables.
460              */
461             if (ntp_delta != 0) {
462                 nbt->tv_nsec += ntp_tick_delta;
463                 ntp_delta -= ntp_tick_delta;
464                 if ((ntp_delta > 0 && ntp_delta < ntp_tick_delta) ||
465                     (ntp_delta < 0 && ntp_delta > ntp_tick_delta)) {
466                         ntp_tick_delta = ntp_delta;
467                 }
468             }
469
470             /*
471              * Apply permanent frequency corrections.  (sysctl API)
472              */
473             if (ntp_tick_permanent != 0) {
474                 ntp_tick_acc += ntp_tick_permanent;
475                 if (ntp_tick_acc >= (1LL << 32)) {
476                     nbt->tv_nsec += ntp_tick_acc >> 32;
477                     ntp_tick_acc -= (ntp_tick_acc >> 32) << 32;
478                 } else if (ntp_tick_acc <= -(1LL << 32)) {
479                     /* Negate ntp_tick_acc to avoid shifting the sign bit. */
480                     nbt->tv_nsec -= (-ntp_tick_acc) >> 32;
481                     ntp_tick_acc += ((-ntp_tick_acc) >> 32) << 32;
482                 }
483             }
484
485             if (nbt->tv_nsec >= 1000000000) {
486                     nbt->tv_sec++;
487                     nbt->tv_nsec -= 1000000000;
488             } else if (nbt->tv_nsec < 0) {
489                     nbt->tv_sec--;
490                     nbt->tv_nsec += 1000000000;
491             }
492
493             /*
494              * Another per-tick compensation.  (for ntp_adjtime() API)
495              */
496             if (nsec_adj != 0) {
497                 nsec_acc += nsec_adj;
498                 if (nsec_acc >= 0x100000000LL) {
499                     nbt->tv_nsec += nsec_acc >> 32;
500                     nsec_acc = (nsec_acc & 0xFFFFFFFFLL);
501                 } else if (nsec_acc <= -0x100000000LL) {
502                     nbt->tv_nsec -= -nsec_acc >> 32;
503                     nsec_acc = -(-nsec_acc & 0xFFFFFFFFLL);
504                 }
505                 if (nbt->tv_nsec >= 1000000000) {
506                     nbt->tv_nsec -= 1000000000;
507                     ++nbt->tv_sec;
508                 } else if (nbt->tv_nsec < 0) {
509                     nbt->tv_nsec += 1000000000;
510                     --nbt->tv_sec;
511                 }
512             }
513
514             /************************************************************
515              *                  LEAP SECOND CORRECTION                  *
516              ************************************************************
517              *
518              * Taking into account all the corrections made above, figure
519              * out the new real time.  If the seconds field has changed
520              * then apply any pending leap-second corrections.
521              */
522             getnanotime_nbt(nbt, &nts);
523
524             if (time_second != nts.tv_sec) {
525                 /*
526                  * Apply leap second (sysctl API).  Adjust nts for changes
527                  * so we do not have to call getnanotime_nbt again.
528                  */
529                 if (ntp_leap_second) {
530                     if (ntp_leap_second == nts.tv_sec) {
531                         if (ntp_leap_insert) {
532                             nbt->tv_sec++;
533                             nts.tv_sec++;
534                         } else {
535                             nbt->tv_sec--;
536                             nts.tv_sec--;
537                         }
538                         ntp_leap_second--;
539                     }
540                 }
541
542                 /*
543                  * Apply leap second (ntp_adjtime() API), calculate a new
544                  * nsec_adj field.  ntp_update_second() returns nsec_adj
545                  * as a per-second value but we need it as a per-tick value.
546                  */
547                 leap = ntp_update_second(time_second, &nsec_adj);
548                 nsec_adj /= hz;
549                 nbt->tv_sec += leap;
550                 nts.tv_sec += leap;
551
552                 /*
553                  * Update the time_second 'approximate time' global.
554                  */
555                 time_second = nts.tv_sec;
556             }
557
558             /*
559              * Finally, our new basetime is ready to go live!
560              */
561             cpu_sfence();
562             basetime_index = ni;
563
564             /*
565              * Update kpmap on each tick.  TS updates are integrated with
566              * fences and upticks allowing userland to read the data
567              * deterministically.
568              */
569             if (kpmap) {
570                 int w;
571
572                 w = (kpmap->upticks + 1) & 1;
573                 getnanouptime(&kpmap->ts_uptime[w]);
574                 getnanotime(&kpmap->ts_realtime[w]);
575                 cpu_sfence();
576                 ++kpmap->upticks;
577                 cpu_sfence();
578             }
579         }
580
581         /*
582          * lwkt thread scheduler fair queueing
583          */
584         lwkt_schedulerclock(curthread);
585
586         /*
587          * softticks are handled for all cpus
588          */
589         hardclock_softtick(gd);
590
591         /*
592          * ITimer handling is per-tick, per-cpu.
593          *
594          * We must acquire the per-process token in order for ksignal()
595          * to be non-blocking.  For the moment this requires an AST fault,
596          * the ksignal() cannot be safely issued from this hard interrupt.
597          *
598          * XXX Even the trytoken here isn't right, and itimer operation in
599          *     a multi threaded environment is going to be weird at the
600          *     very least.
601          */
602         if ((p = curproc) != NULL && lwkt_trytoken(&p->p_token)) {
603                 crit_enter_hard();
604                 if (p->p_upmap)
605                         ++p->p_upmap->runticks;
606
607                 if (frame && CLKF_USERMODE(frame) &&
608                     timevalisset(&p->p_timer[ITIMER_VIRTUAL].it_value) &&
609                     itimerdecr(&p->p_timer[ITIMER_VIRTUAL], ustick) == 0) {
610                         p->p_flags |= P_SIGVTALRM;
611                         need_user_resched();
612                 }
613                 if (timevalisset(&p->p_timer[ITIMER_PROF].it_value) &&
614                     itimerdecr(&p->p_timer[ITIMER_PROF], ustick) == 0) {
615                         p->p_flags |= P_SIGPROF;
616                         need_user_resched();
617                 }
618                 crit_exit_hard();
619                 lwkt_reltoken(&p->p_token);
620         }
621         setdelayed();
622 }
623
624 /*
625  * The statistics clock typically runs at a 125Hz rate, and is intended
626  * to be frequency offset from the hardclock (typ 100Hz).  It is per-cpu.
627  *
628  * NOTE! systimer! the MP lock might not be held here.  We can only safely
629  * manipulate objects owned by the current cpu.
630  *
631  * The stats clock is responsible for grabbing a profiling sample.
632  * Most of the statistics are only used by user-level statistics programs.
633  * The main exceptions are p->p_uticks, p->p_sticks, p->p_iticks, and
634  * p->p_estcpu.
635  *
636  * Like the other clocks, the stat clock is called from what is effectively
637  * a fast interrupt, so the context should be the thread/process that got
638  * interrupted.
639  */
640 static void
641 statclock(systimer_t info, int in_ipi, struct intrframe *frame)
642 {
643 #ifdef GPROF
644         struct gmonparam *g;
645         int i;
646 #endif
647         thread_t td;
648         struct proc *p;
649         int bump;
650         sysclock_t cv;
651         sysclock_t scv;
652
653         /*
654          * How big was our timeslice relative to the last time?  Calculate
655          * in microseconds.
656          *
657          * NOTE: Use of microuptime() is typically MPSAFE, but usually not
658          *       during early boot.  Just use the systimer count to be nice
659          *       to e.g. qemu.  The systimer has a better chance of being
660          *       MPSAFE at early boot.
661          */
662         cv = sys_cputimer->count();
663         scv = mycpu->statint.gd_statcv;
664         if (scv == 0) {
665                 bump = 1;
666         } else {
667                 bump = (sys_cputimer->freq64_usec * (cv - scv)) >> 32;
668                 if (bump < 0)
669                         bump = 0;
670                 if (bump > 1000000)
671                         bump = 1000000;
672         }
673         mycpu->statint.gd_statcv = cv;
674
675 #if 0
676         stv = &mycpu->gd_stattv;
677         if (stv->tv_sec == 0) {
678             bump = 1;
679         } else {
680             bump = tv.tv_usec - stv->tv_usec +
681                 (tv.tv_sec - stv->tv_sec) * 1000000;
682             if (bump < 0)
683                 bump = 0;
684             if (bump > 1000000)
685                 bump = 1000000;
686         }
687         *stv = tv;
688 #endif
689
690         td = curthread;
691         p = td->td_proc;
692
693         if (frame && CLKF_USERMODE(frame)) {
694                 /*
695                  * Came from userland, handle user time and deal with
696                  * possible process.
697                  */
698                 if (p && (p->p_flags & P_PROFIL))
699                         addupc_intr(p, CLKF_PC(frame), 1);
700                 td->td_uticks += bump;
701
702                 /*
703                  * Charge the time as appropriate
704                  */
705                 if (p && p->p_nice > NZERO)
706                         cpu_time.cp_nice += bump;
707                 else
708                         cpu_time.cp_user += bump;
709         } else {
710                 int intr_nest = mycpu->gd_intr_nesting_level;
711
712                 if (in_ipi) {
713                         /*
714                          * IPI processing code will bump gd_intr_nesting_level
715                          * up by one, which breaks following CLKF_INTR testing,
716                          * so we subtract it by one here.
717                          */
718                         --intr_nest;
719                 }
720 #ifdef GPROF
721                 /*
722                  * Kernel statistics are just like addupc_intr, only easier.
723                  */
724                 g = &_gmonparam;
725                 if (g->state == GMON_PROF_ON && frame) {
726                         i = CLKF_PC(frame) - g->lowpc;
727                         if (i < g->textsize) {
728                                 i /= HISTFRACTION * sizeof(*g->kcount);
729                                 g->kcount[i]++;
730                         }
731                 }
732 #endif
733
734 #define IS_INTR_RUNNING ((frame && CLKF_INTR(intr_nest)) || CLKF_INTR_TD(td))
735
736                 /*
737                  * Came from kernel mode, so we were:
738                  * - handling an interrupt,
739                  * - doing syscall or trap work on behalf of the current
740                  *   user process, or
741                  * - spinning in the idle loop.
742                  * Whichever it is, charge the time as appropriate.
743                  * Note that we charge interrupts to the current process,
744                  * regardless of whether they are ``for'' that process,
745                  * so that we know how much of its real time was spent
746                  * in ``non-process'' (i.e., interrupt) work.
747                  *
748                  * XXX assume system if frame is NULL.  A NULL frame 
749                  * can occur if ipi processing is done from a crit_exit().
750                  */
751                 if (IS_INTR_RUNNING)
752                         td->td_iticks += bump;
753                 else
754                         td->td_sticks += bump;
755
756                 if (IS_INTR_RUNNING) {
757                         /*
758                          * If we interrupted an interrupt thread, well,
759                          * count it as interrupt time.
760                          */
761 #ifdef DEBUG_PCTRACK
762                         if (frame)
763                                 do_pctrack(frame, PCTRACK_INT);
764 #endif
765                         cpu_time.cp_intr += bump;
766                 } else {
767                         if (td == &mycpu->gd_idlethread) {
768                                 /*
769                                  * Even if the current thread is the idle
770                                  * thread it could be due to token contention
771                                  * in the LWKT scheduler.  Count such as
772                                  * system time.
773                                  */
774                                 if (mycpu->gd_reqflags & RQF_IDLECHECK_WK_MASK)
775                                         cpu_time.cp_sys += bump;
776                                 else
777                                         cpu_time.cp_idle += bump;
778                         } else {
779                                 /*
780                                  * System thread was running.
781                                  */
782 #ifdef DEBUG_PCTRACK
783                                 if (frame)
784                                         do_pctrack(frame, PCTRACK_SYS);
785 #endif
786                                 cpu_time.cp_sys += bump;
787                         }
788                 }
789
790 #undef IS_INTR_RUNNING
791         }
792 }
793
794 #ifdef DEBUG_PCTRACK
795 /*
796  * Sample the PC when in the kernel or in an interrupt.  User code can
797  * retrieve the information and generate a histogram or other output.
798  */
799
800 static void
801 do_pctrack(struct intrframe *frame, int which)
802 {
803         struct kinfo_pctrack *pctrack;
804
805         pctrack = &cputime_pctrack[mycpu->gd_cpuid][which];
806         pctrack->pc_array[pctrack->pc_index & PCTRACK_ARYMASK] = 
807                 (void *)CLKF_PC(frame);
808         ++pctrack->pc_index;
809 }
810
811 static int
812 sysctl_pctrack(SYSCTL_HANDLER_ARGS)
813 {
814         struct kinfo_pcheader head;
815         int error;
816         int cpu;
817         int ntrack;
818
819         head.pc_ntrack = PCTRACK_SIZE;
820         head.pc_arysize = PCTRACK_ARYSIZE;
821
822         if ((error = SYSCTL_OUT(req, &head, sizeof(head))) != 0)
823                 return (error);
824
825         for (cpu = 0; cpu < ncpus; ++cpu) {
826                 for (ntrack = 0; ntrack < PCTRACK_SIZE; ++ntrack) {
827                         error = SYSCTL_OUT(req, &cputime_pctrack[cpu][ntrack],
828                                            sizeof(struct kinfo_pctrack));
829                         if (error)
830                                 break;
831                 }
832                 if (error)
833                         break;
834         }
835         return (error);
836 }
837 SYSCTL_PROC(_kern, OID_AUTO, pctrack, (CTLTYPE_OPAQUE|CTLFLAG_RD), 0, 0,
838         sysctl_pctrack, "S,kinfo_pcheader", "CPU PC tracking");
839
840 #endif
841
842 /*
843  * The scheduler clock typically runs at a 50Hz rate.  NOTE! systimer,
844  * the MP lock might not be held.  We can safely manipulate parts of curproc
845  * but that's about it.
846  *
847  * Each cpu has its own scheduler clock.
848  */
849 static void
850 schedclock(systimer_t info, int in_ipi __unused, struct intrframe *frame)
851 {
852         struct lwp *lp;
853         struct rusage *ru;
854         struct vmspace *vm;
855         long rss;
856
857         if ((lp = lwkt_preempted_proc()) != NULL) {
858                 /*
859                  * Account for cpu time used and hit the scheduler.  Note
860                  * that this call MUST BE MP SAFE, and the BGL IS NOT HELD
861                  * HERE.
862                  */
863                 ++lp->lwp_cpticks;
864                 usched_schedulerclock(lp, info->periodic, info->time);
865         } else {
866                 usched_schedulerclock(NULL, info->periodic, info->time);
867         }
868         if ((lp = curthread->td_lwp) != NULL) {
869                 /*
870                  * Update resource usage integrals and maximums.
871                  */
872                 if ((ru = &lp->lwp_proc->p_ru) &&
873                     (vm = lp->lwp_proc->p_vmspace) != NULL) {
874                         ru->ru_ixrss += pgtok(vm->vm_tsize);
875                         ru->ru_idrss += pgtok(vm->vm_dsize);
876                         ru->ru_isrss += pgtok(vm->vm_ssize);
877                         if (lwkt_trytoken(&vm->vm_map.token)) {
878                                 rss = pgtok(vmspace_resident_count(vm));
879                                 if (ru->ru_maxrss < rss)
880                                         ru->ru_maxrss = rss;
881                                 lwkt_reltoken(&vm->vm_map.token);
882                         }
883                 }
884         }
885         /* Increment the global sched_ticks */
886         if (mycpu->gd_cpuid == 0)
887                 ++sched_ticks;
888 }
889
890 /*
891  * Compute number of ticks for the specified amount of time.  The 
892  * return value is intended to be used in a clock interrupt timed
893  * operation and guaranteed to meet or exceed the requested time.
894  * If the representation overflows, return INT_MAX.  The minimum return
895  * value is 1 ticks and the function will average the calculation up.
896  * If any value greater then 0 microseconds is supplied, a value
897  * of at least 2 will be returned to ensure that a near-term clock
898  * interrupt does not cause the timeout to occur (degenerately) early.
899  *
900  * Note that limit checks must take into account microseconds, which is
901  * done simply by using the smaller signed long maximum instead of
902  * the unsigned long maximum.
903  *
904  * If ints have 32 bits, then the maximum value for any timeout in
905  * 10ms ticks is 248 days.
906  */
907 int
908 tvtohz_high(struct timeval *tv)
909 {
910         int ticks;
911         long sec, usec;
912
913         sec = tv->tv_sec;
914         usec = tv->tv_usec;
915         if (usec < 0) {
916                 sec--;
917                 usec += 1000000;
918         }
919         if (sec < 0) {
920 #ifdef DIAGNOSTIC
921                 if (usec > 0) {
922                         sec++;
923                         usec -= 1000000;
924                 }
925                 kprintf("tvtohz_high: negative time difference "
926                         "%ld sec %ld usec\n",
927                         sec, usec);
928 #endif
929                 ticks = 1;
930         } else if (sec <= INT_MAX / hz) {
931                 ticks = (int)(sec * hz + 
932                             ((u_long)usec + (ustick - 1)) / ustick) + 1;
933         } else {
934                 ticks = INT_MAX;
935         }
936         return (ticks);
937 }
938
939 int
940 tstohz_high(struct timespec *ts)
941 {
942         int ticks;
943         long sec, nsec;
944
945         sec = ts->tv_sec;
946         nsec = ts->tv_nsec;
947         if (nsec < 0) {
948                 sec--;
949                 nsec += 1000000000;
950         }
951         if (sec < 0) {
952 #ifdef DIAGNOSTIC
953                 if (nsec > 0) {
954                         sec++;
955                         nsec -= 1000000000;
956                 }
957                 kprintf("tstohz_high: negative time difference "
958                         "%ld sec %ld nsec\n",
959                         sec, nsec);
960 #endif
961                 ticks = 1;
962         } else if (sec <= INT_MAX / hz) {
963                 ticks = (int)(sec * hz +
964                             ((u_long)nsec + (nstick - 1)) / nstick) + 1;
965         } else {
966                 ticks = INT_MAX;
967         }
968         return (ticks);
969 }
970
971
972 /*
973  * Compute number of ticks for the specified amount of time, erroring on
974  * the side of it being too low to ensure that sleeping the returned number
975  * of ticks will not result in a late return.
976  *
977  * The supplied timeval may not be negative and should be normalized.  A
978  * return value of 0 is possible if the timeval converts to less then
979  * 1 tick.
980  *
981  * If ints have 32 bits, then the maximum value for any timeout in
982  * 10ms ticks is 248 days.
983  */
984 int
985 tvtohz_low(struct timeval *tv)
986 {
987         int ticks;
988         long sec;
989
990         sec = tv->tv_sec;
991         if (sec <= INT_MAX / hz)
992                 ticks = (int)(sec * hz + (u_long)tv->tv_usec / ustick);
993         else
994                 ticks = INT_MAX;
995         return (ticks);
996 }
997
998 int
999 tstohz_low(struct timespec *ts)
1000 {
1001         int ticks;
1002         long sec;
1003
1004         sec = ts->tv_sec;
1005         if (sec <= INT_MAX / hz)
1006                 ticks = (int)(sec * hz + (u_long)ts->tv_nsec / nstick);
1007         else
1008                 ticks = INT_MAX;
1009         return (ticks);
1010 }
1011
1012 /*
1013  * Start profiling on a process.
1014  *
1015  * Kernel profiling passes proc0 which never exits and hence
1016  * keeps the profile clock running constantly.
1017  */
1018 void
1019 startprofclock(struct proc *p)
1020 {
1021         if ((p->p_flags & P_PROFIL) == 0) {
1022                 p->p_flags |= P_PROFIL;
1023 #if 0   /* XXX */
1024                 if (++profprocs == 1 && stathz != 0) {
1025                         crit_enter();
1026                         psdiv = psratio;
1027                         setstatclockrate(profhz);
1028                         crit_exit();
1029                 }
1030 #endif
1031         }
1032 }
1033
1034 /*
1035  * Stop profiling on a process.
1036  *
1037  * caller must hold p->p_token
1038  */
1039 void
1040 stopprofclock(struct proc *p)
1041 {
1042         if (p->p_flags & P_PROFIL) {
1043                 p->p_flags &= ~P_PROFIL;
1044 #if 0   /* XXX */
1045                 if (--profprocs == 0 && stathz != 0) {
1046                         crit_enter();
1047                         psdiv = 1;
1048                         setstatclockrate(stathz);
1049                         crit_exit();
1050                 }
1051 #endif
1052         }
1053 }
1054
1055 /*
1056  * Return information about system clocks.
1057  */
1058 static int
1059 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
1060 {
1061         struct kinfo_clockinfo clkinfo;
1062         /*
1063          * Construct clockinfo structure.
1064          */
1065         clkinfo.ci_hz = hz;
1066         clkinfo.ci_tick = ustick;
1067         clkinfo.ci_tickadj = ntp_default_tick_delta / 1000;
1068         clkinfo.ci_profhz = profhz;
1069         clkinfo.ci_stathz = stathz ? stathz : hz;
1070         return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
1071 }
1072
1073 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
1074         0, 0, sysctl_kern_clockrate, "S,clockinfo","");
1075
1076 /*
1077  * We have eight functions for looking at the clock, four for
1078  * microseconds and four for nanoseconds.  For each there is fast
1079  * but less precise version "get{nano|micro}[up]time" which will
1080  * return a time which is up to 1/HZ previous to the call, whereas
1081  * the raw version "{nano|micro}[up]time" will return a timestamp
1082  * which is as precise as possible.  The "up" variants return the
1083  * time relative to system boot, these are well suited for time
1084  * interval measurements.
1085  *
1086  * Each cpu independently maintains the current time of day, so all
1087  * we need to do to protect ourselves from changes is to do a loop
1088  * check on the seconds field changing out from under us.
1089  *
1090  * The system timer maintains a 32 bit count and due to various issues
1091  * it is possible for the calculated delta to occasionally exceed
1092  * sys_cputimer->freq.  If this occurs the sys_cputimer->freq64_nsec
1093  * multiplication can easily overflow, so we deal with the case.  For
1094  * uniformity we deal with the case in the usec case too.
1095  *
1096  * All the [get][micro,nano][time,uptime]() routines are MPSAFE.
1097  */
1098 void
1099 getmicrouptime(struct timeval *tvp)
1100 {
1101         struct globaldata *gd = mycpu;
1102         sysclock_t delta;
1103
1104         do {
1105                 tvp->tv_sec = gd->gd_time_seconds;
1106                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1107         } while (tvp->tv_sec != gd->gd_time_seconds);
1108
1109         if (delta >= sys_cputimer->freq) {
1110                 tvp->tv_sec += delta / sys_cputimer->freq;
1111                 delta %= sys_cputimer->freq;
1112         }
1113         tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1114         if (tvp->tv_usec >= 1000000) {
1115                 tvp->tv_usec -= 1000000;
1116                 ++tvp->tv_sec;
1117         }
1118 }
1119
1120 void
1121 getnanouptime(struct timespec *tsp)
1122 {
1123         struct globaldata *gd = mycpu;
1124         sysclock_t delta;
1125
1126         do {
1127                 tsp->tv_sec = gd->gd_time_seconds;
1128                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1129         } while (tsp->tv_sec != gd->gd_time_seconds);
1130
1131         if (delta >= sys_cputimer->freq) {
1132                 tsp->tv_sec += delta / sys_cputimer->freq;
1133                 delta %= sys_cputimer->freq;
1134         }
1135         tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1136 }
1137
1138 void
1139 microuptime(struct timeval *tvp)
1140 {
1141         struct globaldata *gd = mycpu;
1142         sysclock_t delta;
1143
1144         do {
1145                 tvp->tv_sec = gd->gd_time_seconds;
1146                 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1147         } while (tvp->tv_sec != gd->gd_time_seconds);
1148
1149         if (delta >= sys_cputimer->freq) {
1150                 tvp->tv_sec += delta / sys_cputimer->freq;
1151                 delta %= sys_cputimer->freq;
1152         }
1153         tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1154 }
1155
1156 void
1157 nanouptime(struct timespec *tsp)
1158 {
1159         struct globaldata *gd = mycpu;
1160         sysclock_t delta;
1161
1162         do {
1163                 tsp->tv_sec = gd->gd_time_seconds;
1164                 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1165         } while (tsp->tv_sec != gd->gd_time_seconds);
1166
1167         if (delta >= sys_cputimer->freq) {
1168                 tsp->tv_sec += delta / sys_cputimer->freq;
1169                 delta %= sys_cputimer->freq;
1170         }
1171         tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1172 }
1173
1174 /*
1175  * realtime routines
1176  */
1177 void
1178 getmicrotime(struct timeval *tvp)
1179 {
1180         struct globaldata *gd = mycpu;
1181         struct timespec *bt;
1182         sysclock_t delta;
1183
1184         do {
1185                 tvp->tv_sec = gd->gd_time_seconds;
1186                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1187         } while (tvp->tv_sec != gd->gd_time_seconds);
1188
1189         if (delta >= sys_cputimer->freq) {
1190                 tvp->tv_sec += delta / sys_cputimer->freq;
1191                 delta %= sys_cputimer->freq;
1192         }
1193         tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1194
1195         bt = &basetime[basetime_index];
1196         tvp->tv_sec += bt->tv_sec;
1197         tvp->tv_usec += bt->tv_nsec / 1000;
1198         while (tvp->tv_usec >= 1000000) {
1199                 tvp->tv_usec -= 1000000;
1200                 ++tvp->tv_sec;
1201         }
1202 }
1203
1204 void
1205 getnanotime(struct timespec *tsp)
1206 {
1207         struct globaldata *gd = mycpu;
1208         struct timespec *bt;
1209         sysclock_t delta;
1210
1211         do {
1212                 tsp->tv_sec = gd->gd_time_seconds;
1213                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1214         } while (tsp->tv_sec != gd->gd_time_seconds);
1215
1216         if (delta >= sys_cputimer->freq) {
1217                 tsp->tv_sec += delta / sys_cputimer->freq;
1218                 delta %= sys_cputimer->freq;
1219         }
1220         tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1221
1222         bt = &basetime[basetime_index];
1223         tsp->tv_sec += bt->tv_sec;
1224         tsp->tv_nsec += bt->tv_nsec;
1225         while (tsp->tv_nsec >= 1000000000) {
1226                 tsp->tv_nsec -= 1000000000;
1227                 ++tsp->tv_sec;
1228         }
1229 }
1230
1231 static void
1232 getnanotime_nbt(struct timespec *nbt, struct timespec *tsp)
1233 {
1234         struct globaldata *gd = mycpu;
1235         sysclock_t delta;
1236
1237         do {
1238                 tsp->tv_sec = gd->gd_time_seconds;
1239                 delta = gd->gd_hardclock.time - gd->gd_cpuclock_base;
1240         } while (tsp->tv_sec != gd->gd_time_seconds);
1241
1242         if (delta >= sys_cputimer->freq) {
1243                 tsp->tv_sec += delta / sys_cputimer->freq;
1244                 delta %= sys_cputimer->freq;
1245         }
1246         tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1247
1248         tsp->tv_sec += nbt->tv_sec;
1249         tsp->tv_nsec += nbt->tv_nsec;
1250         while (tsp->tv_nsec >= 1000000000) {
1251                 tsp->tv_nsec -= 1000000000;
1252                 ++tsp->tv_sec;
1253         }
1254 }
1255
1256
1257 void
1258 microtime(struct timeval *tvp)
1259 {
1260         struct globaldata *gd = mycpu;
1261         struct timespec *bt;
1262         sysclock_t delta;
1263
1264         do {
1265                 tvp->tv_sec = gd->gd_time_seconds;
1266                 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1267         } while (tvp->tv_sec != gd->gd_time_seconds);
1268
1269         if (delta >= sys_cputimer->freq) {
1270                 tvp->tv_sec += delta / sys_cputimer->freq;
1271                 delta %= sys_cputimer->freq;
1272         }
1273         tvp->tv_usec = (sys_cputimer->freq64_usec * delta) >> 32;
1274
1275         bt = &basetime[basetime_index];
1276         tvp->tv_sec += bt->tv_sec;
1277         tvp->tv_usec += bt->tv_nsec / 1000;
1278         while (tvp->tv_usec >= 1000000) {
1279                 tvp->tv_usec -= 1000000;
1280                 ++tvp->tv_sec;
1281         }
1282 }
1283
1284 void
1285 nanotime(struct timespec *tsp)
1286 {
1287         struct globaldata *gd = mycpu;
1288         struct timespec *bt;
1289         sysclock_t delta;
1290
1291         do {
1292                 tsp->tv_sec = gd->gd_time_seconds;
1293                 delta = sys_cputimer->count() - gd->gd_cpuclock_base;
1294         } while (tsp->tv_sec != gd->gd_time_seconds);
1295
1296         if (delta >= sys_cputimer->freq) {
1297                 tsp->tv_sec += delta / sys_cputimer->freq;
1298                 delta %= sys_cputimer->freq;
1299         }
1300         tsp->tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1301
1302         bt = &basetime[basetime_index];
1303         tsp->tv_sec += bt->tv_sec;
1304         tsp->tv_nsec += bt->tv_nsec;
1305         while (tsp->tv_nsec >= 1000000000) {
1306                 tsp->tv_nsec -= 1000000000;
1307                 ++tsp->tv_sec;
1308         }
1309 }
1310
1311 /*
1312  * note: this is not exactly synchronized with real time.  To do that we
1313  * would have to do what microtime does and check for a nanoseconds overflow.
1314  */
1315 time_t
1316 get_approximate_time_t(void)
1317 {
1318         struct globaldata *gd = mycpu;
1319         struct timespec *bt;
1320
1321         bt = &basetime[basetime_index];
1322         return(gd->gd_time_seconds + bt->tv_sec);
1323 }
1324
1325 int
1326 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1327 {
1328         pps_params_t *app;
1329         struct pps_fetch_args *fapi;
1330 #ifdef PPS_SYNC
1331         struct pps_kcbind_args *kapi;
1332 #endif
1333
1334         switch (cmd) {
1335         case PPS_IOC_CREATE:
1336                 return (0);
1337         case PPS_IOC_DESTROY:
1338                 return (0);
1339         case PPS_IOC_SETPARAMS:
1340                 app = (pps_params_t *)data;
1341                 if (app->mode & ~pps->ppscap)
1342                         return (EINVAL);
1343                 pps->ppsparam = *app;         
1344                 return (0);
1345         case PPS_IOC_GETPARAMS:
1346                 app = (pps_params_t *)data;
1347                 *app = pps->ppsparam;
1348                 app->api_version = PPS_API_VERS_1;
1349                 return (0);
1350         case PPS_IOC_GETCAP:
1351                 *(int*)data = pps->ppscap;
1352                 return (0);
1353         case PPS_IOC_FETCH:
1354                 fapi = (struct pps_fetch_args *)data;
1355                 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1356                         return (EINVAL);
1357                 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec)
1358                         return (EOPNOTSUPP);
1359                 pps->ppsinfo.current_mode = pps->ppsparam.mode;         
1360                 fapi->pps_info_buf = pps->ppsinfo;
1361                 return (0);
1362         case PPS_IOC_KCBIND:
1363 #ifdef PPS_SYNC
1364                 kapi = (struct pps_kcbind_args *)data;
1365                 /* XXX Only root should be able to do this */
1366                 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1367                         return (EINVAL);
1368                 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1369                         return (EINVAL);
1370                 if (kapi->edge & ~pps->ppscap)
1371                         return (EINVAL);
1372                 pps->kcmode = kapi->edge;
1373                 return (0);
1374 #else
1375                 return (EOPNOTSUPP);
1376 #endif
1377         default:
1378                 return (ENOTTY);
1379         }
1380 }
1381
1382 void
1383 pps_init(struct pps_state *pps)
1384 {
1385         pps->ppscap |= PPS_TSFMT_TSPEC;
1386         if (pps->ppscap & PPS_CAPTUREASSERT)
1387                 pps->ppscap |= PPS_OFFSETASSERT;
1388         if (pps->ppscap & PPS_CAPTURECLEAR)
1389                 pps->ppscap |= PPS_OFFSETCLEAR;
1390 }
1391
1392 void
1393 pps_event(struct pps_state *pps, sysclock_t count, int event)
1394 {
1395         struct globaldata *gd;
1396         struct timespec *tsp;
1397         struct timespec *osp;
1398         struct timespec *bt;
1399         struct timespec ts;
1400         sysclock_t *pcount;
1401 #ifdef PPS_SYNC
1402         sysclock_t tcount;
1403 #endif
1404         sysclock_t delta;
1405         pps_seq_t *pseq;
1406         int foff;
1407 #ifdef PPS_SYNC
1408         int fhard;
1409 #else
1410         int fhard __unused;
1411 #endif
1412
1413         gd = mycpu;
1414
1415         /* Things would be easier with arrays... */
1416         if (event == PPS_CAPTUREASSERT) {
1417                 tsp = &pps->ppsinfo.assert_timestamp;
1418                 osp = &pps->ppsparam.assert_offset;
1419                 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1420                 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1421                 pcount = &pps->ppscount[0];
1422                 pseq = &pps->ppsinfo.assert_sequence;
1423         } else {
1424                 tsp = &pps->ppsinfo.clear_timestamp;
1425                 osp = &pps->ppsparam.clear_offset;
1426                 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1427                 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1428                 pcount = &pps->ppscount[1];
1429                 pseq = &pps->ppsinfo.clear_sequence;
1430         }
1431
1432         /* Nothing really happened */
1433         if (*pcount == count)
1434                 return;
1435
1436         *pcount = count;
1437
1438         do {
1439                 ts.tv_sec = gd->gd_time_seconds;
1440                 delta = count - gd->gd_cpuclock_base;
1441         } while (ts.tv_sec != gd->gd_time_seconds);
1442
1443         if (delta >= sys_cputimer->freq) {
1444                 ts.tv_sec += delta / sys_cputimer->freq;
1445                 delta %= sys_cputimer->freq;
1446         }
1447         ts.tv_nsec = (sys_cputimer->freq64_nsec * delta) >> 32;
1448         bt = &basetime[basetime_index];
1449         ts.tv_sec += bt->tv_sec;
1450         ts.tv_nsec += bt->tv_nsec;
1451         while (ts.tv_nsec >= 1000000000) {
1452                 ts.tv_nsec -= 1000000000;
1453                 ++ts.tv_sec;
1454         }
1455
1456         (*pseq)++;
1457         *tsp = ts;
1458
1459         if (foff) {
1460                 timespecadd(tsp, osp);
1461                 if (tsp->tv_nsec < 0) {
1462                         tsp->tv_nsec += 1000000000;
1463                         tsp->tv_sec -= 1;
1464                 }
1465         }
1466 #ifdef PPS_SYNC
1467         if (fhard) {
1468                 /* magic, at its best... */
1469                 tcount = count - pps->ppscount[2];
1470                 pps->ppscount[2] = count;
1471                 if (tcount >= sys_cputimer->freq) {
1472                         delta = (1000000000 * (tcount / sys_cputimer->freq) +
1473                                  sys_cputimer->freq64_nsec * 
1474                                  (tcount % sys_cputimer->freq)) >> 32;
1475                 } else {
1476                         delta = (sys_cputimer->freq64_nsec * tcount) >> 32;
1477                 }
1478                 hardpps(tsp, delta);
1479         }
1480 #endif
1481 }
1482
1483 /*
1484  * Return the tsc target value for a delay of (ns).
1485  *
1486  * Returns -1 if the TSC is not supported.
1487  */
1488 int64_t
1489 tsc_get_target(int ns)
1490 {
1491 #if defined(_RDTSC_SUPPORTED_)
1492         if (cpu_feature & CPUID_TSC) {
1493                 return (rdtsc() + tsc_frequency * ns / (int64_t)1000000000);
1494         }
1495 #endif
1496         return(-1);
1497 }
1498
1499 /*
1500  * Compare the tsc against the passed target
1501  *
1502  * Returns +1 if the target has been reached
1503  * Returns  0 if the target has not yet been reached
1504  * Returns -1 if the TSC is not supported.
1505  *
1506  * Typical use:         while (tsc_test_target(target) == 0) { ...poll... }
1507  */
1508 int
1509 tsc_test_target(int64_t target)
1510 {
1511 #if defined(_RDTSC_SUPPORTED_)
1512         if (cpu_feature & CPUID_TSC) {
1513                 if ((int64_t)(target - rdtsc()) <= 0)
1514                         return(1);
1515                 return(0);
1516         }
1517 #endif
1518         return(-1);
1519 }
1520
1521 /*
1522  * Delay the specified number of nanoseconds using the tsc.  This function
1523  * returns immediately if the TSC is not supported.  At least one cpu_pause()
1524  * will be issued.
1525  */
1526 void
1527 tsc_delay(int ns)
1528 {
1529         int64_t clk;
1530
1531         clk = tsc_get_target(ns);
1532         cpu_pause();
1533         while (tsc_test_target(clk) == 0)
1534                 cpu_pause();
1535 }