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