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