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