include: gcc 7's cpp has problems with the line continuations in .x files
[unleashed.git] / kernel / os / clock.c
blob478cca814967972924e97612455ea92e917884e8
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
21 /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
22 /* All Rights Reserved */
25 * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
26 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2015, Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
28 * Copyright (c) 2016 by Delphix. All rights reserved.
29 * Copyright (c) 2018, Carlos Neira <cneirabustos@gmail.com>
32 #include <sys/param.h>
33 #include <sys/t_lock.h>
34 #include <sys/types.h>
35 #include <sys/tuneable.h>
36 #include <sys/sysmacros.h>
37 #include <sys/systm.h>
38 #include <sys/cpuvar.h>
39 #include <sys/lgrp.h>
40 #include <sys/user.h>
41 #include <sys/proc.h>
42 #include <sys/callo.h>
43 #include <sys/kmem.h>
44 #include <sys/var.h>
45 #include <sys/cmn_err.h>
46 #include <sys/swap.h>
47 #include <sys/vmsystm.h>
48 #include <sys/class.h>
49 #include <sys/time.h>
50 #include <sys/debug.h>
51 #include <sys/vtrace.h>
52 #include <sys/spl.h>
53 #include <sys/atomic.h>
54 #include <sys/dumphdr.h>
55 #include <sys/archsystm.h>
56 #include <sys/fs/swapnode.h>
57 #include <sys/panic.h>
58 #include <sys/disp.h>
59 #include <sys/msacct.h>
61 #include <vm/page.h>
62 #include <vm/anon.h>
63 #include <vm/rm.h>
64 #include <sys/cyclic.h>
65 #include <sys/cpupart.h>
66 #include <sys/rctl.h>
67 #include <sys/task.h>
68 #include <sys/sdt.h>
69 #include <sys/ddi_periodic.h>
70 #include <sys/random.h>
71 #include <sys/modctl.h>
72 #include <sys/zone.h>
75 * for NTP support
77 #include <sys/timex.h>
78 #include <sys/inttypes.h>
80 #include <sys/sunddi.h>
81 #include <sys/clock_impl.h>
84 * clock() is called straight from the clock cyclic; see clock_init().
86 * Functions:
87 * reprime clock
88 * maintain date
89 * jab the scheduler
92 extern kcondvar_t fsflush_cv;
93 extern sysinfo_t sysinfo;
94 extern vminfo_t vminfo;
95 extern int idleswtch; /* flag set while idle in pswtch() */
96 extern hrtime_t volatile devinfo_freeze;
99 * high-precision avenrun values. These are needed to make the
100 * regular avenrun values accurate.
102 static uint64_t hp_avenrun[3];
103 int avenrun[3]; /* FSCALED average run queue lengths */
104 time_t time; /* time in seconds since 1970 - for compatibility only */
106 static struct loadavg_s loadavg;
108 * Phase/frequency-lock loop (PLL/FLL) definitions
110 * The following variables are read and set by the ntp_adjtime() system
111 * call.
113 * time_state shows the state of the system clock, with values defined
114 * in the timex.h header file.
116 * time_status shows the status of the system clock, with bits defined
117 * in the timex.h header file.
119 * time_offset is used by the PLL/FLL to adjust the system time in small
120 * increments.
122 * time_constant determines the bandwidth or "stiffness" of the PLL.
124 * time_tolerance determines maximum frequency error or tolerance of the
125 * CPU clock oscillator and is a property of the architecture; however,
126 * in principle it could change as result of the presence of external
127 * discipline signals, for instance.
129 * time_precision is usually equal to the kernel tick variable; however,
130 * in cases where a precision clock counter or external clock is
131 * available, the resolution can be much less than this and depend on
132 * whether the external clock is working or not.
134 * time_maxerror is initialized by a ntp_adjtime() call and increased by
135 * the kernel once each second to reflect the maximum error bound
136 * growth.
138 * time_esterror is set and read by the ntp_adjtime() call, but
139 * otherwise not used by the kernel.
141 int32_t time_state = TIME_OK; /* clock state */
142 int32_t time_status = STA_UNSYNC; /* clock status bits */
143 int32_t time_offset = 0; /* time offset (us) */
144 int32_t time_constant = 0; /* pll time constant */
145 int32_t time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */
146 int32_t time_precision = 1; /* clock precision (us) */
147 int32_t time_maxerror = MAXPHASE; /* maximum error (us) */
148 int32_t time_esterror = MAXPHASE; /* estimated error (us) */
151 * The following variables establish the state of the PLL/FLL and the
152 * residual time and frequency offset of the local clock. The scale
153 * factors are defined in the timex.h header file.
155 * time_phase and time_freq are the phase increment and the frequency
156 * increment, respectively, of the kernel time variable.
158 * time_freq is set via ntp_adjtime() from a value stored in a file when
159 * the synchronization daemon is first started. Its value is retrieved
160 * via ntp_adjtime() and written to the file about once per hour by the
161 * daemon.
163 * time_adj is the adjustment added to the value of tick at each timer
164 * interrupt and is recomputed from time_phase and time_freq at each
165 * seconds rollover.
167 * time_reftime is the second's portion of the system time at the last
168 * call to ntp_adjtime(). It is used to adjust the time_freq variable
169 * and to increase the time_maxerror as the time since last update
170 * increases.
172 int32_t time_phase = 0; /* phase offset (scaled us) */
173 int32_t time_freq = 0; /* frequency offset (scaled ppm) */
174 int32_t time_adj = 0; /* tick adjust (scaled 1 / hz) */
175 int32_t time_reftime = 0; /* time at last adjustment (s) */
178 * The scale factors of the following variables are defined in the
179 * timex.h header file.
181 * pps_time contains the time at each calibration interval, as read by
182 * microtime(). pps_count counts the seconds of the calibration
183 * interval, the duration of which is nominally pps_shift in powers of
184 * two.
186 * pps_offset is the time offset produced by the time median filter
187 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
188 * this filter.
190 * pps_freq is the frequency offset produced by the frequency median
191 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
192 * by this filter.
194 * pps_usec is latched from a high resolution counter or external clock
195 * at pps_time. Here we want the hardware counter contents only, not the
196 * contents plus the time_tv.usec as usual.
198 * pps_valid counts the number of seconds since the last PPS update. It
199 * is used as a watchdog timer to disable the PPS discipline should the
200 * PPS signal be lost.
202 * pps_glitch counts the number of seconds since the beginning of an
203 * offset burst more than tick/2 from current nominal offset. It is used
204 * mainly to suppress error bursts due to priority conflicts between the
205 * PPS interrupt and timer interrupt.
207 * pps_intcnt counts the calibration intervals for use in the interval-
208 * adaptation algorithm. It's just too complicated for words.
210 struct timeval pps_time; /* kernel time at last interval */
211 int32_t pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
212 int32_t pps_offset = 0; /* pps time offset (us) */
213 int32_t pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
214 int32_t pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
215 int32_t pps_freq = 0; /* frequency offset (scaled ppm) */
216 int32_t pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
217 int32_t pps_usec = 0; /* microsec counter at last interval */
218 int32_t pps_valid = PPS_VALID; /* pps signal watchdog counter */
219 int32_t pps_glitch = 0; /* pps signal glitch counter */
220 int32_t pps_count = 0; /* calibration interval counter (s) */
221 int32_t pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
222 int32_t pps_intcnt = 0; /* intervals at current duration */
225 * PPS signal quality monitors
227 * pps_jitcnt counts the seconds that have been discarded because the
228 * jitter measured by the time median filter exceeds the limit MAXTIME
229 * (100 us).
231 * pps_calcnt counts the frequency calibration intervals, which are
232 * variable from 4 s to 256 s.
234 * pps_errcnt counts the calibration intervals which have been discarded
235 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
236 * calibration interval jitter exceeds two ticks.
238 * pps_stbcnt counts the calibration intervals that have been discarded
239 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
241 int32_t pps_jitcnt = 0; /* jitter limit exceeded */
242 int32_t pps_calcnt = 0; /* calibration intervals */
243 int32_t pps_errcnt = 0; /* calibration errors */
244 int32_t pps_stbcnt = 0; /* stability limit exceeded */
246 kcondvar_t lbolt_cv;
249 * Hybrid lbolt implementation:
251 * The service historically provided by the lbolt and lbolt64 variables has
252 * been replaced by the ddi_get_lbolt() and ddi_get_lbolt64() routines, and the
253 * original symbols removed from the system. The once clock driven variables are
254 * now implemented in an event driven fashion, backed by gethrtime() coarsed to
255 * the appropriate clock resolution. The default event driven implementation is
256 * complemented by a cyclic driven one, active only during periods of intense
257 * activity around the DDI lbolt routines, when a lbolt specific cyclic is
258 * reprogramed to fire at a clock tick interval to serve consumers of lbolt who
259 * rely on the original low cost of consulting a memory position.
261 * The implementation uses the number of calls to these routines and the
262 * frequency of these to determine when to transition from event to cyclic
263 * driven and vice-versa. These values are kept on a per CPU basis for
264 * scalability reasons and to prevent CPUs from constantly invalidating a single
265 * cache line when modifying a global variable. The transition from event to
266 * cyclic mode happens once the thresholds are crossed, and activity on any CPU
267 * can cause such transition.
269 * The lbolt_hybrid function pointer is called by ddi_get_lbolt() and
270 * ddi_get_lbolt64(), and will point to lbolt_event_driven() or
271 * lbolt_cyclic_driven() according to the current mode. When the thresholds
272 * are exceeded, lbolt_event_driven() will reprogram the lbolt cyclic to
273 * fire at a nsec_per_tick interval and increment an internal variable at
274 * each firing. lbolt_hybrid will then point to lbolt_cyclic_driven(), which
275 * will simply return the value of such variable. lbolt_cyclic() will attempt
276 * to shut itself off at each threshold interval (sampling period for calls
277 * to the DDI lbolt routines), and return to the event driven mode, but will
278 * be prevented from doing so if lbolt_cyclic_driven() is being heavily used.
280 * lbolt_bootstrap is used during boot to serve lbolt consumers who don't wait
281 * for the cyclic subsystem to be intialized.
284 int64_t lbolt_bootstrap(void);
285 int64_t lbolt_event_driven(void);
286 int64_t lbolt_cyclic_driven(void);
287 int64_t (*lbolt_hybrid)(void) = lbolt_bootstrap;
288 uint_t lbolt_ev_to_cyclic(caddr_t, caddr_t);
291 * lbolt's cyclic, installed by clock_init().
293 static void lbolt_cyclic(void);
296 * Tunable to keep lbolt in cyclic driven mode. This will prevent the system
297 * from switching back to event driven, once it reaches cyclic mode.
299 static boolean_t lbolt_cyc_only = B_FALSE;
302 * Cache aligned, per CPU structure with lbolt usage statistics.
304 static lbolt_cpu_t *lb_cpu;
307 * Single, cache aligned, structure with all the information required by
308 * the lbolt implementation.
310 lbolt_info_t *lb_info;
313 int one_sec = 1; /* turned on once every second */
314 static int fsflushcnt; /* counter for t_fsflushr */
315 int dosynctodr = 1; /* patchable; enable/disable sync to TOD chip */
316 int tod_needsync = 0; /* need to sync tod chip with software time */
317 static int tod_broken = 0; /* clock chip doesn't work */
318 time_t boot_time = 0; /* Boot time in seconds since 1970 */
319 cyclic_id_t clock_cyclic; /* clock()'s cyclic_id */
320 cyclic_id_t deadman_cyclic; /* deadman()'s cyclic_id */
322 extern void clock_tick_schedule(int);
324 static int lgrp_ticks; /* counter to schedule lgrp load calcs */
327 * for tod fault detection
329 #define TOD_REF_FREQ ((longlong_t)(NANOSEC))
330 #define TOD_STALL_THRESHOLD (TOD_REF_FREQ * 3 / 2)
331 #define TOD_JUMP_THRESHOLD (TOD_REF_FREQ / 2)
332 #define TOD_FILTER_N 4
333 #define TOD_FILTER_SETTLE (4 * TOD_FILTER_N)
334 static enum tod_fault_type tod_faulted = TOD_NOFAULT;
336 static int tod_status_flag = 0; /* used by tod_validate() */
338 static hrtime_t prev_set_tick = 0; /* gethrtime() prior to tod_set() */
339 static time_t prev_set_tod = 0; /* tv_sec value passed to tod_set() */
341 /* patchable via /etc/system */
342 int tod_validate_enable = 1;
344 /* Diagnose/Limit messages about delay(9F) called from interrupt context */
345 int delay_from_interrupt_diagnose = 0;
346 volatile uint32_t delay_from_interrupt_msg = 20;
349 * On non-SPARC systems, TOD validation must be deferred until gethrtime
350 * returns non-zero values (after mach_clkinit's execution).
351 * On SPARC systems, it must be deferred until after hrtime_base
352 * and hres_last_tick are set (in the first invocation of hres_tick).
353 * Since in both cases the prerequisites occur before the invocation of
354 * tod_get() in clock(), the deferment is lifted there.
356 static boolean_t tod_validate_deferred = B_TRUE;
359 * tod_fault_table[] must be aligned with
360 * enum tod_fault_type in systm.h
362 static char *tod_fault_table[] = {
363 "Reversed", /* TOD_REVERSED */
364 "Stalled", /* TOD_STALLED */
365 "Jumped", /* TOD_JUMPED */
366 "Changed in Clock Rate", /* TOD_RATECHANGED */
367 "Is Read-Only" /* TOD_RDONLY */
369 * no strings needed for TOD_NOFAULT
374 * test hook for tod broken detection in tod_validate
376 int tod_unit_test = 0;
377 time_t tod_test_injector;
379 #define CLOCK_ADJ_HIST_SIZE 4
381 static int adj_hist_entry;
383 int64_t clock_adj_hist[CLOCK_ADJ_HIST_SIZE];
385 static void calcloadavg(int, uint64_t *);
386 static int genloadavg(struct loadavg_s *);
387 static void loadavg_update();
389 void (*cpucaps_clock_callout)() = NULL;
391 extern clock_t clock_tick_proc_max;
393 static int64_t deadman_counter = 0;
395 static void recompute_load_averages(void);
396 static void onesec_time_adjustments(void);
397 static void onesec_waiters(void);
399 cyclic_id_t recompute_load_averages_cyclic;
400 cyclic_id_t onesec_time_adjustments_cyclic;
401 cyclic_id_t onesec_waiters_cyclic;
403 static void
404 clock(void)
406 extern void set_freemem();
407 void (*funcp)();
408 int32_t ltemp;
409 int s;
411 if (panicstr)
412 return;
415 * Make sure that 'freemem' do not drift too far from the truth
417 set_freemem();
421 * Before the section which is repeated is executed, we do
422 * the time delta processing which occurs every clock tick
424 * There is additional processing which happens every time
425 * the nanosecond counter rolls over which is described
426 * below - see the section which begins with : if (one_sec)
428 * This section marks the beginning of the precision-kernel
429 * code fragment.
431 * First, compute the phase adjustment. If the low-order bits
432 * (time_phase) of the update overflow, bump the higher order
433 * bits (time_update).
435 time_phase += time_adj;
436 if (time_phase <= -FINEUSEC) {
437 ltemp = -time_phase / SCALE_PHASE;
438 time_phase += ltemp * SCALE_PHASE;
439 s = hr_clock_lock();
440 timedelta -= ltemp * (NANOSEC/MICROSEC);
441 hr_clock_unlock(s);
442 } else if (time_phase >= FINEUSEC) {
443 ltemp = time_phase / SCALE_PHASE;
444 time_phase -= ltemp * SCALE_PHASE;
445 s = hr_clock_lock();
446 timedelta += ltemp * (NANOSEC/MICROSEC);
447 hr_clock_unlock(s);
451 * End of precision-kernel code fragment which is processed
452 * every timer interrupt.
454 * Continue with the interrupt processing as scheduled.
457 clock_tick_schedule(one_sec);
460 * Check for a callout that needs be called from the clock
461 * thread to support the membership protocol in a clustered
462 * system. Copy the function pointer so that we can reset
463 * this to NULL if needed.
465 if ((funcp = cpucaps_clock_callout) != NULL)
466 (*funcp)();
469 static void
470 recompute_load_averages(void)
472 kthread_t *t;
473 uint_t nrunnable;
474 uint_t w_io;
475 cpu_t *cp;
476 cpupart_t *cpupart;
477 int i;
478 pgcnt_t maxswap, resv, free, avail;
481 * Count the number of runnable threads and the number waiting
482 * for some form of I/O to complete -- gets added to
483 * sysinfo.waiting. To know the state of the system, must add
484 * wait counts from all CPUs. Also add up the per-partition
485 * statistics.
488 w_io = 0;
489 nrunnable = 0;
492 * First count the threads waiting on kpreempt queues in each
493 * CPU partition.
496 cpupart = cp_list_head;
497 do {
498 uint_t cpupart_nrunnable = cpupart->cp_kp_queue.disp_nrunnable;
500 cpupart->cp_updates++;
501 nrunnable += cpupart_nrunnable;
502 cpupart->cp_nrunnable_cum += cpupart_nrunnable;
503 cpupart->cp_nrunning = 0;
504 cpupart->cp_nrunnable = cpupart_nrunnable;
505 } while ((cpupart = cpupart->cp_next) != cp_list_head);
508 /* Now count the per-CPU statistics. */
509 cp = cpu_list;
510 do {
511 uint_t cpu_nrunnable = cp->cpu_disp->disp_nrunnable;
513 nrunnable += cpu_nrunnable;
514 cpupart = cp->cpu_part;
515 cpupart->cp_nrunnable_cum += cpu_nrunnable;
516 cpupart->cp_nrunnable += cpu_nrunnable;
518 * Update user, system, and idle cpu times.
520 cpupart->cp_nrunning++;
522 * w_io is used to update sysinfo.waiting during
523 * one_second processing below. Only gather w_io
524 * information when we walk the list of cpus if we're
525 * going to perform one_second processing.
527 w_io += CPU_STATS(cp, sys.iowait);
529 if (cp->cpu_flags & CPU_EXISTS) {
530 int i, load, change;
531 hrtime_t intracct, intrused;
532 const hrtime_t maxnsec = 1000000000;
533 const int precision = 100;
536 * Estimate interrupt load on this cpu each second.
537 * Computes cpu_intrload as %utilization (0-99).
540 /* add up interrupt time from all micro states */
541 for (intracct = 0, i = 0; i < NCMSTATES; i++)
542 intracct += cp->cpu_intracct[i];
543 scalehrtime(&intracct);
545 /* compute nsec used in the past second */
546 intrused = intracct - cp->cpu_intrlast;
547 cp->cpu_intrlast = intracct;
549 /* limit the value for safety (and the first pass) */
550 if (intrused >= maxnsec)
551 intrused = maxnsec - 1;
553 /* calculate %time in interrupt */
554 load = (precision * intrused) / maxnsec;
555 ASSERT(load >= 0 && load < precision);
556 change = cp->cpu_intrload - load;
558 /* jump to new max, or decay the old max */
559 if (change < 0)
560 cp->cpu_intrload = load;
561 else if (change > 0)
562 cp->cpu_intrload -= (change + 3) / 4;
564 DTRACE_PROBE3(cpu_intrload,
565 cpu_t *, cp,
566 hrtime_t, intracct,
567 hrtime_t, intrused);
570 if (cp->cpu_flags & CPU_EXISTS) {
572 * When updating the lgroup's load average,
573 * account for the thread running on the CPU.
574 * If the CPU is the current one, then we need
575 * to account for the underlying thread which
576 * got the clock interrupt not the thread that is
577 * handling the interrupt and caculating the load
578 * average
580 t = cp->cpu_thread;
581 if (CPU == cp)
582 t = t->t_intr;
585 * Account for the load average for this thread if
586 * it isn't the idle thread or it is on the interrupt
587 * stack and not the current CPU handling the clock
588 * interrupt
590 if ((t && t != cp->cpu_idle_thread) || (CPU != cp &&
591 CPU_ON_INTR(cp))) {
592 if (t->t_lpl == cp->cpu_lpl) {
593 /* local thread */
594 cpu_nrunnable++;
595 } else {
597 * This is a remote thread, charge it
598 * against its home lgroup. Note that
599 * we notice that a thread is remote
600 * only if it's currently executing.
601 * This is a reasonable approximation,
602 * since queued remote threads are rare.
603 * Note also that if we didn't charge
604 * it to its home lgroup, remote
605 * execution would often make a system
606 * appear balanced even though it was
607 * not, and thread placement/migration
608 * would often not be done correctly.
610 lgrp_loadavg(t->t_lpl,
611 LGRP_LOADAVG_IN_THREAD_MAX, 0);
614 lgrp_loadavg(cp->cpu_lpl,
615 cpu_nrunnable * LGRP_LOADAVG_IN_THREAD_MAX, 1);
617 } while ((cp = cp->cpu_next) != cpu_list);
619 vminfo.freemem += freemem;
620 avail = MAX((spgcnt_t)(availrmem - swapfs_minfree), 0);
622 maxswap = k_anoninfo.ani_mem_resv + k_anoninfo.ani_max + avail;
623 /* Update ani_free */
624 set_anoninfo();
625 free = k_anoninfo.ani_free + avail;
626 resv = k_anoninfo.ani_phys_resv + k_anoninfo.ani_mem_resv;
628 vminfo.swap_resv += resv;
629 /* number of reserved and allocated pages */
630 #ifdef DEBUG
631 if (maxswap < free)
632 cmn_err(CE_WARN, "clock: maxswap < free");
633 if (maxswap < resv)
634 cmn_err(CE_WARN, "clock: maxswap < resv");
635 #endif
636 vminfo.swap_alloc += maxswap - free;
637 vminfo.swap_avail += maxswap - resv;
638 vminfo.swap_free += free;
639 vminfo.updates++;
641 if (nrunnable) {
642 sysinfo.runque += nrunnable;
643 sysinfo.runocc++;
645 if (nswapped) {
646 sysinfo.swpque += nswapped;
647 sysinfo.swpocc++;
649 sysinfo.waiting += w_io;
650 sysinfo.updates++;
653 * Wake up fsflush to write out DELWRI
654 * buffers, dirty pages and other cached
655 * administrative data, e.g. inodes.
657 if (--fsflushcnt <= 0) {
658 fsflushcnt = tune.t_fsflushr;
659 cv_signal(&fsflush_cv);
662 vmmeter();
663 calcloadavg(genloadavg(&loadavg), hp_avenrun);
664 for (i = 0; i < 3; i++)
666 * At the moment avenrun[] can only hold 31
667 * bits of load average as it is a signed
668 * int in the API. We need to ensure that
669 * hp_avenrun[i] >> (16 - FSHIFT) will not be
670 * too large. If it is, we put the largest value
671 * that we can use into avenrun[i]. This is
672 * kludgey, but about all we can do until we
673 * avenrun[] is declared as an array of uint64[]
675 if (hp_avenrun[i] < ((uint64_t)1<<(31+16-FSHIFT)))
676 avenrun[i] = (int32_t)(hp_avenrun[i] >>
677 (16 - FSHIFT));
678 else
679 avenrun[i] = 0x7fffffff;
681 cpupart = cp_list_head;
682 do {
683 calcloadavg(genloadavg(&cpupart->cp_loadavg),
684 cpupart->cp_hp_avenrun);
685 } while ((cpupart = cpupart->cp_next) != cp_list_head);
687 loadavg_update();
690 static void
691 onesec_time_adjustments(void)
693 int drift, absdrift;
694 timestruc_t tod;
695 int64_t lltemp;
696 clock_t now = LBOLT_NO_ACCOUNT; /* current tick */
697 int s;
700 * Beginning of precision-kernel code fragment executed
701 * every second.
703 * On rollover of the second the phase adjustment to be
704 * used for the next second is calculated. Also, the
705 * maximum error is increased by the tolerance. If the
706 * PPS frequency discipline code is present, the phase is
707 * increased to compensate for the CPU clock oscillator
708 * frequency error.
710 * On a 32-bit machine and given parameters in the timex.h
711 * header file, the maximum phase adjustment is +-512 ms
712 * and maximum frequency offset is (a tad less than)
713 * +-512 ppm. On a 64-bit machine, you shouldn't need to ask.
715 time_maxerror += time_tolerance / SCALE_USEC;
718 * Leap second processing. If in leap-insert state at
719 * the end of the day, the system clock is set back one
720 * second; if in leap-delete state, the system clock is
721 * set ahead one second. The microtime() routine or
722 * external clock driver will insure that reported time
723 * is always monotonic. The ugly divides should be
724 * replaced.
726 switch (time_state) {
728 case TIME_OK:
729 if (time_status & STA_INS)
730 time_state = TIME_INS;
731 else if (time_status & STA_DEL)
732 time_state = TIME_DEL;
733 break;
735 case TIME_INS:
736 if (hrestime.tv_sec % 86400 == 0) {
737 s = hr_clock_lock();
738 hrestime.tv_sec--;
739 hr_clock_unlock(s);
740 time_state = TIME_OOP;
742 break;
744 case TIME_DEL:
745 if ((hrestime.tv_sec + 1) % 86400 == 0) {
746 s = hr_clock_lock();
747 hrestime.tv_sec++;
748 hr_clock_unlock(s);
749 time_state = TIME_WAIT;
751 break;
753 case TIME_OOP:
754 time_state = TIME_WAIT;
755 break;
757 case TIME_WAIT:
758 if (!(time_status & (STA_INS | STA_DEL)))
759 time_state = TIME_OK;
760 default:
761 break;
765 * Compute the phase adjustment for the next second. In
766 * PLL mode, the offset is reduced by a fixed factor
767 * times the time constant. In FLL mode the offset is
768 * used directly. In either mode, the maximum phase
769 * adjustment for each second is clamped so as to spread
770 * the adjustment over not more than the number of
771 * seconds between updates.
773 if (time_offset == 0)
774 time_adj = 0;
775 else if (time_offset < 0) {
776 lltemp = -time_offset;
777 if (!(time_status & STA_FLL)) {
778 if ((1 << time_constant) >= SCALE_KG)
779 lltemp *= (1 << time_constant) /
780 SCALE_KG;
781 else
782 lltemp = (lltemp / SCALE_KG) >>
783 time_constant;
785 if (lltemp > (MAXPHASE / MINSEC) * SCALE_UPDATE)
786 lltemp = (MAXPHASE / MINSEC) * SCALE_UPDATE;
787 time_offset += lltemp;
788 time_adj = -(lltemp * SCALE_PHASE) / hz / SCALE_UPDATE;
789 } else {
790 lltemp = time_offset;
791 if (!(time_status & STA_FLL)) {
792 if ((1 << time_constant) >= SCALE_KG)
793 lltemp *= (1 << time_constant) /
794 SCALE_KG;
795 else
796 lltemp = (lltemp / SCALE_KG) >>
797 time_constant;
799 if (lltemp > (MAXPHASE / MINSEC) * SCALE_UPDATE)
800 lltemp = (MAXPHASE / MINSEC) * SCALE_UPDATE;
801 time_offset -= lltemp;
802 time_adj = (lltemp * SCALE_PHASE) / hz / SCALE_UPDATE;
806 * Compute the frequency estimate and additional phase
807 * adjustment due to frequency error for the next
808 * second. When the PPS signal is engaged, gnaw on the
809 * watchdog counter and update the frequency computed by
810 * the pll and the PPS signal.
812 pps_valid++;
813 if (pps_valid == PPS_VALID) {
814 pps_jitter = MAXTIME;
815 pps_stabil = MAXFREQ;
816 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
817 STA_PPSWANDER | STA_PPSERROR);
819 lltemp = time_freq + pps_freq;
821 if (lltemp)
822 time_adj += (lltemp * SCALE_PHASE) / (SCALE_USEC * hz);
825 * End of precision kernel-code fragment
827 * The section below should be modified if we are planning
828 * to use NTP for synchronization.
830 * Note: the clock synchronization code now assumes
831 * the following:
832 * - if dosynctodr is 1, then compute the drift between
833 * the tod chip and software time and adjust one or
834 * the other depending on the circumstances
836 * - if dosynctodr is 0, then the tod chip is independent
837 * of the software clock and should not be adjusted,
838 * but allowed to free run. this allows NTP to sync.
839 * hrestime without any interference from the tod chip.
842 tod_validate_deferred = B_FALSE;
843 mutex_enter(&tod_lock);
844 tod = tod_get();
845 drift = tod.tv_sec - hrestime.tv_sec;
846 absdrift = (drift >= 0) ? drift : -drift;
847 if (tod_needsync || absdrift > 1) {
848 int s;
849 if (absdrift > 2) {
850 if (!tod_broken && tod_faulted == TOD_NOFAULT) {
851 s = hr_clock_lock();
852 hrestime = tod;
853 membar_enter(); /* hrestime visible */
854 timedelta = 0;
855 timechanged++;
856 tod_needsync = 0;
857 hr_clock_unlock(s);
858 callout_hrestime();
861 } else {
862 if (tod_needsync || !dosynctodr) {
863 gethrestime(&tod);
864 tod_set(tod);
865 s = hr_clock_lock();
866 if (timedelta == 0)
867 tod_needsync = 0;
868 hr_clock_unlock(s);
869 } else {
871 * If the drift is 2 seconds on the
872 * money, then the TOD is adjusting
873 * the clock; record that.
875 clock_adj_hist[adj_hist_entry++ %
876 CLOCK_ADJ_HIST_SIZE] = now;
877 s = hr_clock_lock();
878 timedelta = (int64_t)drift*NANOSEC;
879 hr_clock_unlock(s);
883 time = gethrestime_sec(); /* for crusty old kmem readers */
884 mutex_exit(&tod_lock);
887 static void
888 onesec_waiters(void)
890 deadman_counter++;
893 * Wakeup the cageout thread waiters once per second.
896 one_sec = 0;
899 * Some drivers still depend on this... XXX
901 cv_broadcast(&lbolt_cv);
904 void
905 clock_init(void)
907 cyc_handler_t clk_hdlr, lbolt_hdlr,load_averages_hdlr;
908 cyc_time_t clk_when, lbolt_when, load_averages_when;
909 cyc_handler_t onesec_time_adjustments_hdlr, onesec_waiters_hdlr;
910 cyc_time_t onesec_time_adjustments_when, onesec_waiters_when;
911 int i, sz;
912 intptr_t buf;
915 * Setup handler and timer for the clock cyclic.
917 clk_hdlr.cyh_func = (cyc_func_t)clock;
918 clk_hdlr.cyh_level = CY_LOCK_LEVEL;
919 clk_hdlr.cyh_arg = NULL;
921 clk_when.cyt_when = 0;
922 clk_when.cyt_interval = nsec_per_tick;
925 * Setup handler and timer for load_averages cyclic.
928 load_averages_hdlr.cyh_func = (cyc_func_t)recompute_load_averages;
929 load_averages_hdlr.cyh_level = CY_LOCK_LEVEL;
930 load_averages_hdlr.cyh_arg = NULL;
932 load_averages_when.cyt_when = 0;
933 load_averages_when.cyt_interval = SEC2NSEC(1);
936 * Setup handler and timer for onesec_time_adjustments cyclic.
939 onesec_time_adjustments_hdlr.cyh_func = (cyc_func_t)onesec_time_adjustments;
940 onesec_time_adjustments_hdlr.cyh_level = CY_LOCK_LEVEL;
941 onesec_time_adjustments_hdlr.cyh_arg = NULL;
943 onesec_time_adjustments_when.cyt_when = 0;
944 onesec_time_adjustments_when.cyt_interval = SEC2NSEC(1);
947 * Setup handler and timer for onesec_waiters cyclic.
950 onesec_waiters_hdlr.cyh_func = (cyc_func_t)onesec_waiters;
951 onesec_waiters_hdlr.cyh_level = CY_LOCK_LEVEL;
952 onesec_waiters_hdlr.cyh_arg = NULL;
954 onesec_waiters_when.cyt_when = 0;
955 onesec_waiters_when.cyt_interval = SEC2NSEC(1);
958 * The lbolt cyclic will be reprogramed to fire at a nsec_per_tick
959 * interval to satisfy performance needs of the DDI lbolt consumers.
960 * It is off by default.
962 lbolt_hdlr.cyh_func = (cyc_func_t)lbolt_cyclic;
963 lbolt_hdlr.cyh_level = CY_LOCK_LEVEL;
964 lbolt_hdlr.cyh_arg = NULL;
966 lbolt_when.cyt_interval = nsec_per_tick;
969 * Allocate cache line aligned space for the per CPU lbolt data and
970 * lbolt info structures, and initialize them with their default
971 * values. Note that these structures are also cache line sized.
973 sz = sizeof (lbolt_info_t) + CPU_CACHE_COHERENCE_SIZE;
974 buf = (intptr_t)kmem_zalloc(sz, KM_SLEEP);
975 lb_info = (lbolt_info_t *)P2ROUNDUP(buf, CPU_CACHE_COHERENCE_SIZE);
977 if (hz != HZ_DEFAULT)
978 lb_info->lbi_thresh_interval = LBOLT_THRESH_INTERVAL *
979 hz/HZ_DEFAULT;
980 else
981 lb_info->lbi_thresh_interval = LBOLT_THRESH_INTERVAL;
983 lb_info->lbi_thresh_calls = LBOLT_THRESH_CALLS;
985 sz = (sizeof (lbolt_cpu_t) * max_ncpus) + CPU_CACHE_COHERENCE_SIZE;
986 buf = (intptr_t)kmem_zalloc(sz, KM_SLEEP);
987 lb_cpu = (lbolt_cpu_t *)P2ROUNDUP(buf, CPU_CACHE_COHERENCE_SIZE);
989 for (i = 0; i < max_ncpus; i++)
990 lb_cpu[i].lbc_counter = lb_info->lbi_thresh_calls;
993 * Install the softint used to switch between event and cyclic driven
994 * lbolt. We use a soft interrupt to make sure the context of the
995 * cyclic reprogram call is safe.
997 lbolt_softint_add();
1000 * Since the hybrid lbolt implementation is based on a hardware counter
1001 * that is reset at every hardware reboot and that we'd like to have
1002 * the lbolt value starting at zero after both a hardware and a fast
1003 * reboot, we calculate the number of clock ticks the system's been up
1004 * and store it in the lbi_debug_time field of the lbolt info structure.
1005 * The value of this field will be subtracted from lbolt before
1006 * returning it.
1008 lb_info->lbi_internal = lb_info->lbi_debug_time =
1009 (gethrtime()/nsec_per_tick);
1012 * lbolt_hybrid points at lbolt_bootstrap until now. The LBOLT_* macros
1013 * and lbolt_debug_{enter,return} use this value as an indication that
1014 * the initializaion above hasn't been completed. Setting lbolt_hybrid
1015 * to either lbolt_{cyclic,event}_driven here signals those code paths
1016 * that the lbolt related structures can be used.
1018 if (lbolt_cyc_only) {
1019 lbolt_when.cyt_when = 0;
1020 lbolt_hybrid = lbolt_cyclic_driven;
1021 } else {
1022 lbolt_when.cyt_when = CY_INFINITY;
1023 lbolt_hybrid = lbolt_event_driven;
1027 * Grab cpu_lock and install all six cyclics.
1029 mutex_enter(&cpu_lock);
1031 clock_cyclic = cyclic_add(&clk_hdlr, &clk_when);
1032 lb_info->id.lbi_cyclic_id = cyclic_add(&lbolt_hdlr, &lbolt_when);
1033 recompute_load_averages_cyclic =
1034 cyclic_add(&load_averages_hdlr, &load_averages_when);
1035 onesec_time_adjustments_cyclic =
1036 cyclic_add(&onesec_time_adjustments_hdlr, &onesec_time_adjustments_when);
1037 onesec_waiters_cyclic = cyclic_add(&onesec_waiters_hdlr, &onesec_waiters_when);
1039 mutex_exit(&cpu_lock);
1043 * Called before calcloadavg to get 10-sec moving loadavg together
1046 static int
1047 genloadavg(struct loadavg_s *avgs)
1049 int avg;
1050 int spos; /* starting position */
1051 int cpos; /* moving current position */
1052 int i;
1053 int slen;
1054 hrtime_t hr_avg;
1056 /* 10-second snapshot, calculate first positon */
1057 if (avgs->lg_len == 0) {
1058 return (0);
1060 slen = avgs->lg_len < S_MOVAVG_SZ ? avgs->lg_len : S_MOVAVG_SZ;
1062 spos = (avgs->lg_cur - 1) >= 0 ? avgs->lg_cur - 1 :
1063 S_LOADAVG_SZ + (avgs->lg_cur - 1);
1064 for (i = hr_avg = 0; i < slen; i++) {
1065 cpos = (spos - i) >= 0 ? spos - i : S_LOADAVG_SZ + (spos - i);
1066 hr_avg += avgs->lg_loads[cpos];
1069 hr_avg = hr_avg / slen;
1070 avg = hr_avg / (NANOSEC / LGRP_LOADAVG_IN_THREAD_MAX);
1072 return (avg);
1076 * Run every second from clock () to update the loadavg count available to the
1077 * system and cpu-partitions.
1079 * This works by sampling the previous usr, sys, wait time elapsed,
1080 * computing a delta, and adding that delta to the elapsed usr, sys,
1081 * wait increase.
1084 static void
1085 loadavg_update()
1087 cpu_t *cp;
1088 cpupart_t *cpupart;
1089 hrtime_t cpu_total;
1090 int prev;
1092 cp = cpu_list;
1093 loadavg.lg_total = 0;
1096 * first pass totals up per-cpu statistics for system and cpu
1097 * partitions
1100 do {
1101 struct loadavg_s *lavg;
1103 lavg = &cp->cpu_loadavg;
1105 cpu_total = cp->cpu_acct[CMS_USER] +
1106 cp->cpu_acct[CMS_SYSTEM] + cp->cpu_waitrq;
1107 /* compute delta against last total */
1108 scalehrtime(&cpu_total);
1109 prev = (lavg->lg_cur - 1) >= 0 ? lavg->lg_cur - 1 :
1110 S_LOADAVG_SZ + (lavg->lg_cur - 1);
1111 if (lavg->lg_loads[prev] <= 0) {
1112 lavg->lg_loads[lavg->lg_cur] = cpu_total;
1113 cpu_total = 0;
1114 } else {
1115 lavg->lg_loads[lavg->lg_cur] = cpu_total;
1116 cpu_total = cpu_total - lavg->lg_loads[prev];
1117 if (cpu_total < 0)
1118 cpu_total = 0;
1121 lavg->lg_cur = (lavg->lg_cur + 1) % S_LOADAVG_SZ;
1122 lavg->lg_len = (lavg->lg_len + 1) < S_LOADAVG_SZ ?
1123 lavg->lg_len + 1 : S_LOADAVG_SZ;
1125 loadavg.lg_total += cpu_total;
1126 cp->cpu_part->cp_loadavg.lg_total += cpu_total;
1128 } while ((cp = cp->cpu_next) != cpu_list);
1130 loadavg.lg_loads[loadavg.lg_cur] = loadavg.lg_total;
1131 loadavg.lg_cur = (loadavg.lg_cur + 1) % S_LOADAVG_SZ;
1132 loadavg.lg_len = (loadavg.lg_len + 1) < S_LOADAVG_SZ ?
1133 loadavg.lg_len + 1 : S_LOADAVG_SZ;
1135 * Second pass updates counts
1137 cpupart = cp_list_head;
1139 do {
1140 struct loadavg_s *lavg;
1142 lavg = &cpupart->cp_loadavg;
1143 lavg->lg_loads[lavg->lg_cur] = lavg->lg_total;
1144 lavg->lg_total = 0;
1145 lavg->lg_cur = (lavg->lg_cur + 1) % S_LOADAVG_SZ;
1146 lavg->lg_len = (lavg->lg_len + 1) < S_LOADAVG_SZ ?
1147 lavg->lg_len + 1 : S_LOADAVG_SZ;
1149 } while ((cpupart = cpupart->cp_next) != cp_list_head);
1152 * Third pass totals up per-zone statistics.
1154 zone_loadavg_update();
1158 * clock_update() - local clock update
1160 * This routine is called by ntp_adjtime() to update the local clock
1161 * phase and frequency. The implementation is of an
1162 * adaptive-parameter, hybrid phase/frequency-lock loop (PLL/FLL). The
1163 * routine computes new time and frequency offset estimates for each
1164 * call. The PPS signal itself determines the new time offset,
1165 * instead of the calling argument. Presumably, calls to
1166 * ntp_adjtime() occur only when the caller believes the local clock
1167 * is valid within some bound (+-128 ms with NTP). If the caller's
1168 * time is far different than the PPS time, an argument will ensue,
1169 * and it's not clear who will lose.
1171 * For uncompensated quartz crystal oscillatores and nominal update
1172 * intervals less than 1024 s, operation should be in phase-lock mode
1173 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1174 * intervals greater than this, operation should be in frequency-lock
1175 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1177 * Note: mutex(&tod_lock) is in effect.
1179 void
1180 clock_update(int offset)
1182 int ltemp, mtemp, s;
1184 ASSERT(MUTEX_HELD(&tod_lock));
1186 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1187 return;
1188 ltemp = offset;
1189 if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL))
1190 ltemp = pps_offset;
1193 * Scale the phase adjustment and clamp to the operating range.
1195 if (ltemp > MAXPHASE)
1196 time_offset = MAXPHASE * SCALE_UPDATE;
1197 else if (ltemp < -MAXPHASE)
1198 time_offset = -(MAXPHASE * SCALE_UPDATE);
1199 else
1200 time_offset = ltemp * SCALE_UPDATE;
1203 * Select whether the frequency is to be controlled and in which
1204 * mode (PLL or FLL). Clamp to the operating range. Ugly
1205 * multiply/divide should be replaced someday.
1207 if (time_status & STA_FREQHOLD || time_reftime == 0)
1208 time_reftime = hrestime.tv_sec;
1210 mtemp = hrestime.tv_sec - time_reftime;
1211 time_reftime = hrestime.tv_sec;
1213 if (time_status & STA_FLL) {
1214 if (mtemp >= MINSEC) {
1215 ltemp = ((time_offset / mtemp) * (SCALE_USEC /
1216 SCALE_UPDATE));
1217 if (ltemp)
1218 time_freq += ltemp / SCALE_KH;
1220 } else {
1221 if (mtemp < MAXSEC) {
1222 ltemp *= mtemp;
1223 if (ltemp)
1224 time_freq += (int)(((int64_t)ltemp *
1225 SCALE_USEC) / SCALE_KF)
1226 / (1 << (time_constant * 2));
1229 if (time_freq > time_tolerance)
1230 time_freq = time_tolerance;
1231 else if (time_freq < -time_tolerance)
1232 time_freq = -time_tolerance;
1234 s = hr_clock_lock();
1235 tod_needsync = 1;
1236 hr_clock_unlock(s);
1240 * ddi_hardpps() - discipline CPU clock oscillator to external PPS signal
1242 * This routine is called at each PPS interrupt in order to discipline
1243 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1244 * and leaves it in a handy spot for the clock() routine. It
1245 * integrates successive PPS phase differences and calculates the
1246 * frequency offset. This is used in clock() to discipline the CPU
1247 * clock oscillator so that intrinsic frequency error is cancelled out.
1248 * The code requires the caller to capture the time and hardware counter
1249 * value at the on-time PPS signal transition.
1251 * Note that, on some Unix systems, this routine runs at an interrupt
1252 * priority level higher than the timer interrupt routine clock().
1253 * Therefore, the variables used are distinct from the clock()
1254 * variables, except for certain exceptions: The PPS frequency pps_freq
1255 * and phase pps_offset variables are determined by this routine and
1256 * updated atomically. The time_tolerance variable can be considered a
1257 * constant, since it is infrequently changed, and then only when the
1258 * PPS signal is disabled. The watchdog counter pps_valid is updated
1259 * once per second by clock() and is atomically cleared in this
1260 * routine.
1262 * tvp is the time of the last tick; usec is a microsecond count since the
1263 * last tick.
1265 * Note: In Solaris systems, the tick value is actually given by
1266 * usec_per_tick. This is called from the serial driver cdintr(),
1267 * or equivalent, at a high PIL. Because the kernel keeps a
1268 * highresolution time, the following code can accept either
1269 * the traditional argument pair, or the current highres timestamp
1270 * in tvp and zero in usec.
1272 void
1273 ddi_hardpps(struct timeval *tvp, int usec)
1275 int u_usec, v_usec, bigtick;
1276 time_t cal_sec;
1277 int cal_usec;
1280 * An occasional glitch can be produced when the PPS interrupt
1281 * occurs in the clock() routine before the time variable is
1282 * updated. Here the offset is discarded when the difference
1283 * between it and the last one is greater than tick/2, but not
1284 * if the interval since the first discard exceeds 30 s.
1286 time_status |= STA_PPSSIGNAL;
1287 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1288 pps_valid = 0;
1289 u_usec = -tvp->tv_usec;
1290 if (u_usec < -(MICROSEC/2))
1291 u_usec += MICROSEC;
1292 v_usec = pps_offset - u_usec;
1293 if (v_usec < 0)
1294 v_usec = -v_usec;
1295 if (v_usec > (usec_per_tick >> 1)) {
1296 if (pps_glitch > MAXGLITCH) {
1297 pps_glitch = 0;
1298 pps_tf[2] = u_usec;
1299 pps_tf[1] = u_usec;
1300 } else {
1301 pps_glitch++;
1302 u_usec = pps_offset;
1304 } else
1305 pps_glitch = 0;
1308 * A three-stage median filter is used to help deglitch the pps
1309 * time. The median sample becomes the time offset estimate; the
1310 * difference between the other two samples becomes the time
1311 * dispersion (jitter) estimate.
1313 pps_tf[2] = pps_tf[1];
1314 pps_tf[1] = pps_tf[0];
1315 pps_tf[0] = u_usec;
1316 if (pps_tf[0] > pps_tf[1]) {
1317 if (pps_tf[1] > pps_tf[2]) {
1318 pps_offset = pps_tf[1]; /* 0 1 2 */
1319 v_usec = pps_tf[0] - pps_tf[2];
1320 } else if (pps_tf[2] > pps_tf[0]) {
1321 pps_offset = pps_tf[0]; /* 2 0 1 */
1322 v_usec = pps_tf[2] - pps_tf[1];
1323 } else {
1324 pps_offset = pps_tf[2]; /* 0 2 1 */
1325 v_usec = pps_tf[0] - pps_tf[1];
1327 } else {
1328 if (pps_tf[1] < pps_tf[2]) {
1329 pps_offset = pps_tf[1]; /* 2 1 0 */
1330 v_usec = pps_tf[2] - pps_tf[0];
1331 } else if (pps_tf[2] < pps_tf[0]) {
1332 pps_offset = pps_tf[0]; /* 1 0 2 */
1333 v_usec = pps_tf[1] - pps_tf[2];
1334 } else {
1335 pps_offset = pps_tf[2]; /* 1 2 0 */
1336 v_usec = pps_tf[1] - pps_tf[0];
1339 if (v_usec > MAXTIME)
1340 pps_jitcnt++;
1341 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1342 pps_jitter += v_usec / (1 << PPS_AVG);
1343 if (pps_jitter > (MAXTIME >> 1))
1344 time_status |= STA_PPSJITTER;
1347 * During the calibration interval adjust the starting time when
1348 * the tick overflows. At the end of the interval compute the
1349 * duration of the interval and the difference of the hardware
1350 * counters at the beginning and end of the interval. This code
1351 * is deliciously complicated by the fact valid differences may
1352 * exceed the value of tick when using long calibration
1353 * intervals and small ticks. Note that the counter can be
1354 * greater than tick if caught at just the wrong instant, but
1355 * the values returned and used here are correct.
1357 bigtick = (int)usec_per_tick * SCALE_USEC;
1358 pps_usec -= pps_freq;
1359 if (pps_usec >= bigtick)
1360 pps_usec -= bigtick;
1361 if (pps_usec < 0)
1362 pps_usec += bigtick;
1363 pps_time.tv_sec++;
1364 pps_count++;
1365 if (pps_count < (1 << pps_shift))
1366 return;
1367 pps_count = 0;
1368 pps_calcnt++;
1369 u_usec = usec * SCALE_USEC;
1370 v_usec = pps_usec - u_usec;
1371 if (v_usec >= bigtick >> 1)
1372 v_usec -= bigtick;
1373 if (v_usec < -(bigtick >> 1))
1374 v_usec += bigtick;
1375 if (v_usec < 0)
1376 v_usec = -(-v_usec >> pps_shift);
1377 else
1378 v_usec = v_usec >> pps_shift;
1379 pps_usec = u_usec;
1380 cal_sec = tvp->tv_sec;
1381 cal_usec = tvp->tv_usec;
1382 cal_sec -= pps_time.tv_sec;
1383 cal_usec -= pps_time.tv_usec;
1384 if (cal_usec < 0) {
1385 cal_usec += MICROSEC;
1386 cal_sec--;
1388 pps_time = *tvp;
1391 * Check for lost interrupts, noise, excessive jitter and
1392 * excessive frequency error. The number of timer ticks during
1393 * the interval may vary +-1 tick. Add to this a margin of one
1394 * tick for the PPS signal jitter and maximum frequency
1395 * deviation. If the limits are exceeded, the calibration
1396 * interval is reset to the minimum and we start over.
1398 u_usec = (int)usec_per_tick << 1;
1399 if (!((cal_sec == -1 && cal_usec > (MICROSEC - u_usec)) ||
1400 (cal_sec == 0 && cal_usec < u_usec)) ||
1401 v_usec > time_tolerance || v_usec < -time_tolerance) {
1402 pps_errcnt++;
1403 pps_shift = PPS_SHIFT;
1404 pps_intcnt = 0;
1405 time_status |= STA_PPSERROR;
1406 return;
1410 * A three-stage median filter is used to help deglitch the pps
1411 * frequency. The median sample becomes the frequency offset
1412 * estimate; the difference between the other two samples
1413 * becomes the frequency dispersion (stability) estimate.
1415 pps_ff[2] = pps_ff[1];
1416 pps_ff[1] = pps_ff[0];
1417 pps_ff[0] = v_usec;
1418 if (pps_ff[0] > pps_ff[1]) {
1419 if (pps_ff[1] > pps_ff[2]) {
1420 u_usec = pps_ff[1]; /* 0 1 2 */
1421 v_usec = pps_ff[0] - pps_ff[2];
1422 } else if (pps_ff[2] > pps_ff[0]) {
1423 u_usec = pps_ff[0]; /* 2 0 1 */
1424 v_usec = pps_ff[2] - pps_ff[1];
1425 } else {
1426 u_usec = pps_ff[2]; /* 0 2 1 */
1427 v_usec = pps_ff[0] - pps_ff[1];
1429 } else {
1430 if (pps_ff[1] < pps_ff[2]) {
1431 u_usec = pps_ff[1]; /* 2 1 0 */
1432 v_usec = pps_ff[2] - pps_ff[0];
1433 } else if (pps_ff[2] < pps_ff[0]) {
1434 u_usec = pps_ff[0]; /* 1 0 2 */
1435 v_usec = pps_ff[1] - pps_ff[2];
1436 } else {
1437 u_usec = pps_ff[2]; /* 1 2 0 */
1438 v_usec = pps_ff[1] - pps_ff[0];
1443 * Here the frequency dispersion (stability) is updated. If it
1444 * is less than one-fourth the maximum (MAXFREQ), the frequency
1445 * offset is updated as well, but clamped to the tolerance. It
1446 * will be processed later by the clock() routine.
1448 v_usec = (v_usec >> 1) - pps_stabil;
1449 if (v_usec < 0)
1450 pps_stabil -= -v_usec >> PPS_AVG;
1451 else
1452 pps_stabil += v_usec >> PPS_AVG;
1453 if (pps_stabil > MAXFREQ >> 2) {
1454 pps_stbcnt++;
1455 time_status |= STA_PPSWANDER;
1456 return;
1458 if (time_status & STA_PPSFREQ) {
1459 if (u_usec < 0) {
1460 pps_freq -= -u_usec >> PPS_AVG;
1461 if (pps_freq < -time_tolerance)
1462 pps_freq = -time_tolerance;
1463 u_usec = -u_usec;
1464 } else {
1465 pps_freq += u_usec >> PPS_AVG;
1466 if (pps_freq > time_tolerance)
1467 pps_freq = time_tolerance;
1472 * Here the calibration interval is adjusted. If the maximum
1473 * time difference is greater than tick / 4, reduce the interval
1474 * by half. If this is not the case for four consecutive
1475 * intervals, double the interval.
1477 if (u_usec << pps_shift > bigtick >> 2) {
1478 pps_intcnt = 0;
1479 if (pps_shift > PPS_SHIFT)
1480 pps_shift--;
1481 } else if (pps_intcnt >= 4) {
1482 pps_intcnt = 0;
1483 if (pps_shift < PPS_SHIFTMAX)
1484 pps_shift++;
1485 } else
1486 pps_intcnt++;
1489 * If recovering from kmdb, then make sure the tod chip gets resynced.
1490 * If we took an early exit above, then we don't yet have a stable
1491 * calibration signal to lock onto, so don't mark the tod for sync
1492 * until we get all the way here.
1495 int s = hr_clock_lock();
1497 tod_needsync = 1;
1498 hr_clock_unlock(s);
1503 * Handle clock tick processing for a thread.
1504 * Check for timer action, enforce CPU rlimit, do profiling etc.
1506 void
1507 clock_tick(kthread_t *t, int pending)
1509 struct proc *pp;
1510 klwp_id_t lwp;
1511 struct as *as;
1512 clock_t ticks;
1513 int poke = 0; /* notify another CPU */
1514 int user_mode;
1515 size_t rss;
1516 int i, total_usec, usec;
1517 rctl_qty_t secs;
1519 ASSERT(pending > 0);
1521 /* Must be operating on a lwp/thread */
1522 if ((lwp = ttolwp(t)) == NULL) {
1523 panic("clock_tick: no lwp");
1524 /*NOTREACHED*/
1527 for (i = 0; i < pending; i++) {
1528 CL_TICK(t); /* Class specific tick processing */
1529 DTRACE_SCHED1(tick, kthread_t *, t);
1532 pp = ttoproc(t);
1534 /* pp->p_lock makes sure that the thread does not exit */
1535 ASSERT(MUTEX_HELD(&pp->p_lock));
1537 user_mode = (lwp->lwp_state == LWP_USER);
1539 ticks = (pp->p_utime + pp->p_stime) % hz;
1541 * Update process times. Should use high res clock and state
1542 * changes instead of statistical sampling method. XXX
1544 if (user_mode) {
1545 pp->p_utime += pending;
1546 } else {
1547 pp->p_stime += pending;
1550 pp->p_ttime += pending;
1551 as = pp->p_as;
1554 * Update user profiling statistics. Get the pc from the
1555 * lwp when the AST happens.
1557 if (pp->p_prof.pr_scale) {
1558 atomic_add_32(&lwp->lwp_oweupc, (int32_t)pending);
1559 if (user_mode) {
1560 poke = 1;
1561 aston(t);
1566 * If CPU was in user state, process lwp-virtual time
1567 * interval timer. The value passed to itimerdecr() has to be
1568 * in microseconds and has to be less than one second. Hence
1569 * this loop.
1571 total_usec = usec_per_tick * pending;
1572 while (total_usec > 0) {
1573 usec = MIN(total_usec, (MICROSEC - 1));
1574 if (user_mode &&
1575 timerisset(&lwp->lwp_timer[ITIMER_VIRTUAL].it_value) &&
1576 itimerdecr(&lwp->lwp_timer[ITIMER_VIRTUAL], usec) == 0) {
1577 poke = 1;
1578 sigtoproc(pp, t, SIGVTALRM);
1580 total_usec -= usec;
1584 * If CPU was in user state, process lwp-profile
1585 * interval timer.
1587 total_usec = usec_per_tick * pending;
1588 while (total_usec > 0) {
1589 usec = MIN(total_usec, (MICROSEC - 1));
1590 if (timerisset(&lwp->lwp_timer[ITIMER_PROF].it_value) &&
1591 itimerdecr(&lwp->lwp_timer[ITIMER_PROF], usec) == 0) {
1592 poke = 1;
1593 sigtoproc(pp, t, SIGPROF);
1595 total_usec -= usec;
1599 * Enforce CPU resource controls:
1600 * (a) process.max-cpu-time resource control
1602 * Perform the check only if we have accumulated more a second.
1604 if ((ticks + pending) >= hz) {
1605 (void) rctl_test(rctlproc_legacy[RLIMIT_CPU], pp->p_rctls, pp,
1606 (pp->p_utime + pp->p_stime)/hz, RCA_UNSAFE_SIGINFO);
1610 * (b) task.max-cpu-time resource control
1612 * If we have accumulated enough ticks, increment the task CPU
1613 * time usage and test for the resource limit. This minimizes the
1614 * number of calls to the rct_test(). The task CPU time mutex
1615 * is highly contentious as many processes can be sharing a task.
1617 if (pp->p_ttime >= clock_tick_proc_max) {
1618 secs = task_cpu_time_incr(pp->p_task, pp->p_ttime);
1619 pp->p_ttime = 0;
1620 if (secs) {
1621 (void) rctl_test(rc_task_cpu_time, pp->p_task->tk_rctls,
1622 pp, secs, RCA_UNSAFE_SIGINFO);
1627 * Update memory usage for the currently running process.
1629 rss = rm_asrss(as);
1630 PTOU(pp)->u_mem += rss;
1631 if (rss > PTOU(pp)->u_mem_max)
1632 PTOU(pp)->u_mem_max = rss;
1635 * Notify the CPU the thread is running on.
1637 if (poke && t->t_cpu != CPU)
1638 poke_cpu(t->t_cpu->cpu_id);
1641 void
1642 profil_tick(uintptr_t upc)
1644 int ticks;
1645 proc_t *p = ttoproc(curthread);
1646 klwp_t *lwp = ttolwp(curthread);
1647 struct prof *pr = &p->p_prof;
1649 do {
1650 ticks = lwp->lwp_oweupc;
1651 } while (atomic_cas_32(&lwp->lwp_oweupc, ticks, 0) != ticks);
1653 mutex_enter(&p->p_pflock);
1654 if (pr->pr_scale >= 2 && upc >= pr->pr_off) {
1656 * Old-style profiling
1658 uint16_t *slot = pr->pr_base;
1659 uint16_t old, new;
1660 if (pr->pr_scale != 2) {
1661 uintptr_t delta = upc - pr->pr_off;
1662 uintptr_t byteoff = ((delta >> 16) * pr->pr_scale) +
1663 (((delta & 0xffff) * pr->pr_scale) >> 16);
1664 if (byteoff >= (uintptr_t)pr->pr_size) {
1665 mutex_exit(&p->p_pflock);
1666 return;
1668 slot += byteoff / sizeof (uint16_t);
1670 if (fuword16(slot, &old) < 0 ||
1671 (new = old + ticks) > SHRT_MAX ||
1672 suword16(slot, new) < 0) {
1673 pr->pr_scale = 0;
1675 } else if (pr->pr_scale == 1) {
1677 * PC Sampling
1679 model_t model = lwp_getdatamodel(lwp);
1680 int result;
1681 while (ticks-- > 0) {
1682 if (pr->pr_samples == pr->pr_size) {
1683 /* buffer full, turn off sampling */
1684 pr->pr_scale = 0;
1685 break;
1687 switch (SIZEOF_PTR(model)) {
1688 case sizeof (uint32_t):
1689 result = suword32(pr->pr_base, (uint32_t)upc);
1690 break;
1691 #ifdef _LP64
1692 case sizeof (uint64_t):
1693 result = suword64(pr->pr_base, (uint64_t)upc);
1694 break;
1695 #endif
1696 default:
1697 cmn_err(CE_WARN, "profil_tick: unexpected "
1698 "data model");
1699 result = -1;
1700 break;
1702 if (result != 0) {
1703 pr->pr_scale = 0;
1704 break;
1706 pr->pr_base = (caddr_t)pr->pr_base + SIZEOF_PTR(model);
1707 pr->pr_samples++;
1710 mutex_exit(&p->p_pflock);
1713 static void
1714 delay_wakeup(void *arg)
1716 kthread_t *t = arg;
1718 mutex_enter(&t->t_delay_lock);
1719 cv_signal(&t->t_delay_cv);
1720 mutex_exit(&t->t_delay_lock);
1724 * The delay(9F) man page indicates that it can only be called from user or
1725 * kernel context - detect and diagnose bad calls. The following macro will
1726 * produce a limited number of messages identifying bad callers. This is done
1727 * in a macro so that caller() is meaningful. When a bad caller is identified,
1728 * switching to 'drv_usecwait(TICK_TO_USEC(ticks));' may be appropriate.
1730 #define DELAY_CONTEXT_CHECK() { \
1731 uint32_t m; \
1732 char *f; \
1733 ulong_t off; \
1735 m = delay_from_interrupt_msg; \
1736 if (delay_from_interrupt_diagnose && servicing_interrupt() && \
1737 !panicstr && !devinfo_freeze && \
1738 atomic_cas_32(&delay_from_interrupt_msg, m ? m : 1, m-1)) { \
1739 f = modgetsymname((uintptr_t)caller(), &off); \
1740 cmn_err(CE_WARN, "delay(9F) called from " \
1741 "interrupt context: %s`%s", \
1742 mod_containing_pc(caller()), f ? f : "..."); \
1747 * delay_common: common delay code.
1749 static void
1750 delay_common(clock_t ticks)
1752 kthread_t *t = curthread;
1753 clock_t deadline;
1754 clock_t timeleft;
1755 callout_id_t id;
1757 /* If timeouts aren't running all we can do is spin. */
1758 if (panicstr || devinfo_freeze) {
1759 /* Convert delay(9F) call into drv_usecwait(9F) call. */
1760 if (ticks > 0)
1761 drv_usecwait(TICK_TO_USEC(ticks));
1762 return;
1765 deadline = ddi_get_lbolt() + ticks;
1766 while ((timeleft = deadline - ddi_get_lbolt()) > 0) {
1767 mutex_enter(&t->t_delay_lock);
1768 id = timeout_default(delay_wakeup, t, timeleft);
1769 cv_wait(&t->t_delay_cv, &t->t_delay_lock);
1770 mutex_exit(&t->t_delay_lock);
1771 (void) untimeout_default(id, 0);
1776 * Delay specified number of clock ticks.
1778 void
1779 delay(clock_t ticks)
1781 DELAY_CONTEXT_CHECK();
1783 delay_common(ticks);
1787 * Delay a random number of clock ticks between 1 and ticks.
1789 void
1790 delay_random(clock_t ticks)
1792 int r;
1794 DELAY_CONTEXT_CHECK();
1796 (void) random_get_pseudo_bytes((void *)&r, sizeof (r));
1797 if (ticks == 0)
1798 ticks = 1;
1799 ticks = (r % ticks) + 1;
1800 delay_common(ticks);
1804 * Like delay, but interruptible by a signal.
1807 delay_sig(clock_t ticks)
1809 kthread_t *t = curthread;
1810 clock_t deadline;
1811 clock_t rc;
1813 /* If timeouts aren't running all we can do is spin. */
1814 if (panicstr || devinfo_freeze) {
1815 if (ticks > 0)
1816 drv_usecwait(TICK_TO_USEC(ticks));
1817 return (0);
1820 deadline = ddi_get_lbolt() + ticks;
1821 mutex_enter(&t->t_delay_lock);
1822 do {
1823 rc = cv_timedwait_sig(&t->t_delay_cv,
1824 &t->t_delay_lock, deadline);
1825 /* loop until past deadline or signaled */
1826 } while (rc > 0);
1827 mutex_exit(&t->t_delay_lock);
1828 if (rc == 0)
1829 return (EINTR);
1830 return (0);
1833 static void
1834 ddi_sleep_common(hrtime_t delay, hrtime_t resolution)
1836 kthread_t *t = curthread;
1837 hrtime_t deadline;
1838 callout_id_t id;
1839 hrtime_t tmp;
1841 /* If timeouts aren't running all we can do is spin. */
1842 if (panicstr || devinfo_freeze) {
1843 /* Convert ddi_*sleep(9F) call into drv_usecwait(9F) call. */
1844 if (NSEC2USEC(delay) > 0)
1845 drv_usecwait(NSEC2USEC(delay));
1846 return;
1850 * TODO: does this need to be in a loop checking that we didn't get
1851 * woken up too early?
1853 mutex_enter(&t->t_delay_lock);
1854 tmp = gethrtime();
1855 id = timeout_generic(CALLOUT_NORMAL, delay_wakeup, t, delay,
1856 resolution, CALLOUT_FLAG_ROUNDUP);
1857 cv_wait(&t->t_delay_cv, &t->t_delay_lock);
1858 mutex_exit(&t->t_delay_lock);
1859 (void) untimeout_generic(id, 0);
1860 if (gethrtime() - tmp < delay)
1861 cmn_err(CE_WARN, "%s returned too soon (wanted %llu, got %llu)",
1862 __func__, delay, gethrtime() - tmp);
1865 void
1866 ddi_sleep(clock_t secs)
1868 hrtime_t res;
1871 * We don't want to use 1 s resulution unconditionally because of
1872 * how it is used for rounding up the deadline. With 1 s
1873 * resolution, a sleep of 1 second can take anywhere from 1 to
1874 * 1.999999999 seconds on an idle system. This seems unacceptable,
1875 * and so we use either 100 ms or 10% of sleep interval as the
1876 * resolution - whichever is smaller.
1878 * (There is a similar issue with the milli- and micro- sleep
1879 * functions, but somehow an extra 1 ms or 1us doesn't seem as bad.)
1881 if (secs > 0)
1882 res = MIN(100000000 /* 100 ms */, SEC2NSEC(secs) / 10);
1883 else
1884 res = 100000000; /* 100 ms */
1886 ddi_sleep_common(SEC2NSEC(secs), res);
1889 void
1890 ddi_msleep(clock_t msecs)
1892 ddi_sleep_common(MSEC2NSEC(msecs), 1000000 /* 1 ms */);
1895 void
1896 ddi_usleep(clock_t usecs)
1898 ddi_sleep_common(USEC2NSEC(usecs), 1000 /* 1 us */);
1902 #define SECONDS_PER_DAY 86400
1905 * Initialize the system time based on the TOD chip. approx is used as
1906 * an approximation of time (e.g. from the filesystem) in the event that
1907 * the TOD chip has been cleared or is unresponsive. An approx of -1
1908 * means the filesystem doesn't keep time.
1910 void
1911 clkset(time_t approx)
1913 timestruc_t ts;
1914 int spl;
1915 int set_clock = 0;
1917 mutex_enter(&tod_lock);
1918 ts = tod_get();
1920 if (ts.tv_sec > 365 * SECONDS_PER_DAY) {
1922 * If the TOD chip is reporting some time after 1971,
1923 * then it probably didn't lose power or become otherwise
1924 * cleared in the recent past; check to assure that
1925 * the time coming from the filesystem isn't in the future
1926 * according to the TOD chip.
1928 if (approx != -1 && approx > ts.tv_sec) {
1929 cmn_err(CE_WARN, "Last shutdown is later "
1930 "than time on time-of-day chip; check date.");
1932 } else {
1934 * If the TOD chip isn't giving correct time, set it to the
1935 * greater of i) approx and ii) 1987. That way if approx
1936 * is negative or is earlier than 1987, we set the clock
1937 * back to a time when Oliver North, ALF and Dire Straits
1938 * were all on the collective brain: 1987.
1940 timestruc_t tmp;
1941 time_t diagnose_date = (1987 - 1970) * 365 * SECONDS_PER_DAY;
1942 ts.tv_sec = (approx > diagnose_date ? approx : diagnose_date);
1943 ts.tv_nsec = 0;
1946 * Attempt to write the new time to the TOD chip. Set spl high
1947 * to avoid getting preempted between the tod_set and tod_get.
1949 spl = splhi();
1950 tod_set(ts);
1951 tmp = tod_get();
1952 splx(spl);
1954 if (tmp.tv_sec != ts.tv_sec && tmp.tv_sec != ts.tv_sec + 1) {
1955 tod_broken = 1;
1956 dosynctodr = 0;
1957 cmn_err(CE_WARN, "Time-of-day chip unresponsive.");
1958 } else {
1959 cmn_err(CE_WARN, "Time-of-day chip had "
1960 "incorrect date; check and reset.");
1962 set_clock = 1;
1965 if (!boot_time) {
1966 boot_time = ts.tv_sec;
1967 set_clock = 1;
1970 if (set_clock)
1971 set_hrestime(&ts);
1973 mutex_exit(&tod_lock);
1976 int timechanged; /* for testing if the system time has been reset */
1978 void
1979 set_hrestime(timestruc_t *ts)
1981 int spl = hr_clock_lock();
1982 hrestime = *ts;
1983 membar_enter(); /* hrestime must be visible before timechanged++ */
1984 timedelta = 0;
1985 timechanged++;
1986 hr_clock_unlock(spl);
1987 callout_hrestime();
1990 static uint_t deadman_seconds;
1991 static uint32_t deadman_panics;
1992 static int deadman_enabled = 0;
1993 static int deadman_panic_timers = 1;
1995 static void
1996 deadman(void)
1998 if (panicstr) {
2000 * During panic, other CPUs besides the panic
2001 * master continue to handle cyclics and some other
2002 * interrupts. The code below is intended to be
2003 * single threaded, so any CPU other than the master
2004 * must keep out.
2006 if (CPU->cpu_id != panic_cpu.cpu_id)
2007 return;
2009 if (!deadman_panic_timers)
2010 return; /* allow all timers to be manually disabled */
2013 * If we are generating a crash dump or syncing filesystems and
2014 * the corresponding timer is set, decrement it and re-enter
2015 * the panic code to abort it and advance to the next state.
2016 * The panic states and triggers are explained in panic.c.
2018 if (panic_dump) {
2019 if (dump_timeleft && (--dump_timeleft == 0)) {
2020 panic("panic dump timeout");
2021 /*NOTREACHED*/
2024 return;
2027 if (deadman_counter != CPU->cpu_deadman_counter) {
2028 CPU->cpu_deadman_counter = deadman_counter;
2029 CPU->cpu_deadman_countdown = deadman_seconds;
2030 return;
2033 if (--CPU->cpu_deadman_countdown > 0)
2034 return;
2037 * Regardless of whether or not we actually bring the system down,
2038 * bump the deadman_panics variable.
2040 * N.B. deadman_panics is incremented once for each CPU that
2041 * passes through here. It's expected that all the CPUs will
2042 * detect this condition within one second of each other, so
2043 * when deadman_enabled is off, deadman_panics will
2044 * typically be a multiple of the total number of CPUs in
2045 * the system.
2047 atomic_inc_32(&deadman_panics);
2049 if (!deadman_enabled) {
2050 CPU->cpu_deadman_countdown = deadman_seconds;
2051 return;
2055 * If we're here, we want to bring the system down.
2057 panic("deadman: timed out after %d seconds of clock "
2058 "inactivity", deadman_seconds);
2059 /*NOTREACHED*/
2062 /*ARGSUSED*/
2063 static void
2064 deadman_online(void *arg, cpu_t *cpu, cyc_handler_t *hdlr, cyc_time_t *when)
2066 cpu->cpu_deadman_counter = 0;
2067 cpu->cpu_deadman_countdown = deadman_seconds;
2069 hdlr->cyh_func = (cyc_func_t)deadman;
2070 hdlr->cyh_level = CY_HIGH_LEVEL;
2071 hdlr->cyh_arg = NULL;
2074 * Stagger the CPUs so that they don't all run deadman() at
2075 * the same time. Simplest reason to do this is to make it
2076 * more likely that only one CPU will panic in case of a
2077 * timeout. This is (strictly speaking) an aesthetic, not a
2078 * technical consideration.
2080 when->cyt_when = cpu->cpu_id * (NANOSEC / NCPU);
2081 when->cyt_interval = NANOSEC;
2085 void
2086 deadman_init(void)
2088 cyc_omni_handler_t hdlr;
2090 if (deadman_seconds == 0)
2091 deadman_seconds = snoop_interval / MICROSEC;
2093 if (snooping)
2094 deadman_enabled = 1;
2096 hdlr.cyo_online = deadman_online;
2097 hdlr.cyo_offline = NULL;
2098 hdlr.cyo_arg = NULL;
2100 mutex_enter(&cpu_lock);
2101 deadman_cyclic = cyclic_add_omni(&hdlr);
2102 mutex_exit(&cpu_lock);
2106 * tod_fault() is for updating tod validate mechanism state:
2107 * (1) TOD_NOFAULT: for resetting the state to 'normal'.
2108 * currently used for debugging only
2109 * (2) The following four cases detected by tod validate mechanism:
2110 * TOD_REVERSED: current tod value is less than previous value.
2111 * TOD_STALLED: current tod value hasn't advanced.
2112 * TOD_JUMPED: current tod value advanced too far from previous value.
2113 * TOD_RATECHANGED: the ratio between average tod delta and
2114 * average tick delta has changed.
2115 * (3) TOD_RDONLY: when the TOD clock is not writeable e.g. because it is
2116 * a virtual TOD provided by a hypervisor.
2118 enum tod_fault_type
2119 tod_fault(enum tod_fault_type ftype, int off)
2121 ASSERT(MUTEX_HELD(&tod_lock));
2123 if (tod_faulted != ftype) {
2124 switch (ftype) {
2125 case TOD_NOFAULT:
2126 plat_tod_fault(TOD_NOFAULT);
2127 cmn_err(CE_NOTE, "Restarted tracking "
2128 "Time of Day clock.");
2129 tod_faulted = ftype;
2130 break;
2131 case TOD_REVERSED:
2132 case TOD_JUMPED:
2133 if (tod_faulted == TOD_NOFAULT) {
2134 plat_tod_fault(ftype);
2135 cmn_err(CE_WARN, "Time of Day clock error: "
2136 "reason [%s by 0x%x]. -- "
2137 " Stopped tracking Time Of Day clock.",
2138 tod_fault_table[ftype], off);
2139 tod_faulted = ftype;
2141 break;
2142 case TOD_STALLED:
2143 case TOD_RATECHANGED:
2144 if (tod_faulted == TOD_NOFAULT) {
2145 plat_tod_fault(ftype);
2146 cmn_err(CE_WARN, "Time of Day clock error: "
2147 "reason [%s]. -- "
2148 " Stopped tracking Time Of Day clock.",
2149 tod_fault_table[ftype]);
2150 tod_faulted = ftype;
2152 break;
2153 case TOD_RDONLY:
2154 if (tod_faulted == TOD_NOFAULT) {
2155 plat_tod_fault(ftype);
2156 cmn_err(CE_NOTE, "!Time of Day clock is "
2157 "Read-Only; set of Date/Time will not "
2158 "persist across reboot.");
2159 tod_faulted = ftype;
2161 break;
2162 default:
2163 break;
2166 return (tod_faulted);
2170 * Two functions that allow tod_status_flag to be manipulated by functions
2171 * external to this file.
2174 void
2175 tod_status_set(int tod_flag)
2177 tod_status_flag |= tod_flag;
2180 void
2181 tod_status_clear(int tod_flag)
2183 tod_status_flag &= ~tod_flag;
2187 * Record a timestamp and the value passed to tod_set(). The next call to
2188 * tod_validate() can use these values, prev_set_tick and prev_set_tod,
2189 * when checking the timestruc_t returned by tod_get(). Ordinarily,
2190 * tod_validate() will use prev_tick and prev_tod for this task but these
2191 * become obsolete, and will be re-assigned with the prev_set_* values,
2192 * in the case when the TOD is re-written.
2194 void
2195 tod_set_prev(timestruc_t ts)
2197 if ((tod_validate_enable == 0) || (tod_faulted != TOD_NOFAULT) ||
2198 tod_validate_deferred) {
2199 return;
2201 prev_set_tick = gethrtime();
2203 * A negative value will be set to zero in utc_to_tod() so we fake
2204 * a zero here in such a case. This would need to change if the
2205 * behavior of utc_to_tod() changes.
2207 prev_set_tod = ts.tv_sec < 0 ? 0 : ts.tv_sec;
2211 * tod_validate() is used for checking values returned by tod_get().
2212 * Four error cases can be detected by this routine:
2213 * TOD_REVERSED: current tod value is less than previous.
2214 * TOD_STALLED: current tod value hasn't advanced.
2215 * TOD_JUMPED: current tod value advanced too far from previous value.
2216 * TOD_RATECHANGED: the ratio between average tod delta and
2217 * average tick delta has changed.
2219 time_t
2220 tod_validate(time_t tod)
2222 time_t diff_tod;
2223 hrtime_t diff_tick;
2225 long dtick;
2226 int dtick_delta;
2228 int off = 0;
2229 enum tod_fault_type tod_bad = TOD_NOFAULT;
2231 static int firsttime = 1;
2233 static time_t prev_tod = 0;
2234 static hrtime_t prev_tick = 0;
2235 static long dtick_avg = TOD_REF_FREQ;
2237 int cpr_resume_done = 0;
2238 int dr_resume_done = 0;
2240 hrtime_t tick = gethrtime();
2242 ASSERT(MUTEX_HELD(&tod_lock));
2245 * tod_validate_enable is patchable via /etc/system.
2246 * If TOD is already faulted, or if TOD validation is deferred,
2247 * there is nothing to do.
2249 if ((tod_validate_enable == 0) || (tod_faulted != TOD_NOFAULT) ||
2250 tod_validate_deferred) {
2251 return (tod);
2255 * If this is the first time through, we just need to save the tod
2256 * we were called with and hrtime so we can use them next time to
2257 * validate tod_get().
2259 if (firsttime) {
2260 firsttime = 0;
2261 prev_tod = tod;
2262 prev_tick = tick;
2263 return (tod);
2267 * Handle any flags that have been turned on by tod_status_set().
2268 * In the case where a tod_set() is done and then a subsequent
2269 * tod_get() fails (ie, both TOD_SET_DONE and TOD_GET_FAILED are
2270 * true), we treat the TOD_GET_FAILED with precedence by switching
2271 * off the flag, returning tod and leaving TOD_SET_DONE asserted
2272 * until such time as tod_get() completes successfully.
2274 if (tod_status_flag & TOD_GET_FAILED) {
2276 * tod_get() has encountered an issue, possibly transitory,
2277 * when reading TOD. We'll just return the incoming tod
2278 * value (which is actually hrestime.tv_sec in this case)
2279 * and when we get a genuine tod, following a successful
2280 * tod_get(), we can validate using prev_tod and prev_tick.
2282 tod_status_flag &= ~TOD_GET_FAILED;
2283 return (tod);
2284 } else if (tod_status_flag & TOD_SET_DONE) {
2286 * TOD has been modified. Just before the TOD was written,
2287 * tod_set_prev() saved tod and hrtime; we can now use
2288 * those values, prev_set_tod and prev_set_tick, to validate
2289 * the incoming tod that's just been read.
2291 prev_tod = prev_set_tod;
2292 prev_tick = prev_set_tick;
2293 dtick_avg = TOD_REF_FREQ;
2294 tod_status_flag &= ~TOD_SET_DONE;
2296 * If a tod_set() preceded a cpr_suspend() without an
2297 * intervening tod_validate(), we need to ensure that a
2298 * TOD_JUMPED condition is ignored.
2299 * Note this isn't a concern in the case of DR as we've
2300 * just reassigned dtick_avg, above.
2302 if (tod_status_flag & TOD_CPR_RESUME_DONE) {
2303 cpr_resume_done = 1;
2304 tod_status_flag &= ~TOD_CPR_RESUME_DONE;
2306 } else if (tod_status_flag & TOD_CPR_RESUME_DONE) {
2308 * The system's coming back from a checkpoint resume.
2310 cpr_resume_done = 1;
2311 tod_status_flag &= ~TOD_CPR_RESUME_DONE;
2313 * We need to handle the possibility of a CPR suspend
2314 * operation having been initiated whilst a DR event was
2315 * in-flight.
2317 if (tod_status_flag & TOD_DR_RESUME_DONE) {
2318 dr_resume_done = 1;
2319 tod_status_flag &= ~TOD_DR_RESUME_DONE;
2321 } else if (tod_status_flag & TOD_DR_RESUME_DONE) {
2323 * A Dynamic Reconfiguration event has taken place.
2325 dr_resume_done = 1;
2326 tod_status_flag &= ~TOD_DR_RESUME_DONE;
2329 /* test hook */
2330 switch (tod_unit_test) {
2331 case 1: /* for testing jumping tod */
2332 tod += tod_test_injector;
2333 tod_unit_test = 0;
2334 break;
2335 case 2: /* for testing stuck tod bit */
2336 tod |= 1 << tod_test_injector;
2337 tod_unit_test = 0;
2338 break;
2339 case 3: /* for testing stalled tod */
2340 tod = prev_tod;
2341 tod_unit_test = 0;
2342 break;
2343 case 4: /* reset tod fault status */
2344 (void) tod_fault(TOD_NOFAULT, 0);
2345 tod_unit_test = 0;
2346 break;
2347 default:
2348 break;
2351 diff_tod = tod - prev_tod;
2352 diff_tick = tick - prev_tick;
2354 ASSERT(diff_tick >= 0);
2356 if (diff_tod < 0) {
2357 /* ERROR - tod reversed */
2358 tod_bad = TOD_REVERSED;
2359 off = (int)(prev_tod - tod);
2360 } else if (diff_tod == 0) {
2361 /* tod did not advance */
2362 if (diff_tick > TOD_STALL_THRESHOLD) {
2363 /* ERROR - tod stalled */
2364 tod_bad = TOD_STALLED;
2365 } else {
2367 * Make sure we don't update prev_tick
2368 * so that diff_tick is calculated since
2369 * the first diff_tod == 0
2371 return (tod);
2373 } else {
2374 /* calculate dtick */
2375 dtick = diff_tick / diff_tod;
2377 /* update dtick averages */
2378 dtick_avg += ((dtick - dtick_avg) / TOD_FILTER_N);
2381 * Calculate dtick_delta as
2382 * variation from reference freq in quartiles
2384 dtick_delta = (dtick_avg - TOD_REF_FREQ) /
2385 (TOD_REF_FREQ >> 2);
2388 * Even with a perfectly functioning TOD device,
2389 * when the number of elapsed seconds is low the
2390 * algorithm can calculate a rate that is beyond
2391 * tolerance, causing an error. The algorithm is
2392 * inaccurate when elapsed time is low (less than
2393 * 5 seconds).
2395 if (diff_tod > 4) {
2396 if (dtick < TOD_JUMP_THRESHOLD) {
2398 * If we've just done a CPR resume, we detect
2399 * a jump in the TOD but, actually, what's
2400 * happened is that the TOD has been increasing
2401 * whilst the system was suspended and the tick
2402 * count hasn't kept up. We consider the first
2403 * occurrence of this after a resume as normal
2404 * and ignore it; otherwise, in a non-resume
2405 * case, we regard it as a TOD problem.
2407 if (!cpr_resume_done) {
2408 /* ERROR - tod jumped */
2409 tod_bad = TOD_JUMPED;
2410 off = (int)diff_tod;
2413 if (dtick_delta) {
2415 * If we've just done a DR resume, dtick_avg
2416 * can go a bit askew so we reset it and carry
2417 * on; otherwise, the TOD is in error.
2419 if (dr_resume_done) {
2420 dtick_avg = TOD_REF_FREQ;
2421 } else {
2422 /* ERROR - change in clock rate */
2423 tod_bad = TOD_RATECHANGED;
2429 if (tod_bad != TOD_NOFAULT) {
2430 (void) tod_fault(tod_bad, off);
2433 * Disable dosynctodr since we are going to fault
2434 * the TOD chip anyway here
2436 dosynctodr = 0;
2439 * Set tod to the correct value from hrestime
2441 tod = hrestime.tv_sec;
2444 prev_tod = tod;
2445 prev_tick = tick;
2446 return (tod);
2449 static void
2450 calcloadavg(int nrun, uint64_t *hp_ave)
2452 static int64_t f[3] = { 135, 27, 9 };
2453 uint_t i;
2454 int64_t q, r;
2457 * Compute load average over the last 1, 5, and 15 minutes
2458 * (60, 300, and 900 seconds). The constants in f[3] are for
2459 * exponential decay:
2460 * (1 - exp(-1/60)) << 13 = 135,
2461 * (1 - exp(-1/300)) << 13 = 27,
2462 * (1 - exp(-1/900)) << 13 = 9.
2466 * a little hoop-jumping to avoid integer overflow
2468 for (i = 0; i < 3; i++) {
2469 q = (hp_ave[i] >> 16) << 7;
2470 r = (hp_ave[i] & 0xffff) << 7;
2471 hp_ave[i] += ((nrun - q) * f[i] - ((r * f[i]) >> 16)) >> 4;
2476 * lbolt_hybrid() is used by ddi_get_lbolt() and ddi_get_lbolt64() to
2477 * calculate the value of lbolt according to the current mode. In the event
2478 * driven mode (the default), lbolt is calculated by dividing the current hires
2479 * time by the number of nanoseconds per clock tick. In the cyclic driven mode
2480 * an internal variable is incremented at each firing of the lbolt cyclic
2481 * and returned by lbolt_cyclic_driven().
2483 * The system will transition from event to cyclic driven mode when the number
2484 * of calls to lbolt_event_driven() exceeds the (per CPU) threshold within a
2485 * window of time. It does so by reprograming lbolt_cyclic from CY_INFINITY to
2486 * nsec_per_tick. The lbolt cyclic will remain ON while at least one CPU is
2487 * causing enough activity to cross the thresholds.
2489 int64_t
2490 lbolt_bootstrap(void)
2492 return (0);
2495 /* ARGSUSED */
2496 uint_t
2497 lbolt_ev_to_cyclic(caddr_t arg1, caddr_t arg2)
2499 hrtime_t ts, exp;
2500 int ret;
2502 ASSERT(lbolt_hybrid != lbolt_cyclic_driven);
2504 kpreempt_disable();
2506 ts = gethrtime();
2507 lb_info->lbi_internal = (ts/nsec_per_tick);
2510 * Align the next expiration to a clock tick boundary.
2512 exp = ts + nsec_per_tick - 1;
2513 exp = (exp/nsec_per_tick) * nsec_per_tick;
2515 ret = cyclic_reprogram(lb_info->id.lbi_cyclic_id, exp);
2516 ASSERT(ret);
2518 lbolt_hybrid = lbolt_cyclic_driven;
2519 lb_info->lbi_cyc_deactivate = B_FALSE;
2520 lb_info->lbi_cyc_deac_start = lb_info->lbi_internal;
2522 kpreempt_enable();
2524 ret = atomic_dec_32_nv(&lb_info->lbi_token);
2525 ASSERT(ret == 0);
2527 return (1);
2530 int64_t
2531 lbolt_event_driven(void)
2533 hrtime_t ts;
2534 int64_t lb;
2535 int ret, cpu = CPU->cpu_seqid;
2537 ts = gethrtime();
2538 ASSERT(ts > 0);
2540 ASSERT(nsec_per_tick > 0);
2541 lb = (ts/nsec_per_tick);
2544 * Switch to cyclic mode if the number of calls to this routine
2545 * has reached the threshold within the interval.
2547 if ((lb - lb_cpu[cpu].lbc_cnt_start) < lb_info->lbi_thresh_interval) {
2549 if (--lb_cpu[cpu].lbc_counter == 0) {
2551 * Reached the threshold within the interval, reset
2552 * the usage statistics.
2554 lb_cpu[cpu].lbc_counter = lb_info->lbi_thresh_calls;
2555 lb_cpu[cpu].lbc_cnt_start = lb;
2558 * Make sure only one thread reprograms the
2559 * lbolt cyclic and changes the mode.
2561 if (panicstr == NULL &&
2562 atomic_cas_32(&lb_info->lbi_token, 0, 1) == 0) {
2564 if (lbolt_hybrid == lbolt_cyclic_driven) {
2565 ret = atomic_dec_32_nv(
2566 &lb_info->lbi_token);
2567 ASSERT(ret == 0);
2568 } else {
2569 lbolt_softint_post();
2573 } else {
2575 * Exceeded the interval, reset the usage statistics.
2577 lb_cpu[cpu].lbc_counter = lb_info->lbi_thresh_calls;
2578 lb_cpu[cpu].lbc_cnt_start = lb;
2581 ASSERT(lb >= lb_info->lbi_debug_time);
2583 return (lb - lb_info->lbi_debug_time);
2586 int64_t
2587 lbolt_cyclic_driven(void)
2589 int64_t lb = lb_info->lbi_internal;
2590 int cpu;
2593 * If a CPU has already prevented the lbolt cyclic from deactivating
2594 * itself, don't bother tracking the usage. Otherwise check if we're
2595 * within the interval and how the per CPU counter is doing.
2597 if (lb_info->lbi_cyc_deactivate) {
2598 cpu = CPU->cpu_seqid;
2599 if ((lb - lb_cpu[cpu].lbc_cnt_start) <
2600 lb_info->lbi_thresh_interval) {
2602 if (lb_cpu[cpu].lbc_counter == 0)
2604 * Reached the threshold within the interval,
2605 * prevent the lbolt cyclic from turning itself
2606 * off.
2608 lb_info->lbi_cyc_deactivate = B_FALSE;
2609 else
2610 lb_cpu[cpu].lbc_counter--;
2611 } else {
2613 * Only reset the usage statistics when we have
2614 * exceeded the interval.
2616 lb_cpu[cpu].lbc_counter = lb_info->lbi_thresh_calls;
2617 lb_cpu[cpu].lbc_cnt_start = lb;
2621 ASSERT(lb >= lb_info->lbi_debug_time);
2623 return (lb - lb_info->lbi_debug_time);
2627 * The lbolt_cyclic() routine will fire at a nsec_per_tick interval to satisfy
2628 * performance needs of ddi_get_lbolt() and ddi_get_lbolt64() consumers.
2629 * It is inactive by default, and will be activated when switching from event
2630 * to cyclic driven lbolt. The cyclic will turn itself off unless signaled
2631 * by lbolt_cyclic_driven().
2633 static void
2634 lbolt_cyclic(void)
2636 int ret;
2638 lb_info->lbi_internal++;
2640 if (!lbolt_cyc_only) {
2642 if (lb_info->lbi_cyc_deactivate) {
2644 * Switching from cyclic to event driven mode.
2646 if (panicstr == NULL &&
2647 atomic_cas_32(&lb_info->lbi_token, 0, 1) == 0) {
2649 if (lbolt_hybrid == lbolt_event_driven) {
2650 ret = atomic_dec_32_nv(
2651 &lb_info->lbi_token);
2652 ASSERT(ret == 0);
2653 return;
2656 kpreempt_disable();
2658 lbolt_hybrid = lbolt_event_driven;
2659 ret = cyclic_reprogram(
2660 lb_info->id.lbi_cyclic_id,
2661 CY_INFINITY);
2662 ASSERT(ret);
2664 kpreempt_enable();
2666 ret = atomic_dec_32_nv(&lb_info->lbi_token);
2667 ASSERT(ret == 0);
2672 * The lbolt cyclic should not try to deactivate itself before
2673 * the sampling period has elapsed.
2675 if (lb_info->lbi_internal - lb_info->lbi_cyc_deac_start >=
2676 lb_info->lbi_thresh_interval) {
2677 lb_info->lbi_cyc_deactivate = B_TRUE;
2678 lb_info->lbi_cyc_deac_start = lb_info->lbi_internal;
2684 * Since the lbolt service was historically cyclic driven, it must be 'stopped'
2685 * when the system drops into the kernel debugger. lbolt_debug_entry() is
2686 * called by the KDI system claim callbacks to record a hires timestamp at
2687 * debug enter time. lbolt_debug_return() is called by the sistem release
2688 * callbacks to account for the time spent in the debugger. The value is then
2689 * accumulated in the lb_info structure and used by lbolt_event_driven() and
2690 * lbolt_cyclic_driven(), as well as the mdb_get_lbolt() routine.
2692 void
2693 lbolt_debug_entry(void)
2695 if (lbolt_hybrid != lbolt_bootstrap) {
2696 ASSERT(lb_info != NULL);
2697 lb_info->lbi_debug_ts = gethrtime();
2702 * Calculate the time spent in the debugger and add it to the lbolt info
2703 * structure. We also update the internal lbolt value in case we were in
2704 * cyclic driven mode going in.
2706 void
2707 lbolt_debug_return(void)
2709 hrtime_t ts;
2711 if (lbolt_hybrid != lbolt_bootstrap) {
2712 ASSERT(lb_info != NULL);
2713 ASSERT(nsec_per_tick > 0);
2715 ts = gethrtime();
2716 lb_info->lbi_internal = (ts/nsec_per_tick);
2717 lb_info->lbi_debug_time +=
2718 ((ts - lb_info->lbi_debug_ts)/nsec_per_tick);
2720 lb_info->lbi_debug_ts = 0;