kern_clock.c revision 1.74.2.4 1 /* $NetBSD: kern_clock.c,v 1.74.2.4 2001/11/14 19:16:33 nathanw Exp $ */
2
3 /*-
4 * Copyright (c) 2000 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*-
41 * Copyright (c) 1982, 1986, 1991, 1993
42 * The Regents of the University of California. All rights reserved.
43 * (c) UNIX System Laboratories, Inc.
44 * All or some portions of this file are derived from material licensed
45 * to the University of California by American Telephone and Telegraph
46 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
47 * the permission of UNIX System Laboratories, Inc.
48 *
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions
51 * are met:
52 * 1. Redistributions of source code must retain the above copyright
53 * notice, this list of conditions and the following disclaimer.
54 * 2. Redistributions in binary form must reproduce the above copyright
55 * notice, this list of conditions and the following disclaimer in the
56 * documentation and/or other materials provided with the distribution.
57 * 3. All advertising materials mentioning features or use of this software
58 * must display the following acknowledgement:
59 * This product includes software developed by the University of
60 * California, Berkeley and its contributors.
61 * 4. Neither the name of the University nor the names of its contributors
62 * may be used to endorse or promote products derived from this software
63 * without specific prior written permission.
64 *
65 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75 * SUCH DAMAGE.
76 *
77 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
78 */
79
80 #include <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.74.2.4 2001/11/14 19:16:33 nathanw Exp $");
82
83 #include "opt_callout.h"
84 #include "opt_ntp.h"
85
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/dkstat.h>
89 #include <sys/callout.h>
90 #include <sys/kernel.h>
91 #include <sys/lwp.h>
92 #include <sys/proc.h>
93 #include <sys/resourcevar.h>
94 #include <sys/signalvar.h>
95 #include <uvm/uvm_extern.h>
96 #include <sys/sysctl.h>
97 #include <sys/timex.h>
98 #include <sys/sched.h>
99 #ifdef CALLWHEEL_STATS
100 #include <sys/device.h>
101 #endif
102
103 #include <machine/cpu.h>
104 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
105 #include <machine/intr.h>
106 #endif
107
108 #ifdef GPROF
109 #include <sys/gmon.h>
110 #endif
111
112 /*
113 * Clock handling routines.
114 *
115 * This code is written to operate with two timers that run independently of
116 * each other. The main clock, running hz times per second, is used to keep
117 * track of real time. The second timer handles kernel and user profiling,
118 * and does resource use estimation. If the second timer is programmable,
119 * it is randomized to avoid aliasing between the two clocks. For example,
120 * the randomization prevents an adversary from always giving up the cpu
121 * just before its quantum expires. Otherwise, it would never accumulate
122 * cpu ticks. The mean frequency of the second timer is stathz.
123 *
124 * If no second timer exists, stathz will be zero; in this case we drive
125 * profiling and statistics off the main clock. This WILL NOT be accurate;
126 * do not do it unless absolutely necessary.
127 *
128 * The statistics clock may (or may not) be run at a higher rate while
129 * profiling. This profile clock runs at profhz. We require that profhz
130 * be an integral multiple of stathz.
131 *
132 * If the statistics clock is running fast, it must be divided by the ratio
133 * profhz/stathz for statistics. (For profiling, every tick counts.)
134 */
135
136 #ifdef NTP /* NTP phase-locked loop in kernel */
137 /*
138 * Phase/frequency-lock loop (PLL/FLL) definitions
139 *
140 * The following variables are read and set by the ntp_adjtime() system
141 * call.
142 *
143 * time_state shows the state of the system clock, with values defined
144 * in the timex.h header file.
145 *
146 * time_status shows the status of the system clock, with bits defined
147 * in the timex.h header file.
148 *
149 * time_offset is used by the PLL/FLL to adjust the system time in small
150 * increments.
151 *
152 * time_constant determines the bandwidth or "stiffness" of the PLL.
153 *
154 * time_tolerance determines maximum frequency error or tolerance of the
155 * CPU clock oscillator and is a property of the architecture; however,
156 * in principle it could change as result of the presence of external
157 * discipline signals, for instance.
158 *
159 * time_precision is usually equal to the kernel tick variable; however,
160 * in cases where a precision clock counter or external clock is
161 * available, the resolution can be much less than this and depend on
162 * whether the external clock is working or not.
163 *
164 * time_maxerror is initialized by a ntp_adjtime() call and increased by
165 * the kernel once each second to reflect the maximum error bound
166 * growth.
167 *
168 * time_esterror is set and read by the ntp_adjtime() call, but
169 * otherwise not used by the kernel.
170 */
171 int time_state = TIME_OK; /* clock state */
172 int time_status = STA_UNSYNC; /* clock status bits */
173 long time_offset = 0; /* time offset (us) */
174 long time_constant = 0; /* pll time constant */
175 long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */
176 long time_precision = 1; /* clock precision (us) */
177 long time_maxerror = MAXPHASE; /* maximum error (us) */
178 long time_esterror = MAXPHASE; /* estimated error (us) */
179
180 /*
181 * The following variables establish the state of the PLL/FLL and the
182 * residual time and frequency offset of the local clock. The scale
183 * factors are defined in the timex.h header file.
184 *
185 * time_phase and time_freq are the phase increment and the frequency
186 * increment, respectively, of the kernel time variable.
187 *
188 * time_freq is set via ntp_adjtime() from a value stored in a file when
189 * the synchronization daemon is first started. Its value is retrieved
190 * via ntp_adjtime() and written to the file about once per hour by the
191 * daemon.
192 *
193 * time_adj is the adjustment added to the value of tick at each timer
194 * interrupt and is recomputed from time_phase and time_freq at each
195 * seconds rollover.
196 *
197 * time_reftime is the second's portion of the system time at the last
198 * call to ntp_adjtime(). It is used to adjust the time_freq variable
199 * and to increase the time_maxerror as the time since last update
200 * increases.
201 */
202 long time_phase = 0; /* phase offset (scaled us) */
203 long time_freq = 0; /* frequency offset (scaled ppm) */
204 long time_adj = 0; /* tick adjust (scaled 1 / hz) */
205 long time_reftime = 0; /* time at last adjustment (s) */
206
207 #ifdef PPS_SYNC
208 /*
209 * The following variables are used only if the kernel PPS discipline
210 * code is configured (PPS_SYNC). The scale factors are defined in the
211 * timex.h header file.
212 *
213 * pps_time contains the time at each calibration interval, as read by
214 * microtime(). pps_count counts the seconds of the calibration
215 * interval, the duration of which is nominally pps_shift in powers of
216 * two.
217 *
218 * pps_offset is the time offset produced by the time median filter
219 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
220 * this filter.
221 *
222 * pps_freq is the frequency offset produced by the frequency median
223 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
224 * by this filter.
225 *
226 * pps_usec is latched from a high resolution counter or external clock
227 * at pps_time. Here we want the hardware counter contents only, not the
228 * contents plus the time_tv.usec as usual.
229 *
230 * pps_valid counts the number of seconds since the last PPS update. It
231 * is used as a watchdog timer to disable the PPS discipline should the
232 * PPS signal be lost.
233 *
234 * pps_glitch counts the number of seconds since the beginning of an
235 * offset burst more than tick/2 from current nominal offset. It is used
236 * mainly to suppress error bursts due to priority conflicts between the
237 * PPS interrupt and timer interrupt.
238 *
239 * pps_intcnt counts the calibration intervals for use in the interval-
240 * adaptation algorithm. It's just too complicated for words.
241 */
242 struct timeval pps_time; /* kernel time at last interval */
243 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
244 long pps_offset = 0; /* pps time offset (us) */
245 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
246 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
247 long pps_freq = 0; /* frequency offset (scaled ppm) */
248 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
249 long pps_usec = 0; /* microsec counter at last interval */
250 long pps_valid = PPS_VALID; /* pps signal watchdog counter */
251 int pps_glitch = 0; /* pps signal glitch counter */
252 int pps_count = 0; /* calibration interval counter (s) */
253 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
254 int pps_intcnt = 0; /* intervals at current duration */
255
256 /*
257 * PPS signal quality monitors
258 *
259 * pps_jitcnt counts the seconds that have been discarded because the
260 * jitter measured by the time median filter exceeds the limit MAXTIME
261 * (100 us).
262 *
263 * pps_calcnt counts the frequency calibration intervals, which are
264 * variable from 4 s to 256 s.
265 *
266 * pps_errcnt counts the calibration intervals which have been discarded
267 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
268 * calibration interval jitter exceeds two ticks.
269 *
270 * pps_stbcnt counts the calibration intervals that have been discarded
271 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
272 */
273 long pps_jitcnt = 0; /* jitter limit exceeded */
274 long pps_calcnt = 0; /* calibration intervals */
275 long pps_errcnt = 0; /* calibration errors */
276 long pps_stbcnt = 0; /* stability limit exceeded */
277 #endif /* PPS_SYNC */
278
279 #ifdef EXT_CLOCK
280 /*
281 * External clock definitions
282 *
283 * The following definitions and declarations are used only if an
284 * external clock is configured on the system.
285 */
286 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */
287
288 /*
289 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
290 * interrupt and decremented once each second.
291 */
292 int clock_count = 0; /* CPU clock counter */
293
294 #ifdef HIGHBALL
295 /*
296 * The clock_offset and clock_cpu variables are used by the HIGHBALL
297 * interface. The clock_offset variable defines the offset between
298 * system time and the HIGBALL counters. The clock_cpu variable contains
299 * the offset between the system clock and the HIGHBALL clock for use in
300 * disciplining the kernel time variable.
301 */
302 extern struct timeval clock_offset; /* Highball clock offset */
303 long clock_cpu = 0; /* CPU clock adjust */
304 #endif /* HIGHBALL */
305 #endif /* EXT_CLOCK */
306 #endif /* NTP */
307
308
309 /*
310 * Bump a timeval by a small number of usec's.
311 */
312 #define BUMPTIME(t, usec) { \
313 volatile struct timeval *tp = (t); \
314 long us; \
315 \
316 tp->tv_usec = us = tp->tv_usec + (usec); \
317 if (us >= 1000000) { \
318 tp->tv_usec = us - 1000000; \
319 tp->tv_sec++; \
320 } \
321 }
322
323 int stathz;
324 int profhz;
325 int schedhz;
326 int profprocs;
327 int softclock_running; /* 1 => softclock() is running */
328 static int psdiv; /* prof => stat divider */
329 int psratio; /* ratio: prof / stat */
330 int tickfix, tickfixinterval; /* used if tick not really integral */
331 #ifndef NTP
332 static int tickfixcnt; /* accumulated fractional error */
333 #else
334 int fixtick; /* used by NTP for same */
335 int shifthz;
336 #endif
337
338 /*
339 * We might want ldd to load the both words from time at once.
340 * To succeed we need to be quadword aligned.
341 * The sparc already does that, and that it has worked so far is a fluke.
342 */
343 volatile struct timeval time __attribute__((__aligned__(__alignof__(quad_t))));
344 volatile struct timeval mono_time;
345
346 /*
347 * The callout mechanism is based on the work of Adam M. Costello and
348 * George Varghese, published in a technical report entitled "Redesigning
349 * the BSD Callout and Timer Facilities", and Justin Gibbs's subsequent
350 * integration into FreeBSD, modified for NetBSD by Jason R. Thorpe.
351 *
352 * The original work on the data structures used in this implementation
353 * was published by G. Varghese and A. Lauck in the paper "Hashed and
354 * Hierarchical Timing Wheels: Data Structures for the Efficient
355 * Implementation of a Timer Facility" in the Proceedings of the 11th
356 * ACM Annual Symposium on Operating System Principles, Austin, Texas,
357 * November 1987.
358 */
359 struct callout_queue *callwheel;
360 int callwheelsize, callwheelbits, callwheelmask;
361
362 static struct callout *nextsoftcheck; /* next callout to be checked */
363
364 #ifdef CALLWHEEL_STATS
365 int *callwheel_sizes; /* per-bucket length count */
366 struct evcnt callwheel_collisions; /* number of hash collisions */
367 struct evcnt callwheel_maxlength; /* length of the longest hash chain */
368 struct evcnt callwheel_count; /* # callouts currently */
369 struct evcnt callwheel_established; /* # callouts established */
370 struct evcnt callwheel_fired; /* # callouts that fired */
371 struct evcnt callwheel_disestablished; /* # callouts disestablished */
372 struct evcnt callwheel_changed; /* # callouts changed */
373 struct evcnt callwheel_softclocks; /* # times softclock() called */
374 struct evcnt callwheel_softchecks; /* # checks per softclock() */
375 struct evcnt callwheel_softempty; /* # empty buckets seen */
376 struct evcnt callwheel_hintworked; /* # times hint saved scan */
377 #endif /* CALLWHEEL_STATS */
378
379 /*
380 * This value indicates the number of consecutive callouts that
381 * will be checked before we allow interrupts to have a chance
382 * again.
383 */
384 #ifndef MAX_SOFTCLOCK_STEPS
385 #define MAX_SOFTCLOCK_STEPS 100
386 #endif
387
388 struct simplelock callwheel_slock;
389
390 #define CALLWHEEL_LOCK(s) \
391 do { \
392 s = splclock(); \
393 simple_lock(&callwheel_slock); \
394 } while (0)
395
396 #define CALLWHEEL_UNLOCK(s) \
397 do { \
398 simple_unlock(&callwheel_slock); \
399 splx(s); \
400 } while (0)
401
402 static void callout_stop_locked(struct callout *);
403
404 /*
405 * These are both protected by callwheel_lock.
406 * XXX SHOULD BE STATIC!!
407 */
408 u_int64_t hardclock_ticks, softclock_ticks;
409
410 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
411 void softclock(void *);
412 void *softclock_si;
413 #endif
414
415 /*
416 * Initialize clock frequencies and start both clocks running.
417 */
418 void
419 initclocks(void)
420 {
421 int i;
422
423 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
424 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
425 if (softclock_si == NULL)
426 panic("initclocks: unable to register softclock intr");
427 #endif
428
429 /*
430 * Set divisors to 1 (normal case) and let the machine-specific
431 * code do its bit.
432 */
433 psdiv = 1;
434 cpu_initclocks();
435
436 /*
437 * Compute profhz/stathz/rrticks, and fix profhz if needed.
438 */
439 i = stathz ? stathz : hz;
440 if (profhz == 0)
441 profhz = i;
442 psratio = profhz / i;
443 rrticks = hz / 10;
444
445 #ifdef NTP
446 switch (hz) {
447 case 1:
448 shifthz = SHIFT_SCALE - 0;
449 break;
450 case 2:
451 shifthz = SHIFT_SCALE - 1;
452 break;
453 case 4:
454 shifthz = SHIFT_SCALE - 2;
455 break;
456 case 8:
457 shifthz = SHIFT_SCALE - 3;
458 break;
459 case 16:
460 shifthz = SHIFT_SCALE - 4;
461 break;
462 case 32:
463 shifthz = SHIFT_SCALE - 5;
464 break;
465 case 60:
466 case 64:
467 shifthz = SHIFT_SCALE - 6;
468 break;
469 case 96:
470 case 100:
471 case 128:
472 shifthz = SHIFT_SCALE - 7;
473 break;
474 case 256:
475 shifthz = SHIFT_SCALE - 8;
476 break;
477 case 512:
478 shifthz = SHIFT_SCALE - 9;
479 break;
480 case 1000:
481 case 1024:
482 shifthz = SHIFT_SCALE - 10;
483 break;
484 case 1200:
485 case 2048:
486 shifthz = SHIFT_SCALE - 11;
487 break;
488 case 4096:
489 shifthz = SHIFT_SCALE - 12;
490 break;
491 case 8192:
492 shifthz = SHIFT_SCALE - 13;
493 break;
494 case 16384:
495 shifthz = SHIFT_SCALE - 14;
496 break;
497 case 32768:
498 shifthz = SHIFT_SCALE - 15;
499 break;
500 case 65536:
501 shifthz = SHIFT_SCALE - 16;
502 break;
503 default:
504 panic("weird hz");
505 }
506 if (fixtick == 0) {
507 /*
508 * Give MD code a chance to set this to a better
509 * value; but, if it doesn't, we should.
510 */
511 fixtick = (1000000 - (hz*tick));
512 }
513 #endif
514 }
515
516 /*
517 * The real-time timer, interrupting hz times per second.
518 */
519 void
520 hardclock(struct clockframe *frame)
521 {
522 struct lwp *l;
523 struct proc *p;
524 int delta;
525 extern int tickdelta;
526 extern long timedelta;
527 struct cpu_info *ci = curcpu();
528 #ifdef NTP
529 int time_update;
530 int ltemp;
531 #endif
532
533 l = curproc;
534 if (l) {
535 struct pstats *pstats;
536 p = l->l_proc;
537 /*
538 * Run current process's virtual and profile time, as needed.
539 */
540 pstats = p->p_stats;
541 if (CLKF_USERMODE(frame) &&
542 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
543 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
544 psignal(p, SIGVTALRM);
545 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
546 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
547 psignal(p, SIGPROF);
548 }
549
550 /*
551 * If no separate statistics clock is available, run it from here.
552 */
553 if (stathz == 0)
554 statclock(frame);
555 if ((--ci->ci_schedstate.spc_rrticks) <= 0)
556 roundrobin(ci);
557
558 #if defined(MULTIPROCESSOR)
559 /*
560 * If we are not the primary CPU, we're not allowed to do
561 * any more work.
562 */
563 if (CPU_IS_PRIMARY(ci) == 0)
564 return;
565 #endif
566
567 /*
568 * Increment the time-of-day. The increment is normally just
569 * ``tick''. If the machine is one which has a clock frequency
570 * such that ``hz'' would not divide the second evenly into
571 * milliseconds, a periodic adjustment must be applied. Finally,
572 * if we are still adjusting the time (see adjtime()),
573 * ``tickdelta'' may also be added in.
574 */
575 delta = tick;
576
577 #ifndef NTP
578 if (tickfix) {
579 tickfixcnt += tickfix;
580 if (tickfixcnt >= tickfixinterval) {
581 delta++;
582 tickfixcnt -= tickfixinterval;
583 }
584 }
585 #endif /* !NTP */
586 /* Imprecise 4bsd adjtime() handling */
587 if (timedelta != 0) {
588 delta += tickdelta;
589 timedelta -= tickdelta;
590 }
591
592 #ifdef notyet
593 microset();
594 #endif
595
596 #ifndef NTP
597 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
598 #endif
599 BUMPTIME(&mono_time, delta);
600
601 #ifdef NTP
602 time_update = delta;
603
604 /*
605 * Compute the phase adjustment. If the low-order bits
606 * (time_phase) of the update overflow, bump the high-order bits
607 * (time_update).
608 */
609 time_phase += time_adj;
610 if (time_phase <= -FINEUSEC) {
611 ltemp = -time_phase >> SHIFT_SCALE;
612 time_phase += ltemp << SHIFT_SCALE;
613 time_update -= ltemp;
614 } else if (time_phase >= FINEUSEC) {
615 ltemp = time_phase >> SHIFT_SCALE;
616 time_phase -= ltemp << SHIFT_SCALE;
617 time_update += ltemp;
618 }
619
620 #ifdef HIGHBALL
621 /*
622 * If the HIGHBALL board is installed, we need to adjust the
623 * external clock offset in order to close the hardware feedback
624 * loop. This will adjust the external clock phase and frequency
625 * in small amounts. The additional phase noise and frequency
626 * wander this causes should be minimal. We also need to
627 * discipline the kernel time variable, since the PLL is used to
628 * discipline the external clock. If the Highball board is not
629 * present, we discipline kernel time with the PLL as usual. We
630 * assume that the external clock phase adjustment (time_update)
631 * and kernel phase adjustment (clock_cpu) are less than the
632 * value of tick.
633 */
634 clock_offset.tv_usec += time_update;
635 if (clock_offset.tv_usec >= 1000000) {
636 clock_offset.tv_sec++;
637 clock_offset.tv_usec -= 1000000;
638 }
639 if (clock_offset.tv_usec < 0) {
640 clock_offset.tv_sec--;
641 clock_offset.tv_usec += 1000000;
642 }
643 time.tv_usec += clock_cpu;
644 clock_cpu = 0;
645 #else
646 time.tv_usec += time_update;
647 #endif /* HIGHBALL */
648
649 /*
650 * On rollover of the second the phase adjustment to be used for
651 * the next second is calculated. Also, the maximum error is
652 * increased by the tolerance. If the PPS frequency discipline
653 * code is present, the phase is increased to compensate for the
654 * CPU clock oscillator frequency error.
655 *
656 * On a 32-bit machine and given parameters in the timex.h
657 * header file, the maximum phase adjustment is +-512 ms and
658 * maximum frequency offset is a tad less than) +-512 ppm. On a
659 * 64-bit machine, you shouldn't need to ask.
660 */
661 if (time.tv_usec >= 1000000) {
662 time.tv_usec -= 1000000;
663 time.tv_sec++;
664 time_maxerror += time_tolerance >> SHIFT_USEC;
665
666 /*
667 * Leap second processing. If in leap-insert state at
668 * the end of the day, the system clock is set back one
669 * second; if in leap-delete state, the system clock is
670 * set ahead one second. The microtime() routine or
671 * external clock driver will insure that reported time
672 * is always monotonic. The ugly divides should be
673 * replaced.
674 */
675 switch (time_state) {
676 case TIME_OK:
677 if (time_status & STA_INS)
678 time_state = TIME_INS;
679 else if (time_status & STA_DEL)
680 time_state = TIME_DEL;
681 break;
682
683 case TIME_INS:
684 if (time.tv_sec % 86400 == 0) {
685 time.tv_sec--;
686 time_state = TIME_OOP;
687 }
688 break;
689
690 case TIME_DEL:
691 if ((time.tv_sec + 1) % 86400 == 0) {
692 time.tv_sec++;
693 time_state = TIME_WAIT;
694 }
695 break;
696
697 case TIME_OOP:
698 time_state = TIME_WAIT;
699 break;
700
701 case TIME_WAIT:
702 if (!(time_status & (STA_INS | STA_DEL)))
703 time_state = TIME_OK;
704 break;
705 }
706
707 /*
708 * Compute the phase adjustment for the next second. In
709 * PLL mode, the offset is reduced by a fixed factor
710 * times the time constant. In FLL mode the offset is
711 * used directly. In either mode, the maximum phase
712 * adjustment for each second is clamped so as to spread
713 * the adjustment over not more than the number of
714 * seconds between updates.
715 */
716 if (time_offset < 0) {
717 ltemp = -time_offset;
718 if (!(time_status & STA_FLL))
719 ltemp >>= SHIFT_KG + time_constant;
720 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
721 ltemp = (MAXPHASE / MINSEC) <<
722 SHIFT_UPDATE;
723 time_offset += ltemp;
724 time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
725 } else if (time_offset > 0) {
726 ltemp = time_offset;
727 if (!(time_status & STA_FLL))
728 ltemp >>= SHIFT_KG + time_constant;
729 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
730 ltemp = (MAXPHASE / MINSEC) <<
731 SHIFT_UPDATE;
732 time_offset -= ltemp;
733 time_adj = ltemp << (shifthz - SHIFT_UPDATE);
734 } else
735 time_adj = 0;
736
737 /*
738 * Compute the frequency estimate and additional phase
739 * adjustment due to frequency error for the next
740 * second. When the PPS signal is engaged, gnaw on the
741 * watchdog counter and update the frequency computed by
742 * the pll and the PPS signal.
743 */
744 #ifdef PPS_SYNC
745 pps_valid++;
746 if (pps_valid == PPS_VALID) {
747 pps_jitter = MAXTIME;
748 pps_stabil = MAXFREQ;
749 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
750 STA_PPSWANDER | STA_PPSERROR);
751 }
752 ltemp = time_freq + pps_freq;
753 #else
754 ltemp = time_freq;
755 #endif /* PPS_SYNC */
756
757 if (ltemp < 0)
758 time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
759 else
760 time_adj += ltemp >> (SHIFT_USEC - shifthz);
761 time_adj += (long)fixtick << shifthz;
762
763 /*
764 * When the CPU clock oscillator frequency is not a
765 * power of 2 in Hz, shifthz is only an approximate
766 * scale factor.
767 *
768 * To determine the adjustment, you can do the following:
769 * bc -q
770 * scale=24
771 * obase=2
772 * idealhz/realhz
773 * where `idealhz' is the next higher power of 2, and `realhz'
774 * is the actual value. You may need to factor this result
775 * into a sequence of 2 multipliers to get better precision.
776 *
777 * Likewise, the error can be calculated with (e.g. for 100Hz):
778 * bc -q
779 * scale=24
780 * ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
781 * (and then multiply by 1000000 to get ppm).
782 */
783 switch (hz) {
784 case 60:
785 /* A factor of 1.000100010001 gives about 15ppm
786 error. */
787 if (time_adj < 0) {
788 time_adj -= (-time_adj >> 4);
789 time_adj -= (-time_adj >> 8);
790 } else {
791 time_adj += (time_adj >> 4);
792 time_adj += (time_adj >> 8);
793 }
794 break;
795
796 case 96:
797 /* A factor of 1.0101010101 gives about 244ppm error. */
798 if (time_adj < 0) {
799 time_adj -= (-time_adj >> 2);
800 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
801 } else {
802 time_adj += (time_adj >> 2);
803 time_adj += (time_adj >> 4) + (time_adj >> 8);
804 }
805 break;
806
807 case 100:
808 /* A factor of 1.010001111010111 gives about 1ppm
809 error. */
810 if (time_adj < 0) {
811 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
812 time_adj += (-time_adj >> 10);
813 } else {
814 time_adj += (time_adj >> 2) + (time_adj >> 5);
815 time_adj -= (time_adj >> 10);
816 }
817 break;
818
819 case 1000:
820 /* A factor of 1.000001100010100001 gives about 50ppm
821 error. */
822 if (time_adj < 0) {
823 time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
824 time_adj -= (-time_adj >> 7);
825 } else {
826 time_adj += (time_adj >> 6) + (time_adj >> 11);
827 time_adj += (time_adj >> 7);
828 }
829 break;
830
831 case 1200:
832 /* A factor of 1.1011010011100001 gives about 64ppm
833 error. */
834 if (time_adj < 0) {
835 time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
836 time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
837 } else {
838 time_adj += (time_adj >> 1) + (time_adj >> 6);
839 time_adj += (time_adj >> 3) + (time_adj >> 10);
840 }
841 break;
842 }
843
844 #ifdef EXT_CLOCK
845 /*
846 * If an external clock is present, it is necessary to
847 * discipline the kernel time variable anyway, since not
848 * all system components use the microtime() interface.
849 * Here, the time offset between the external clock and
850 * kernel time variable is computed every so often.
851 */
852 clock_count++;
853 if (clock_count > CLOCK_INTERVAL) {
854 clock_count = 0;
855 microtime(&clock_ext);
856 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
857 delta.tv_usec = clock_ext.tv_usec -
858 time.tv_usec;
859 if (delta.tv_usec < 0)
860 delta.tv_sec--;
861 if (delta.tv_usec >= 500000) {
862 delta.tv_usec -= 1000000;
863 delta.tv_sec++;
864 }
865 if (delta.tv_usec < -500000) {
866 delta.tv_usec += 1000000;
867 delta.tv_sec--;
868 }
869 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
870 delta.tv_usec > MAXPHASE) ||
871 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
872 delta.tv_usec < -MAXPHASE)) {
873 time = clock_ext;
874 delta.tv_sec = 0;
875 delta.tv_usec = 0;
876 }
877 #ifdef HIGHBALL
878 clock_cpu = delta.tv_usec;
879 #else /* HIGHBALL */
880 hardupdate(delta.tv_usec);
881 #endif /* HIGHBALL */
882 }
883 #endif /* EXT_CLOCK */
884 }
885
886 #endif /* NTP */
887
888 /*
889 * Process callouts at a very low cpu priority, so we don't keep the
890 * relatively high clock interrupt priority any longer than necessary.
891 */
892 simple_lock(&callwheel_slock); /* already at splclock() */
893 hardclock_ticks++;
894 if (! TAILQ_EMPTY(&callwheel[hardclock_ticks & callwheelmask].cq_q)) {
895 simple_unlock(&callwheel_slock);
896 if (CLKF_BASEPRI(frame)) {
897 /*
898 * Save the overhead of a software interrupt;
899 * it will happen as soon as we return, so do
900 * it now.
901 *
902 * NOTE: If we're at ``base priority'', softclock()
903 * was not already running.
904 */
905 spllowersoftclock();
906 KERNEL_LOCK(LK_CANRECURSE|LK_EXCLUSIVE);
907 softclock(NULL);
908 KERNEL_UNLOCK();
909 } else {
910 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
911 softintr_schedule(softclock_si);
912 #else
913 setsoftclock();
914 #endif
915 }
916 return;
917 } else if (softclock_running == 0 &&
918 (softclock_ticks + 1) == hardclock_ticks) {
919 softclock_ticks++;
920 }
921 simple_unlock(&callwheel_slock);
922 }
923
924 /*
925 * Software (low priority) clock interrupt.
926 * Run periodic events from timeout queue.
927 */
928 /*ARGSUSED*/
929 void
930 softclock(void *v)
931 {
932 struct callout_queue *bucket;
933 struct callout *c;
934 void (*func)(void *);
935 void *arg;
936 int s, idx;
937 int steps = 0;
938
939 CALLWHEEL_LOCK(s);
940
941 softclock_running = 1;
942
943 #ifdef CALLWHEEL_STATS
944 callwheel_softclocks.ev_count++;
945 #endif
946
947 while (softclock_ticks != hardclock_ticks) {
948 softclock_ticks++;
949 idx = (int)(softclock_ticks & callwheelmask);
950 bucket = &callwheel[idx];
951 c = TAILQ_FIRST(&bucket->cq_q);
952 if (c == NULL) {
953 #ifdef CALLWHEEL_STATS
954 callwheel_softempty.ev_count++;
955 #endif
956 continue;
957 }
958 if (softclock_ticks < bucket->cq_hint) {
959 #ifdef CALLWHEEL_STATS
960 callwheel_hintworked.ev_count++;
961 #endif
962 continue;
963 }
964 bucket->cq_hint = UQUAD_MAX;
965 while (c != NULL) {
966 #ifdef CALLWHEEL_STATS
967 callwheel_softchecks.ev_count++;
968 #endif
969 if (c->c_time != softclock_ticks) {
970 if (c->c_time < bucket->cq_hint)
971 bucket->cq_hint = c->c_time;
972 c = TAILQ_NEXT(c, c_link);
973 if (++steps >= MAX_SOFTCLOCK_STEPS) {
974 nextsoftcheck = c;
975 /* Give interrupts a chance. */
976 CALLWHEEL_UNLOCK(s);
977 CALLWHEEL_LOCK(s);
978 c = nextsoftcheck;
979 steps = 0;
980 }
981 } else {
982 nextsoftcheck = TAILQ_NEXT(c, c_link);
983 TAILQ_REMOVE(&bucket->cq_q, c, c_link);
984 #ifdef CALLWHEEL_STATS
985 callwheel_sizes[idx]--;
986 callwheel_fired.ev_count++;
987 callwheel_count.ev_count--;
988 #endif
989 func = c->c_func;
990 arg = c->c_arg;
991 c->c_func = NULL;
992 c->c_flags &= ~CALLOUT_PENDING;
993 CALLWHEEL_UNLOCK(s);
994 (*func)(arg);
995 CALLWHEEL_LOCK(s);
996 steps = 0;
997 c = nextsoftcheck;
998 }
999 }
1000 if (TAILQ_EMPTY(&bucket->cq_q))
1001 bucket->cq_hint = UQUAD_MAX;
1002 }
1003 nextsoftcheck = NULL;
1004 softclock_running = 0;
1005 CALLWHEEL_UNLOCK(s);
1006 }
1007
1008 /*
1009 * callout_setsize:
1010 *
1011 * Determine how many callwheels are necessary and
1012 * set hash mask. Called from allocsys().
1013 */
1014 void
1015 callout_setsize(void)
1016 {
1017
1018 for (callwheelsize = 1; callwheelsize < ncallout; callwheelsize <<= 1)
1019 /* loop */ ;
1020 callwheelmask = callwheelsize - 1;
1021 }
1022
1023 /*
1024 * callout_startup:
1025 *
1026 * Initialize the callwheel buckets.
1027 */
1028 void
1029 callout_startup(void)
1030 {
1031 int i;
1032
1033 for (i = 0; i < callwheelsize; i++) {
1034 callwheel[i].cq_hint = UQUAD_MAX;
1035 TAILQ_INIT(&callwheel[i].cq_q);
1036 }
1037
1038 simple_lock_init(&callwheel_slock);
1039
1040 #ifdef CALLWHEEL_STATS
1041 evcnt_attach_dynamic(&callwheel_collisions, EVCNT_TYPE_MISC,
1042 NULL, "callwheel", "collisions");
1043 evcnt_attach_dynamic(&callwheel_maxlength, EVCNT_TYPE_MISC,
1044 NULL, "callwheel", "maxlength");
1045 evcnt_attach_dynamic(&callwheel_count, EVCNT_TYPE_MISC,
1046 NULL, "callwheel", "count");
1047 evcnt_attach_dynamic(&callwheel_established, EVCNT_TYPE_MISC,
1048 NULL, "callwheel", "established");
1049 evcnt_attach_dynamic(&callwheel_fired, EVCNT_TYPE_MISC,
1050 NULL, "callwheel", "fired");
1051 evcnt_attach_dynamic(&callwheel_disestablished, EVCNT_TYPE_MISC,
1052 NULL, "callwheel", "disestablished");
1053 evcnt_attach_dynamic(&callwheel_changed, EVCNT_TYPE_MISC,
1054 NULL, "callwheel", "changed");
1055 evcnt_attach_dynamic(&callwheel_softclocks, EVCNT_TYPE_MISC,
1056 NULL, "callwheel", "softclocks");
1057 evcnt_attach_dynamic(&callwheel_softempty, EVCNT_TYPE_MISC,
1058 NULL, "callwheel", "softempty");
1059 evcnt_attach_dynamic(&callwheel_hintworked, EVCNT_TYPE_MISC,
1060 NULL, "callwheel", "hintworked");
1061 #endif /* CALLWHEEL_STATS */
1062 }
1063
1064 /*
1065 * callout_init:
1066 *
1067 * Initialize a callout structure so that it can be used
1068 * by callout_reset() and callout_stop().
1069 */
1070 void
1071 callout_init(struct callout *c)
1072 {
1073
1074 memset(c, 0, sizeof(*c));
1075 }
1076
1077 /*
1078 * callout_reset:
1079 *
1080 * Establish or change a timeout.
1081 */
1082 void
1083 callout_reset(struct callout *c, int ticks, void (*func)(void *), void *arg)
1084 {
1085 struct callout_queue *bucket;
1086 int s;
1087
1088 if (ticks <= 0)
1089 ticks = 1;
1090
1091 CALLWHEEL_LOCK(s);
1092
1093 /*
1094 * If this callout's timer is already running, cancel it
1095 * before we modify it.
1096 */
1097 if (c->c_flags & CALLOUT_PENDING) {
1098 callout_stop_locked(c); /* Already locked */
1099 #ifdef CALLWHEEL_STATS
1100 callwheel_changed.ev_count++;
1101 #endif
1102 }
1103
1104 c->c_arg = arg;
1105 c->c_func = func;
1106 c->c_flags = CALLOUT_ACTIVE | CALLOUT_PENDING;
1107 c->c_time = hardclock_ticks + ticks;
1108
1109 bucket = &callwheel[c->c_time & callwheelmask];
1110
1111 #ifdef CALLWHEEL_STATS
1112 if (! TAILQ_EMPTY(&bucket->cq_q))
1113 callwheel_collisions.ev_count++;
1114 #endif
1115
1116 TAILQ_INSERT_TAIL(&bucket->cq_q, c, c_link);
1117 if (c->c_time < bucket->cq_hint)
1118 bucket->cq_hint = c->c_time;
1119
1120 #ifdef CALLWHEEL_STATS
1121 callwheel_count.ev_count++;
1122 callwheel_established.ev_count++;
1123 if (++callwheel_sizes[c->c_time & callwheelmask] >
1124 callwheel_maxlength.ev_count)
1125 callwheel_maxlength.ev_count =
1126 callwheel_sizes[c->c_time & callwheelmask];
1127 #endif
1128
1129 CALLWHEEL_UNLOCK(s);
1130 }
1131
1132 /*
1133 * callout_stop_locked:
1134 *
1135 * Disestablish a timeout. Callwheel is locked.
1136 */
1137 static void
1138 callout_stop_locked(struct callout *c)
1139 {
1140 struct callout_queue *bucket;
1141
1142 /*
1143 * Don't attempt to delete a callout that's not on the queue.
1144 */
1145 if ((c->c_flags & CALLOUT_PENDING) == 0) {
1146 c->c_flags &= ~CALLOUT_ACTIVE;
1147 return;
1148 }
1149
1150 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1151
1152 if (nextsoftcheck == c)
1153 nextsoftcheck = TAILQ_NEXT(c, c_link);
1154
1155 bucket = &callwheel[c->c_time & callwheelmask];
1156 TAILQ_REMOVE(&bucket->cq_q, c, c_link);
1157 if (TAILQ_EMPTY(&bucket->cq_q))
1158 bucket->cq_hint = UQUAD_MAX;
1159 #ifdef CALLWHEEL_STATS
1160 callwheel_count.ev_count--;
1161 callwheel_disestablished.ev_count++;
1162 callwheel_sizes[c->c_time & callwheelmask]--;
1163 #endif
1164
1165 c->c_func = NULL;
1166 }
1167
1168 /*
1169 * callout_stop:
1170 *
1171 * Disestablish a timeout. Callwheel is unlocked. This is
1172 * the standard entry point.
1173 */
1174 void
1175 callout_stop(struct callout *c)
1176 {
1177 int s;
1178
1179 CALLWHEEL_LOCK(s);
1180 callout_stop_locked(c);
1181 CALLWHEEL_UNLOCK(s);
1182 }
1183
1184 #ifdef CALLWHEEL_STATS
1185 /*
1186 * callout_showstats:
1187 *
1188 * Display callout statistics. Call it from DDB.
1189 */
1190 void
1191 callout_showstats(void)
1192 {
1193 u_int64_t curticks;
1194 int s;
1195
1196 s = splclock();
1197 curticks = softclock_ticks;
1198 splx(s);
1199
1200 printf("Callwheel statistics:\n");
1201 printf("\tCallouts currently queued: %llu\n",
1202 (long long) callwheel_count.ev_count);
1203 printf("\tCallouts established: %llu\n",
1204 (long long) callwheel_established.ev_count);
1205 printf("\tCallouts disestablished: %llu\n",
1206 (long long) callwheel_disestablished.ev_count);
1207 if (callwheel_changed.ev_count != 0)
1208 printf("\t\tOf those, %llu were changes\n",
1209 (long long) callwheel_changed.ev_count);
1210 printf("\tCallouts that fired: %llu\n",
1211 (long long) callwheel_fired.ev_count);
1212 printf("\tNumber of buckets: %d\n", callwheelsize);
1213 printf("\tNumber of hash collisions: %llu\n",
1214 (long long) callwheel_collisions.ev_count);
1215 printf("\tMaximum hash chain length: %llu\n",
1216 (long long) callwheel_maxlength.ev_count);
1217 printf("\tSoftclocks: %llu, Softchecks: %llu\n",
1218 (long long) callwheel_softclocks.ev_count,
1219 (long long) callwheel_softchecks.ev_count);
1220 printf("\t\tEmpty buckets seen: %llu\n",
1221 (long long) callwheel_softempty.ev_count);
1222 printf("\t\tTimes hint saved scan: %llu\n",
1223 (long long) callwheel_hintworked.ev_count);
1224 }
1225 #endif
1226
1227 /*
1228 * Compute number of hz until specified time. Used to compute second
1229 * argument to callout_reset() from an absolute time.
1230 */
1231 int
1232 hzto(struct timeval *tv)
1233 {
1234 unsigned long ticks;
1235 long sec, usec;
1236 int s;
1237
1238 /*
1239 * If the number of usecs in the whole seconds part of the time
1240 * difference fits in a long, then the total number of usecs will
1241 * fit in an unsigned long. Compute the total and convert it to
1242 * ticks, rounding up and adding 1 to allow for the current tick
1243 * to expire. Rounding also depends on unsigned long arithmetic
1244 * to avoid overflow.
1245 *
1246 * Otherwise, if the number of ticks in the whole seconds part of
1247 * the time difference fits in a long, then convert the parts to
1248 * ticks separately and add, using similar rounding methods and
1249 * overflow avoidance. This method would work in the previous
1250 * case, but it is slightly slower and assume that hz is integral.
1251 *
1252 * Otherwise, round the time difference down to the maximum
1253 * representable value.
1254 *
1255 * If ints are 32-bit, then the maximum value for any timeout in
1256 * 10ms ticks is 248 days.
1257 */
1258 s = splclock();
1259 sec = tv->tv_sec - time.tv_sec;
1260 usec = tv->tv_usec - time.tv_usec;
1261 splx(s);
1262
1263 if (usec < 0) {
1264 sec--;
1265 usec += 1000000;
1266 }
1267
1268 if (sec < 0 || (sec == 0 && usec <= 0)) {
1269 /*
1270 * Would expire now or in the past. Return 0 ticks.
1271 * This is different from the legacy hzto() interface,
1272 * and callers need to check for it.
1273 */
1274 ticks = 0;
1275 } else if (sec <= (LONG_MAX / 1000000))
1276 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
1277 / tick) + 1;
1278 else if (sec <= (LONG_MAX / hz))
1279 ticks = (sec * hz) +
1280 (((unsigned long)usec + (tick - 1)) / tick) + 1;
1281 else
1282 ticks = LONG_MAX;
1283
1284 if (ticks > INT_MAX)
1285 ticks = INT_MAX;
1286
1287 return ((int)ticks);
1288 }
1289
1290 /*
1291 * Start profiling on a process.
1292 *
1293 * Kernel profiling passes proc0 which never exits and hence
1294 * keeps the profile clock running constantly.
1295 */
1296 void
1297 startprofclock(struct proc *p)
1298 {
1299
1300 if ((p->p_flag & P_PROFIL) == 0) {
1301 p->p_flag |= P_PROFIL;
1302 if (++profprocs == 1 && stathz != 0)
1303 psdiv = psratio;
1304 }
1305 }
1306
1307 /*
1308 * Stop profiling on a process.
1309 */
1310 void
1311 stopprofclock(struct proc *p)
1312 {
1313
1314 if (p->p_flag & P_PROFIL) {
1315 p->p_flag &= ~P_PROFIL;
1316 if (--profprocs == 0 && stathz != 0)
1317 psdiv = 1;
1318 }
1319 }
1320
1321 /*
1322 * Statistics clock. Grab profile sample, and if divider reaches 0,
1323 * do process and kernel statistics.
1324 */
1325 void
1326 statclock(struct clockframe *frame)
1327 {
1328 #ifdef GPROF
1329 struct gmonparam *g;
1330 intptr_t i;
1331 #endif
1332 struct cpu_info *ci = curcpu();
1333 struct schedstate_percpu *spc = &ci->ci_schedstate;
1334 struct lwp *l;
1335 struct proc *p;
1336
1337 /*
1338 * Notice changes in divisor frequency, and adjust clock
1339 * frequency accordingly.
1340 */
1341 if (spc->spc_psdiv != psdiv) {
1342 spc->spc_psdiv = psdiv;
1343 spc->spc_pscnt = psdiv;
1344 if (psdiv == 1) {
1345 setstatclockrate(stathz);
1346 } else {
1347 setstatclockrate(profhz);
1348 }
1349 }
1350 l = curproc;
1351 p = (l ? l->l_proc : 0);
1352 if (CLKF_USERMODE(frame)) {
1353 if (p->p_flag & P_PROFIL)
1354 addupc_intr(p, CLKF_PC(frame));
1355 if (--spc->spc_pscnt > 0)
1356 return;
1357 /*
1358 * Came from user mode; CPU was in user state.
1359 * If this process is being profiled record the tick.
1360 */
1361 p->p_uticks++;
1362 if (p->p_nice > NZERO)
1363 spc->spc_cp_time[CP_NICE]++;
1364 else
1365 spc->spc_cp_time[CP_USER]++;
1366 } else {
1367 #ifdef GPROF
1368 /*
1369 * Kernel statistics are just like addupc_intr, only easier.
1370 */
1371 g = &_gmonparam;
1372 if (g->state == GMON_PROF_ON) {
1373 i = CLKF_PC(frame) - g->lowpc;
1374 if (i < g->textsize) {
1375 i /= HISTFRACTION * sizeof(*g->kcount);
1376 g->kcount[i]++;
1377 }
1378 }
1379 #endif
1380 #ifdef LWP_PC
1381 if (p && p->p_flag & P_PROFIL)
1382 addupc_intr(p, LWP_PC(l));
1383 #endif
1384 if (--spc->spc_pscnt > 0)
1385 return;
1386 /*
1387 * Came from kernel mode, so we were:
1388 * - handling an interrupt,
1389 * - doing syscall or trap work on behalf of the current
1390 * user process, or
1391 * - spinning in the idle loop.
1392 * Whichever it is, charge the time as appropriate.
1393 * Note that we charge interrupts to the current process,
1394 * regardless of whether they are ``for'' that process,
1395 * so that we know how much of its real time was spent
1396 * in ``non-process'' (i.e., interrupt) work.
1397 */
1398 if (CLKF_INTR(frame)) {
1399 if (p != NULL)
1400 p->p_iticks++;
1401 spc->spc_cp_time[CP_INTR]++;
1402 } else if (p != NULL) {
1403 p->p_sticks++;
1404 spc->spc_cp_time[CP_SYS]++;
1405 } else
1406 spc->spc_cp_time[CP_IDLE]++;
1407 }
1408 spc->spc_pscnt = psdiv;
1409
1410 if (l != NULL) {
1411 ++p->p_cpticks;
1412 /*
1413 * If no separate schedclock is provided, call it here
1414 * at ~~12-25 Hz, ~~16 Hz is best
1415 */
1416 if (schedhz == 0)
1417 if ((++ci->ci_schedstate.spc_schedticks & 3) == 0)
1418 schedclock(l);
1419 }
1420 }
1421
1422
1423 #ifdef NTP /* NTP phase-locked loop in kernel */
1424
1425 /*
1426 * hardupdate() - local clock update
1427 *
1428 * This routine is called by ntp_adjtime() to update the local clock
1429 * phase and frequency. The implementation is of an adaptive-parameter,
1430 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1431 * time and frequency offset estimates for each call. If the kernel PPS
1432 * discipline code is configured (PPS_SYNC), the PPS signal itself
1433 * determines the new time offset, instead of the calling argument.
1434 * Presumably, calls to ntp_adjtime() occur only when the caller
1435 * believes the local clock is valid within some bound (+-128 ms with
1436 * NTP). If the caller's time is far different than the PPS time, an
1437 * argument will ensue, and it's not clear who will lose.
1438 *
1439 * For uncompensated quartz crystal oscillatores and nominal update
1440 * intervals less than 1024 s, operation should be in phase-lock mode
1441 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1442 * intervals greater than thiss, operation should be in frequency-lock
1443 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1444 *
1445 * Note: splclock() is in effect.
1446 */
1447 void
1448 hardupdate(long offset)
1449 {
1450 long ltemp, mtemp;
1451
1452 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1453 return;
1454 ltemp = offset;
1455 #ifdef PPS_SYNC
1456 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1457 ltemp = pps_offset;
1458 #endif /* PPS_SYNC */
1459
1460 /*
1461 * Scale the phase adjustment and clamp to the operating range.
1462 */
1463 if (ltemp > MAXPHASE)
1464 time_offset = MAXPHASE << SHIFT_UPDATE;
1465 else if (ltemp < -MAXPHASE)
1466 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1467 else
1468 time_offset = ltemp << SHIFT_UPDATE;
1469
1470 /*
1471 * Select whether the frequency is to be controlled and in which
1472 * mode (PLL or FLL). Clamp to the operating range. Ugly
1473 * multiply/divide should be replaced someday.
1474 */
1475 if (time_status & STA_FREQHOLD || time_reftime == 0)
1476 time_reftime = time.tv_sec;
1477 mtemp = time.tv_sec - time_reftime;
1478 time_reftime = time.tv_sec;
1479 if (time_status & STA_FLL) {
1480 if (mtemp >= MINSEC) {
1481 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1482 SHIFT_UPDATE));
1483 if (ltemp < 0)
1484 time_freq -= -ltemp >> SHIFT_KH;
1485 else
1486 time_freq += ltemp >> SHIFT_KH;
1487 }
1488 } else {
1489 if (mtemp < MAXSEC) {
1490 ltemp *= mtemp;
1491 if (ltemp < 0)
1492 time_freq -= -ltemp >> (time_constant +
1493 time_constant + SHIFT_KF -
1494 SHIFT_USEC);
1495 else
1496 time_freq += ltemp >> (time_constant +
1497 time_constant + SHIFT_KF -
1498 SHIFT_USEC);
1499 }
1500 }
1501 if (time_freq > time_tolerance)
1502 time_freq = time_tolerance;
1503 else if (time_freq < -time_tolerance)
1504 time_freq = -time_tolerance;
1505 }
1506
1507 #ifdef PPS_SYNC
1508 /*
1509 * hardpps() - discipline CPU clock oscillator to external PPS signal
1510 *
1511 * This routine is called at each PPS interrupt in order to discipline
1512 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1513 * and leaves it in a handy spot for the hardclock() routine. It
1514 * integrates successive PPS phase differences and calculates the
1515 * frequency offset. This is used in hardclock() to discipline the CPU
1516 * clock oscillator so that intrinsic frequency error is cancelled out.
1517 * The code requires the caller to capture the time and hardware counter
1518 * value at the on-time PPS signal transition.
1519 *
1520 * Note that, on some Unix systems, this routine runs at an interrupt
1521 * priority level higher than the timer interrupt routine hardclock().
1522 * Therefore, the variables used are distinct from the hardclock()
1523 * variables, except for certain exceptions: The PPS frequency pps_freq
1524 * and phase pps_offset variables are determined by this routine and
1525 * updated atomically. The time_tolerance variable can be considered a
1526 * constant, since it is infrequently changed, and then only when the
1527 * PPS signal is disabled. The watchdog counter pps_valid is updated
1528 * once per second by hardclock() and is atomically cleared in this
1529 * routine.
1530 */
1531 void
1532 hardpps(struct timeval *tvp, /* time at PPS */
1533 long usec /* hardware counter at PPS */)
1534 {
1535 long u_usec, v_usec, bigtick;
1536 long cal_sec, cal_usec;
1537
1538 /*
1539 * An occasional glitch can be produced when the PPS interrupt
1540 * occurs in the hardclock() routine before the time variable is
1541 * updated. Here the offset is discarded when the difference
1542 * between it and the last one is greater than tick/2, but not
1543 * if the interval since the first discard exceeds 30 s.
1544 */
1545 time_status |= STA_PPSSIGNAL;
1546 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1547 pps_valid = 0;
1548 u_usec = -tvp->tv_usec;
1549 if (u_usec < -500000)
1550 u_usec += 1000000;
1551 v_usec = pps_offset - u_usec;
1552 if (v_usec < 0)
1553 v_usec = -v_usec;
1554 if (v_usec > (tick >> 1)) {
1555 if (pps_glitch > MAXGLITCH) {
1556 pps_glitch = 0;
1557 pps_tf[2] = u_usec;
1558 pps_tf[1] = u_usec;
1559 } else {
1560 pps_glitch++;
1561 u_usec = pps_offset;
1562 }
1563 } else
1564 pps_glitch = 0;
1565
1566 /*
1567 * A three-stage median filter is used to help deglitch the pps
1568 * time. The median sample becomes the time offset estimate; the
1569 * difference between the other two samples becomes the time
1570 * dispersion (jitter) estimate.
1571 */
1572 pps_tf[2] = pps_tf[1];
1573 pps_tf[1] = pps_tf[0];
1574 pps_tf[0] = u_usec;
1575 if (pps_tf[0] > pps_tf[1]) {
1576 if (pps_tf[1] > pps_tf[2]) {
1577 pps_offset = pps_tf[1]; /* 0 1 2 */
1578 v_usec = pps_tf[0] - pps_tf[2];
1579 } else if (pps_tf[2] > pps_tf[0]) {
1580 pps_offset = pps_tf[0]; /* 2 0 1 */
1581 v_usec = pps_tf[2] - pps_tf[1];
1582 } else {
1583 pps_offset = pps_tf[2]; /* 0 2 1 */
1584 v_usec = pps_tf[0] - pps_tf[1];
1585 }
1586 } else {
1587 if (pps_tf[1] < pps_tf[2]) {
1588 pps_offset = pps_tf[1]; /* 2 1 0 */
1589 v_usec = pps_tf[2] - pps_tf[0];
1590 } else if (pps_tf[2] < pps_tf[0]) {
1591 pps_offset = pps_tf[0]; /* 1 0 2 */
1592 v_usec = pps_tf[1] - pps_tf[2];
1593 } else {
1594 pps_offset = pps_tf[2]; /* 1 2 0 */
1595 v_usec = pps_tf[1] - pps_tf[0];
1596 }
1597 }
1598 if (v_usec > MAXTIME)
1599 pps_jitcnt++;
1600 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1601 if (v_usec < 0)
1602 pps_jitter -= -v_usec >> PPS_AVG;
1603 else
1604 pps_jitter += v_usec >> PPS_AVG;
1605 if (pps_jitter > (MAXTIME >> 1))
1606 time_status |= STA_PPSJITTER;
1607
1608 /*
1609 * During the calibration interval adjust the starting time when
1610 * the tick overflows. At the end of the interval compute the
1611 * duration of the interval and the difference of the hardware
1612 * counters at the beginning and end of the interval. This code
1613 * is deliciously complicated by the fact valid differences may
1614 * exceed the value of tick when using long calibration
1615 * intervals and small ticks. Note that the counter can be
1616 * greater than tick if caught at just the wrong instant, but
1617 * the values returned and used here are correct.
1618 */
1619 bigtick = (long)tick << SHIFT_USEC;
1620 pps_usec -= pps_freq;
1621 if (pps_usec >= bigtick)
1622 pps_usec -= bigtick;
1623 if (pps_usec < 0)
1624 pps_usec += bigtick;
1625 pps_time.tv_sec++;
1626 pps_count++;
1627 if (pps_count < (1 << pps_shift))
1628 return;
1629 pps_count = 0;
1630 pps_calcnt++;
1631 u_usec = usec << SHIFT_USEC;
1632 v_usec = pps_usec - u_usec;
1633 if (v_usec >= bigtick >> 1)
1634 v_usec -= bigtick;
1635 if (v_usec < -(bigtick >> 1))
1636 v_usec += bigtick;
1637 if (v_usec < 0)
1638 v_usec = -(-v_usec >> pps_shift);
1639 else
1640 v_usec = v_usec >> pps_shift;
1641 pps_usec = u_usec;
1642 cal_sec = tvp->tv_sec;
1643 cal_usec = tvp->tv_usec;
1644 cal_sec -= pps_time.tv_sec;
1645 cal_usec -= pps_time.tv_usec;
1646 if (cal_usec < 0) {
1647 cal_usec += 1000000;
1648 cal_sec--;
1649 }
1650 pps_time = *tvp;
1651
1652 /*
1653 * Check for lost interrupts, noise, excessive jitter and
1654 * excessive frequency error. The number of timer ticks during
1655 * the interval may vary +-1 tick. Add to this a margin of one
1656 * tick for the PPS signal jitter and maximum frequency
1657 * deviation. If the limits are exceeded, the calibration
1658 * interval is reset to the minimum and we start over.
1659 */
1660 u_usec = (long)tick << 1;
1661 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1662 || (cal_sec == 0 && cal_usec < u_usec))
1663 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1664 pps_errcnt++;
1665 pps_shift = PPS_SHIFT;
1666 pps_intcnt = 0;
1667 time_status |= STA_PPSERROR;
1668 return;
1669 }
1670
1671 /*
1672 * A three-stage median filter is used to help deglitch the pps
1673 * frequency. The median sample becomes the frequency offset
1674 * estimate; the difference between the other two samples
1675 * becomes the frequency dispersion (stability) estimate.
1676 */
1677 pps_ff[2] = pps_ff[1];
1678 pps_ff[1] = pps_ff[0];
1679 pps_ff[0] = v_usec;
1680 if (pps_ff[0] > pps_ff[1]) {
1681 if (pps_ff[1] > pps_ff[2]) {
1682 u_usec = pps_ff[1]; /* 0 1 2 */
1683 v_usec = pps_ff[0] - pps_ff[2];
1684 } else if (pps_ff[2] > pps_ff[0]) {
1685 u_usec = pps_ff[0]; /* 2 0 1 */
1686 v_usec = pps_ff[2] - pps_ff[1];
1687 } else {
1688 u_usec = pps_ff[2]; /* 0 2 1 */
1689 v_usec = pps_ff[0] - pps_ff[1];
1690 }
1691 } else {
1692 if (pps_ff[1] < pps_ff[2]) {
1693 u_usec = pps_ff[1]; /* 2 1 0 */
1694 v_usec = pps_ff[2] - pps_ff[0];
1695 } else if (pps_ff[2] < pps_ff[0]) {
1696 u_usec = pps_ff[0]; /* 1 0 2 */
1697 v_usec = pps_ff[1] - pps_ff[2];
1698 } else {
1699 u_usec = pps_ff[2]; /* 1 2 0 */
1700 v_usec = pps_ff[1] - pps_ff[0];
1701 }
1702 }
1703
1704 /*
1705 * Here the frequency dispersion (stability) is updated. If it
1706 * is less than one-fourth the maximum (MAXFREQ), the frequency
1707 * offset is updated as well, but clamped to the tolerance. It
1708 * will be processed later by the hardclock() routine.
1709 */
1710 v_usec = (v_usec >> 1) - pps_stabil;
1711 if (v_usec < 0)
1712 pps_stabil -= -v_usec >> PPS_AVG;
1713 else
1714 pps_stabil += v_usec >> PPS_AVG;
1715 if (pps_stabil > MAXFREQ >> 2) {
1716 pps_stbcnt++;
1717 time_status |= STA_PPSWANDER;
1718 return;
1719 }
1720 if (time_status & STA_PPSFREQ) {
1721 if (u_usec < 0) {
1722 pps_freq -= -u_usec >> PPS_AVG;
1723 if (pps_freq < -time_tolerance)
1724 pps_freq = -time_tolerance;
1725 u_usec = -u_usec;
1726 } else {
1727 pps_freq += u_usec >> PPS_AVG;
1728 if (pps_freq > time_tolerance)
1729 pps_freq = time_tolerance;
1730 }
1731 }
1732
1733 /*
1734 * Here the calibration interval is adjusted. If the maximum
1735 * time difference is greater than tick / 4, reduce the interval
1736 * by half. If this is not the case for four consecutive
1737 * intervals, double the interval.
1738 */
1739 if (u_usec << pps_shift > bigtick >> 2) {
1740 pps_intcnt = 0;
1741 if (pps_shift > PPS_SHIFT)
1742 pps_shift--;
1743 } else if (pps_intcnt >= 4) {
1744 pps_intcnt = 0;
1745 if (pps_shift < PPS_SHIFTMAX)
1746 pps_shift++;
1747 } else
1748 pps_intcnt++;
1749 }
1750 #endif /* PPS_SYNC */
1751 #endif /* NTP */
1752
1753 /*
1754 * Return information about system clocks.
1755 */
1756 int
1757 sysctl_clockrate(void *where, size_t *sizep)
1758 {
1759 struct clockinfo clkinfo;
1760
1761 /*
1762 * Construct clockinfo structure.
1763 */
1764 clkinfo.tick = tick;
1765 clkinfo.tickadj = tickadj;
1766 clkinfo.hz = hz;
1767 clkinfo.profhz = profhz;
1768 clkinfo.stathz = stathz ? stathz : hz;
1769 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1770 }
1771