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