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