xref: /illumos-gate/usr/src/uts/common/os/clock.c (revision bcd524b5c10222cf2a1ef37ac7ea8bf1baa3a2ee)
1 /*
2  * CDDL HEADER START
3  *
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.
7  *
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.
12  *
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]
18  *
19  * CDDL HEADER END
20  */
21 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
22 /*	  All Rights Reserved	*/
23 
24 
25 /*
26  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
27  * Use is subject to license terms.
28  */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
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>
60 #include <sys/mem_cage.h>
61 
62 #include <vm/page.h>
63 #include <vm/anon.h>
64 #include <vm/rm.h>
65 #include <sys/cyclic.h>
66 #include <sys/cpupart.h>
67 #include <sys/rctl.h>
68 #include <sys/task.h>
69 #include <sys/sdt.h>
70 
71 /*
72  * for NTP support
73  */
74 #include <sys/timex.h>
75 #include <sys/inttypes.h>
76 
77 /*
78  * clock() is called straight from the clock cyclic; see clock_init().
79  *
80  * Functions:
81  *	reprime clock
82  *	schedule callouts
83  *	maintain date
84  *	jab the scheduler
85  */
86 
87 extern kcondvar_t	fsflush_cv;
88 extern sysinfo_t	sysinfo;
89 extern vminfo_t	vminfo;
90 extern int	idleswtch;	/* flag set while idle in pswtch() */
91 
92 /*
93  * high-precision avenrun values.  These are needed to make the
94  * regular avenrun values accurate.
95  */
96 static uint64_t hp_avenrun[3];
97 int	avenrun[3];		/* FSCALED average run queue lengths */
98 time_t	time;	/* time in seconds since 1970 - for compatibility only */
99 
100 static struct loadavg_s loadavg;
101 /*
102  * Phase/frequency-lock loop (PLL/FLL) definitions
103  *
104  * The following variables are read and set by the ntp_adjtime() system
105  * call.
106  *
107  * time_state shows the state of the system clock, with values defined
108  * in the timex.h header file.
109  *
110  * time_status shows the status of the system clock, with bits defined
111  * in the timex.h header file.
112  *
113  * time_offset is used by the PLL/FLL to adjust the system time in small
114  * increments.
115  *
116  * time_constant determines the bandwidth or "stiffness" of the PLL.
117  *
118  * time_tolerance determines maximum frequency error or tolerance of the
119  * CPU clock oscillator and is a property of the architecture; however,
120  * in principle it could change as result of the presence of external
121  * discipline signals, for instance.
122  *
123  * time_precision is usually equal to the kernel tick variable; however,
124  * in cases where a precision clock counter or external clock is
125  * available, the resolution can be much less than this and depend on
126  * whether the external clock is working or not.
127  *
128  * time_maxerror is initialized by a ntp_adjtime() call and increased by
129  * the kernel once each second to reflect the maximum error bound
130  * growth.
131  *
132  * time_esterror is set and read by the ntp_adjtime() call, but
133  * otherwise not used by the kernel.
134  */
135 int32_t time_state = TIME_OK;	/* clock state */
136 int32_t time_status = STA_UNSYNC;	/* clock status bits */
137 int32_t time_offset = 0;		/* time offset (us) */
138 int32_t time_constant = 0;		/* pll time constant */
139 int32_t time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
140 int32_t time_precision = 1;	/* clock precision (us) */
141 int32_t time_maxerror = MAXPHASE;	/* maximum error (us) */
142 int32_t time_esterror = MAXPHASE;	/* estimated error (us) */
143 
144 /*
145  * The following variables establish the state of the PLL/FLL and the
146  * residual time and frequency offset of the local clock. The scale
147  * factors are defined in the timex.h header file.
148  *
149  * time_phase and time_freq are the phase increment and the frequency
150  * increment, respectively, of the kernel time variable.
151  *
152  * time_freq is set via ntp_adjtime() from a value stored in a file when
153  * the synchronization daemon is first started. Its value is retrieved
154  * via ntp_adjtime() and written to the file about once per hour by the
155  * daemon.
156  *
157  * time_adj is the adjustment added to the value of tick at each timer
158  * interrupt and is recomputed from time_phase and time_freq at each
159  * seconds rollover.
160  *
161  * time_reftime is the second's portion of the system time at the last
162  * call to ntp_adjtime(). It is used to adjust the time_freq variable
163  * and to increase the time_maxerror as the time since last update
164  * increases.
165  */
166 int32_t time_phase = 0;		/* phase offset (scaled us) */
167 int32_t time_freq = 0;		/* frequency offset (scaled ppm) */
168 int32_t time_adj = 0;		/* tick adjust (scaled 1 / hz) */
169 int32_t time_reftime = 0;		/* time at last adjustment (s) */
170 
171 /*
172  * The scale factors of the following variables are defined in the
173  * timex.h header file.
174  *
175  * pps_time contains the time at each calibration interval, as read by
176  * microtime(). pps_count counts the seconds of the calibration
177  * interval, the duration of which is nominally pps_shift in powers of
178  * two.
179  *
180  * pps_offset is the time offset produced by the time median filter
181  * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
182  * this filter.
183  *
184  * pps_freq is the frequency offset produced by the frequency median
185  * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
186  * by this filter.
187  *
188  * pps_usec is latched from a high resolution counter or external clock
189  * at pps_time. Here we want the hardware counter contents only, not the
190  * contents plus the time_tv.usec as usual.
191  *
192  * pps_valid counts the number of seconds since the last PPS update. It
193  * is used as a watchdog timer to disable the PPS discipline should the
194  * PPS signal be lost.
195  *
196  * pps_glitch counts the number of seconds since the beginning of an
197  * offset burst more than tick/2 from current nominal offset. It is used
198  * mainly to suppress error bursts due to priority conflicts between the
199  * PPS interrupt and timer interrupt.
200  *
201  * pps_intcnt counts the calibration intervals for use in the interval-
202  * adaptation algorithm. It's just too complicated for words.
203  */
204 struct timeval pps_time;	/* kernel time at last interval */
205 int32_t pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
206 int32_t pps_offset = 0;		/* pps time offset (us) */
207 int32_t pps_jitter = MAXTIME;	/* time dispersion (jitter) (us) */
208 int32_t pps_ff[] = {0, 0, 0};	/* pps frequency offset median filter */
209 int32_t pps_freq = 0;		/* frequency offset (scaled ppm) */
210 int32_t pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
211 int32_t pps_usec = 0;		/* microsec counter at last interval */
212 int32_t pps_valid = PPS_VALID;	/* pps signal watchdog counter */
213 int32_t pps_glitch = 0;		/* pps signal glitch counter */
214 int32_t pps_count = 0;		/* calibration interval counter (s) */
215 int32_t pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
216 int32_t pps_intcnt = 0;		/* intervals at current duration */
217 
218 /*
219  * PPS signal quality monitors
220  *
221  * pps_jitcnt counts the seconds that have been discarded because the
222  * jitter measured by the time median filter exceeds the limit MAXTIME
223  * (100 us).
224  *
225  * pps_calcnt counts the frequency calibration intervals, which are
226  * variable from 4 s to 256 s.
227  *
228  * pps_errcnt counts the calibration intervals which have been discarded
229  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
230  * calibration interval jitter exceeds two ticks.
231  *
232  * pps_stbcnt counts the calibration intervals that have been discarded
233  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
234  */
235 int32_t pps_jitcnt = 0;		/* jitter limit exceeded */
236 int32_t pps_calcnt = 0;		/* calibration intervals */
237 int32_t pps_errcnt = 0;		/* calibration errors */
238 int32_t pps_stbcnt = 0;		/* stability limit exceeded */
239 
240 /* The following variables require no explicit locking */
241 volatile clock_t lbolt;		/* time in Hz since last boot */
242 volatile int64_t lbolt64;	/* lbolt64 won't wrap for 2.9 billion yrs */
243 
244 kcondvar_t lbolt_cv;
245 int one_sec = 1; /* turned on once every second */
246 static int fsflushcnt;	/* counter for t_fsflushr */
247 int	dosynctodr = 1;	/* patchable; enable/disable sync to TOD chip */
248 int	tod_needsync = 0;	/* need to sync tod chip with software time */
249 static int tod_broken = 0;	/* clock chip doesn't work */
250 time_t	boot_time = 0;		/* Boot time in seconds since 1970 */
251 cyclic_id_t clock_cyclic;	/* clock()'s cyclic_id */
252 cyclic_id_t deadman_cyclic;	/* deadman()'s cyclic_id */
253 
254 static int lgrp_ticks;		/* counter to schedule lgrp load calcs */
255 
256 /*
257  * for tod fault detection
258  */
259 #define	TOD_REF_FREQ		((longlong_t)(NANOSEC))
260 #define	TOD_STALL_THRESHOLD	(TOD_REF_FREQ * 3 / 2)
261 #define	TOD_JUMP_THRESHOLD	(TOD_REF_FREQ / 2)
262 #define	TOD_FILTER_N		4
263 #define	TOD_FILTER_SETTLE	(4 * TOD_FILTER_N)
264 static int tod_faulted = TOD_NOFAULT;
265 static int tod_fault_reset_flag = 0;
266 
267 /* patchable via /etc/system */
268 int tod_validate_enable = 1;
269 
270 /*
271  * On non-SPARC systems, TOD validation must be deferred until gethrtime
272  * returns non-zero values (after mach_clkinit's execution).
273  * On SPARC systems, it must be deferred until after hrtime_base
274  * and hres_last_tick are set (in the first invocation of hres_tick).
275  * Since in both cases the prerequisites occur before the invocation of
276  * tod_get() in clock(), the deferment is lifted there.
277  */
278 static boolean_t tod_validate_deferred = B_TRUE;
279 
280 /*
281  * tod_fault_table[] must be aligned with
282  * enum tod_fault_type in systm.h
283  */
284 static char *tod_fault_table[] = {
285 	"Reversed",			/* TOD_REVERSED */
286 	"Stalled",			/* TOD_STALLED */
287 	"Jumped",			/* TOD_JUMPED */
288 	"Changed in Clock Rate"		/* TOD_RATECHANGED */
289 	/*
290 	 * no strings needed for TOD_NOFAULT
291 	 */
292 };
293 
294 /*
295  * test hook for tod broken detection in tod_validate
296  */
297 int tod_unit_test = 0;
298 time_t tod_test_injector;
299 
300 #define	CLOCK_ADJ_HIST_SIZE	4
301 
302 static int	adj_hist_entry;
303 
304 int64_t clock_adj_hist[CLOCK_ADJ_HIST_SIZE];
305 
306 static void clock_tick(kthread_t *);
307 static void calcloadavg(int, uint64_t *);
308 static int genloadavg(struct loadavg_s *);
309 static void loadavg_update();
310 
311 void (*cmm_clock_callout)() = NULL;
312 void (*cpucaps_clock_callout)() = NULL;
313 
314 static void
315 clock(void)
316 {
317 	kthread_t	*t;
318 	kmutex_t	*plockp;	/* pointer to thread's process lock */
319 	int	pinned_intr = 0;
320 	uint_t	nrunnable, nrunning;
321 	uint_t	w_io;
322 	cpu_t	*cp;
323 	cpupart_t *cpupart;
324 	int	exiting;
325 	extern void set_anoninfo();
326 	extern	void	set_freemem();
327 	void	(*funcp)();
328 	int32_t ltemp;
329 	int64_t lltemp;
330 	int s;
331 	int do_lgrp_load;
332 	int i;
333 
334 	if (panicstr)
335 		return;
336 
337 	set_anoninfo();
338 	/*
339 	 * Make sure that 'freemem' do not drift too far from the truth
340 	 */
341 	set_freemem();
342 
343 
344 	/*
345 	 * Before the section which is repeated is executed, we do
346 	 * the time delta processing which occurs every clock tick
347 	 *
348 	 * There is additional processing which happens every time
349 	 * the nanosecond counter rolls over which is described
350 	 * below - see the section which begins with : if (one_sec)
351 	 *
352 	 * This section marks the beginning of the precision-kernel
353 	 * code fragment.
354 	 *
355 	 * First, compute the phase adjustment. If the low-order bits
356 	 * (time_phase) of the update overflow, bump the higher order
357 	 * bits (time_update).
358 	 */
359 	time_phase += time_adj;
360 	if (time_phase <= -FINEUSEC) {
361 		ltemp = -time_phase / SCALE_PHASE;
362 		time_phase += ltemp * SCALE_PHASE;
363 		s = hr_clock_lock();
364 		timedelta -= ltemp * (NANOSEC/MICROSEC);
365 		hr_clock_unlock(s);
366 	} else if (time_phase >= FINEUSEC) {
367 		ltemp = time_phase / SCALE_PHASE;
368 		time_phase -= ltemp * SCALE_PHASE;
369 		s = hr_clock_lock();
370 		timedelta += ltemp * (NANOSEC/MICROSEC);
371 		hr_clock_unlock(s);
372 	}
373 
374 	/*
375 	 * End of precision-kernel code fragment which is processed
376 	 * every timer interrupt.
377 	 *
378 	 * Continue with the interrupt processing as scheduled.
379 	 *
380 	 * Did we pin another interrupt thread?  Need to check this before
381 	 * grabbing any adaptive locks, since if we block on a lock the
382 	 * pinned thread could escape.  Note that this is just a heuristic;
383 	 * if we take multiple laps though clock() without returning from
384 	 * the interrupt because we have another clock tick pending, then
385 	 * the pinned interrupt could be released by one of the previous
386 	 * laps.  The only consequence is that the CPU will be counted as
387 	 * in idle (or wait) state once the pinned interrupt is released.
388 	 * Since this accounting is inaccurate by nature, this isn't a big
389 	 * deal --- but we should try to get it right in the common case
390 	 * where we only call clock() once per interrupt.
391 	 */
392 	if (curthread->t_intr != NULL)
393 		pinned_intr = (curthread->t_intr->t_flag & T_INTR_THREAD);
394 
395 	/*
396 	 * Count the number of runnable threads and the number waiting
397 	 * for some form of I/O to complete -- gets added to
398 	 * sysinfo.waiting.  To know the state of the system, must add
399 	 * wait counts from all CPUs.  Also add up the per-partition
400 	 * statistics.
401 	 */
402 	w_io = 0;
403 	nrunnable = 0;
404 
405 	/*
406 	 * keep track of when to update lgrp/part loads
407 	 */
408 
409 	do_lgrp_load = 0;
410 	if (lgrp_ticks++ >= hz / 10) {
411 		lgrp_ticks = 0;
412 		do_lgrp_load = 1;
413 	}
414 
415 	if (one_sec)
416 		loadavg_update();
417 
418 	/*
419 	 * First count the threads waiting on kpreempt queues in each
420 	 * CPU partition.
421 	 */
422 
423 	cpupart = cp_list_head;
424 	do {
425 		uint_t cpupart_nrunnable = cpupart->cp_kp_queue.disp_nrunnable;
426 
427 		cpupart->cp_updates++;
428 		nrunnable += cpupart_nrunnable;
429 		cpupart->cp_nrunnable_cum += cpupart_nrunnable;
430 		if (one_sec) {
431 			cpupart->cp_nrunning = 0;
432 			cpupart->cp_nrunnable = cpupart_nrunnable;
433 		}
434 	} while ((cpupart = cpupart->cp_next) != cp_list_head);
435 
436 
437 	/* Now count the per-CPU statistics. */
438 	cp = cpu_list;
439 	do {
440 		uint_t cpu_nrunnable = cp->cpu_disp->disp_nrunnable;
441 
442 		nrunnable += cpu_nrunnable;
443 		cpupart = cp->cpu_part;
444 		cpupart->cp_nrunnable_cum += cpu_nrunnable;
445 		if (one_sec) {
446 			cpupart->cp_nrunnable += cpu_nrunnable;
447 			/*
448 			 * w_io is used to update sysinfo.waiting during
449 			 * one_second processing below.  Only gather w_io
450 			 * information when we walk the list of cpus if we're
451 			 * going to perform one_second processing.
452 			 */
453 			w_io += CPU_STATS(cp, sys.iowait);
454 
455 		}
456 		if (do_lgrp_load &&
457 		    (cp->cpu_flags & CPU_EXISTS)) {
458 			/*
459 			 * When updating the lgroup's load average,
460 			 * account for the thread running on the CPU.
461 			 * If the CPU is the current one, then we need
462 			 * to account for the underlying thread which
463 			 * got the clock interrupt not the thread that is
464 			 * handling the interrupt and caculating the load
465 			 * average
466 			 */
467 			t = cp->cpu_thread;
468 			if (CPU == cp)
469 				t = t->t_intr;
470 
471 			/*
472 			 * Account for the load average for this thread if
473 			 * it isn't the idle thread or it is on the interrupt
474 			 * stack and not the current CPU handling the clock
475 			 * interrupt
476 			 */
477 			if ((t && t != cp->cpu_idle_thread) || (CPU != cp &&
478 			    CPU_ON_INTR(cp))) {
479 				if (t->t_lpl == cp->cpu_lpl) {
480 					/* local thread */
481 					cpu_nrunnable++;
482 				} else {
483 					/*
484 					 * This is a remote thread, charge it
485 					 * against its home lgroup.  Note that
486 					 * we notice that a thread is remote
487 					 * only if it's currently executing.
488 					 * This is a reasonable approximation,
489 					 * since queued remote threads are rare.
490 					 * Note also that if we didn't charge
491 					 * it to its home lgroup, remote
492 					 * execution would often make a system
493 					 * appear balanced even though it was
494 					 * not, and thread placement/migration
495 					 * would often not be done correctly.
496 					 */
497 					lgrp_loadavg(t->t_lpl,
498 					    LGRP_LOADAVG_IN_THREAD_MAX, 0);
499 				}
500 			}
501 			lgrp_loadavg(cp->cpu_lpl,
502 			    cpu_nrunnable * LGRP_LOADAVG_IN_THREAD_MAX, 1);
503 		}
504 	} while ((cp = cp->cpu_next) != cpu_list);
505 
506 	/*
507 	 * Do tick processing for all the active threads running in
508 	 * the system.  We're trying to be more fair by walking the
509 	 * list of CPUs starting from a different CPUs each time.
510 	 */
511 	cp = clock_cpu_list;
512 	nrunning = 0;
513 	do {
514 		klwp_id_t lwp;
515 		int intr;
516 		int thread_away;
517 
518 		/*
519 		 * Don't do any tick processing on CPUs that
520 		 * aren't even in the system or aren't up yet.
521 		 */
522 		if ((cp->cpu_flags & CPU_EXISTS) == 0) {
523 			continue;
524 		}
525 
526 		/*
527 		 * The locking here is rather tricky.  We use
528 		 * thread_free_lock to keep the currently running
529 		 * thread from being freed or recycled while we're
530 		 * looking at it.  We can then check if the thread
531 		 * is exiting and get the appropriate p_lock if it
532 		 * is not.  We have to be careful, though, because
533 		 * the _process_ can still be freed while we're
534 		 * holding thread_free_lock.  To avoid touching the
535 		 * proc structure we put a pointer to the p_lock in the
536 		 * thread structure.  The p_lock is persistent so we
537 		 * can acquire it even if the process is gone.  At that
538 		 * point we can check (again) if the thread is exiting
539 		 * and either drop the lock or do the tick processing.
540 		 */
541 		mutex_enter(&thread_free_lock);
542 		/*
543 		 * We cannot hold the cpu_lock to prevent the
544 		 * cpu_list from changing in the clock interrupt.
545 		 * As long as we don't block (or don't get pre-empted)
546 		 * the cpu_list will not change (all threads are paused
547 		 * before list modification). If the list does change
548 		 * any deleted cpu structures will remain with cpu_next
549 		 * set to NULL, hence the following test.
550 		 */
551 		if (cp->cpu_next == NULL) {
552 			mutex_exit(&thread_free_lock);
553 			break;
554 		}
555 		t = cp->cpu_thread;	/* Current running thread */
556 		if (CPU == cp) {
557 			/*
558 			 * 't' will be the clock interrupt thread on this
559 			 * CPU.  Use the pinned thread (if any) on this CPU
560 			 * as the target of the clock tick.  If we pinned
561 			 * an interrupt, though, just keep using the clock
562 			 * interrupt thread since the formerly pinned one
563 			 * may have gone away.  One interrupt thread is as
564 			 * good as another, and this means we don't have
565 			 * to continue to check pinned_intr in subsequent
566 			 * code.
567 			 */
568 			ASSERT(t == curthread);
569 			if (t->t_intr != NULL && !pinned_intr)
570 				t = t->t_intr;
571 		}
572 
573 		intr = t->t_flag & T_INTR_THREAD;
574 		lwp = ttolwp(t);
575 		if (lwp == NULL || (t->t_proc_flag & TP_LWPEXIT) || intr) {
576 			/*
577 			 * Thread is exiting (or uninteresting) so don't
578 			 * do tick processing or grab p_lock.  Once we
579 			 * drop thread_free_lock we can't look inside the
580 			 * thread or lwp structure, since the thread may
581 			 * have gone away.
582 			 */
583 			exiting = 1;
584 		} else {
585 			/*
586 			 * OK, try to grab the process lock.  See
587 			 * comments above for why we're not using
588 			 * ttoproc(t)->p_lockp here.
589 			 */
590 			plockp = t->t_plockp;
591 			mutex_enter(plockp);
592 			/* See above comment. */
593 			if (cp->cpu_next == NULL) {
594 				mutex_exit(plockp);
595 				mutex_exit(&thread_free_lock);
596 				break;
597 			}
598 			/*
599 			 * The thread may have exited between when we
600 			 * checked above, and when we got the p_lock.
601 			 */
602 			if (t->t_proc_flag & TP_LWPEXIT) {
603 				mutex_exit(plockp);
604 				exiting = 1;
605 			} else {
606 				exiting = 0;
607 			}
608 		}
609 		/*
610 		 * Either we have the p_lock for the thread's process,
611 		 * or we don't care about the thread structure any more.
612 		 * Either way we can drop thread_free_lock.
613 		 */
614 		mutex_exit(&thread_free_lock);
615 
616 		/*
617 		 * Update user, system, and idle cpu times.
618 		 */
619 		if (one_sec) {
620 			nrunning++;
621 			cp->cpu_part->cp_nrunning++;
622 		}
623 		/*
624 		 * If we haven't done tick processing for this
625 		 * lwp, then do it now. Since we don't hold the
626 		 * lwp down on a CPU it can migrate and show up
627 		 * more than once, hence the lbolt check.
628 		 *
629 		 * Also, make sure that it's okay to perform the
630 		 * tick processing before calling clock_tick.
631 		 * Setting thread_away to a TRUE value (ie. not 0)
632 		 * results in tick processing not being performed for
633 		 * that thread.  Or, in other words, keeps the thread
634 		 * away from clock_tick processing.
635 		 */
636 		thread_away = ((cp->cpu_flags & CPU_QUIESCED) ||
637 		    CPU_ON_INTR(cp) || intr ||
638 		    (cp->cpu_dispthread == cp->cpu_idle_thread) || exiting);
639 
640 		if ((!thread_away) && (lbolt - t->t_lbolt != 0)) {
641 			t->t_lbolt = lbolt;
642 			clock_tick(t);
643 		}
644 
645 		if (!exiting)
646 			mutex_exit(plockp);
647 	} while ((cp = cp->cpu_next) != clock_cpu_list);
648 
649 	clock_cpu_list = clock_cpu_list->cpu_next;
650 
651 	/*
652 	 * bump time in ticks
653 	 *
654 	 * We rely on there being only one clock thread and hence
655 	 * don't need a lock to protect lbolt.
656 	 */
657 	lbolt++;
658 	atomic_add_64((uint64_t *)&lbolt64, (int64_t)1);
659 
660 	/*
661 	 * Check for a callout that needs be called from the clock
662 	 * thread to support the membership protocol in a clustered
663 	 * system.  Copy the function pointer so that we can reset
664 	 * this to NULL if needed.
665 	 */
666 	if ((funcp = cmm_clock_callout) != NULL)
667 		(*funcp)();
668 
669 	if ((funcp = cpucaps_clock_callout) != NULL)
670 		(*funcp)();
671 
672 	/*
673 	 * Wakeup the cageout thread waiters once per second.
674 	 */
675 	if (one_sec)
676 		kcage_tick();
677 
678 	/*
679 	 * Schedule timeout() requests if any are due at this time.
680 	 */
681 	callout_schedule();
682 
683 	if (one_sec) {
684 
685 		int drift, absdrift;
686 		timestruc_t tod;
687 		int s;
688 
689 		/*
690 		 * Beginning of precision-kernel code fragment executed
691 		 * every second.
692 		 *
693 		 * On rollover of the second the phase adjustment to be
694 		 * used for the next second is calculated.  Also, the
695 		 * maximum error is increased by the tolerance.  If the
696 		 * PPS frequency discipline code is present, the phase is
697 		 * increased to compensate for the CPU clock oscillator
698 		 * frequency error.
699 		 *
700 		 * On a 32-bit machine and given parameters in the timex.h
701 		 * header file, the maximum phase adjustment is +-512 ms
702 		 * and maximum frequency offset is (a tad less than)
703 		 * +-512 ppm. On a 64-bit machine, you shouldn't need to ask.
704 		 */
705 		time_maxerror += time_tolerance / SCALE_USEC;
706 
707 		/*
708 		 * Leap second processing. If in leap-insert state at
709 		 * the end of the day, the system clock is set back one
710 		 * second; if in leap-delete state, the system clock is
711 		 * set ahead one second. The microtime() routine or
712 		 * external clock driver will insure that reported time
713 		 * is always monotonic. The ugly divides should be
714 		 * replaced.
715 		 */
716 		switch (time_state) {
717 
718 		case TIME_OK:
719 			if (time_status & STA_INS)
720 				time_state = TIME_INS;
721 			else if (time_status & STA_DEL)
722 				time_state = TIME_DEL;
723 			break;
724 
725 		case TIME_INS:
726 			if (hrestime.tv_sec % 86400 == 0) {
727 				s = hr_clock_lock();
728 				hrestime.tv_sec--;
729 				hr_clock_unlock(s);
730 				time_state = TIME_OOP;
731 			}
732 			break;
733 
734 		case TIME_DEL:
735 			if ((hrestime.tv_sec + 1) % 86400 == 0) {
736 				s = hr_clock_lock();
737 				hrestime.tv_sec++;
738 				hr_clock_unlock(s);
739 				time_state = TIME_WAIT;
740 			}
741 			break;
742 
743 		case TIME_OOP:
744 			time_state = TIME_WAIT;
745 			break;
746 
747 		case TIME_WAIT:
748 			if (!(time_status & (STA_INS | STA_DEL)))
749 				time_state = TIME_OK;
750 		default:
751 			break;
752 		}
753 
754 		/*
755 		 * Compute the phase adjustment for the next second. In
756 		 * PLL mode, the offset is reduced by a fixed factor
757 		 * times the time constant. In FLL mode the offset is
758 		 * used directly. In either mode, the maximum phase
759 		 * adjustment for each second is clamped so as to spread
760 		 * the adjustment over not more than the number of
761 		 * seconds between updates.
762 		 */
763 		if (time_offset == 0)
764 			time_adj = 0;
765 		else if (time_offset < 0) {
766 			lltemp = -time_offset;
767 			if (!(time_status & STA_FLL)) {
768 				if ((1 << time_constant) >= SCALE_KG)
769 					lltemp *= (1 << time_constant) /
770 					    SCALE_KG;
771 				else
772 					lltemp = (lltemp / SCALE_KG) >>
773 					    time_constant;
774 			}
775 			if (lltemp > (MAXPHASE / MINSEC) * SCALE_UPDATE)
776 				lltemp = (MAXPHASE / MINSEC) * SCALE_UPDATE;
777 			time_offset += lltemp;
778 			time_adj = -(lltemp * SCALE_PHASE) / hz / SCALE_UPDATE;
779 		} else {
780 			lltemp = time_offset;
781 			if (!(time_status & STA_FLL)) {
782 				if ((1 << time_constant) >= SCALE_KG)
783 					lltemp *= (1 << time_constant) /
784 					    SCALE_KG;
785 				else
786 					lltemp = (lltemp / SCALE_KG) >>
787 					    time_constant;
788 			}
789 			if (lltemp > (MAXPHASE / MINSEC) * SCALE_UPDATE)
790 				lltemp = (MAXPHASE / MINSEC) * SCALE_UPDATE;
791 			time_offset -= lltemp;
792 			time_adj = (lltemp * SCALE_PHASE) / hz / SCALE_UPDATE;
793 		}
794 
795 		/*
796 		 * Compute the frequency estimate and additional phase
797 		 * adjustment due to frequency error for the next
798 		 * second. When the PPS signal is engaged, gnaw on the
799 		 * watchdog counter and update the frequency computed by
800 		 * the pll and the PPS signal.
801 		 */
802 		pps_valid++;
803 		if (pps_valid == PPS_VALID) {
804 			pps_jitter = MAXTIME;
805 			pps_stabil = MAXFREQ;
806 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
807 			    STA_PPSWANDER | STA_PPSERROR);
808 		}
809 		lltemp = time_freq + pps_freq;
810 
811 		if (lltemp)
812 			time_adj += (lltemp * SCALE_PHASE) / (SCALE_USEC * hz);
813 
814 		/*
815 		 * End of precision kernel-code fragment
816 		 *
817 		 * The section below should be modified if we are planning
818 		 * to use NTP for synchronization.
819 		 *
820 		 * Note: the clock synchronization code now assumes
821 		 * the following:
822 		 *   - if dosynctodr is 1, then compute the drift between
823 		 *	the tod chip and software time and adjust one or
824 		 *	the other depending on the circumstances
825 		 *
826 		 *   - if dosynctodr is 0, then the tod chip is independent
827 		 *	of the software clock and should not be adjusted,
828 		 *	but allowed to free run.  this allows NTP to sync.
829 		 *	hrestime without any interference from the tod chip.
830 		 */
831 
832 		tod_validate_deferred = B_FALSE;
833 		mutex_enter(&tod_lock);
834 		tod = tod_get();
835 		drift = tod.tv_sec - hrestime.tv_sec;
836 		absdrift = (drift >= 0) ? drift : -drift;
837 		if (tod_needsync || absdrift > 1) {
838 			int s;
839 			if (absdrift > 2) {
840 				if (!tod_broken && tod_faulted == TOD_NOFAULT) {
841 					s = hr_clock_lock();
842 					hrestime = tod;
843 					membar_enter();	/* hrestime visible */
844 					timedelta = 0;
845 					hrestime_isvalid = 1;
846 					tod_needsync = 0;
847 					hr_clock_unlock(s);
848 				}
849 			} else {
850 				if (tod_needsync || !dosynctodr) {
851 					gethrestime(&tod);
852 					tod_set(tod);
853 					s = hr_clock_lock();
854 					if (timedelta == 0)
855 						tod_needsync = 0;
856 					hr_clock_unlock(s);
857 				} else {
858 					/*
859 					 * If the drift is 2 seconds on the
860 					 * money, then the TOD is adjusting
861 					 * the clock;  record that.
862 					 */
863 					clock_adj_hist[adj_hist_entry++ %
864 					    CLOCK_ADJ_HIST_SIZE] = lbolt64;
865 					s = hr_clock_lock();
866 					timedelta = (int64_t)drift*NANOSEC;
867 					hr_clock_unlock(s);
868 				}
869 			}
870 		}
871 		one_sec = 0;
872 		time = gethrestime_sec();  /* for crusty old kmem readers */
873 		mutex_exit(&tod_lock);
874 
875 		/*
876 		 * Some drivers still depend on this... XXX
877 		 */
878 		cv_broadcast(&lbolt_cv);
879 
880 		sysinfo.updates++;
881 		vminfo.freemem += freemem;
882 		{
883 			pgcnt_t maxswap, resv, free;
884 			pgcnt_t avail =
885 			    MAX((spgcnt_t)(availrmem - swapfs_minfree), 0);
886 
887 			maxswap = k_anoninfo.ani_mem_resv
888 					+ k_anoninfo.ani_max +avail;
889 			free = k_anoninfo.ani_free + avail;
890 			resv = k_anoninfo.ani_phys_resv +
891 			    k_anoninfo.ani_mem_resv;
892 
893 			vminfo.swap_resv += resv;
894 			/* number of reserved and allocated pages */
895 #ifdef	DEBUG
896 			if (maxswap < free)
897 				cmn_err(CE_WARN, "clock: maxswap < free");
898 			if (maxswap < resv)
899 				cmn_err(CE_WARN, "clock: maxswap < resv");
900 #endif
901 			vminfo.swap_alloc += maxswap - free;
902 			vminfo.swap_avail += maxswap - resv;
903 			vminfo.swap_free += free;
904 		}
905 		if (nrunnable) {
906 			sysinfo.runque += nrunnable;
907 			sysinfo.runocc++;
908 		}
909 		if (nswapped) {
910 			sysinfo.swpque += nswapped;
911 			sysinfo.swpocc++;
912 		}
913 		sysinfo.waiting += w_io;
914 
915 		/*
916 		 * Wake up fsflush to write out DELWRI
917 		 * buffers, dirty pages and other cached
918 		 * administrative data, e.g. inodes.
919 		 */
920 		if (--fsflushcnt <= 0) {
921 			fsflushcnt = tune.t_fsflushr;
922 			cv_signal(&fsflush_cv);
923 		}
924 
925 		vmmeter();
926 		calcloadavg(genloadavg(&loadavg), hp_avenrun);
927 		for (i = 0; i < 3; i++)
928 			/*
929 			 * At the moment avenrun[] can only hold 31
930 			 * bits of load average as it is a signed
931 			 * int in the API. We need to ensure that
932 			 * hp_avenrun[i] >> (16 - FSHIFT) will not be
933 			 * too large. If it is, we put the largest value
934 			 * that we can use into avenrun[i]. This is
935 			 * kludgey, but about all we can do until we
936 			 * avenrun[] is declared as an array of uint64[]
937 			 */
938 			if (hp_avenrun[i] < ((uint64_t)1<<(31+16-FSHIFT)))
939 				avenrun[i] = (int32_t)(hp_avenrun[i] >>
940 				    (16 - FSHIFT));
941 			else
942 				avenrun[i] = 0x7fffffff;
943 
944 		cpupart = cp_list_head;
945 		do {
946 			calcloadavg(genloadavg(&cpupart->cp_loadavg),
947 			    cpupart->cp_hp_avenrun);
948 		} while ((cpupart = cpupart->cp_next) != cp_list_head);
949 
950 		/*
951 		 * Wake up the swapper thread if necessary.
952 		 */
953 		if (runin ||
954 		    (runout && (avefree < desfree || wake_sched_sec))) {
955 			t = &t0;
956 			thread_lock(t);
957 			if (t->t_state == TS_STOPPED) {
958 				runin = runout = 0;
959 				wake_sched_sec = 0;
960 				t->t_whystop = 0;
961 				t->t_whatstop = 0;
962 				t->t_schedflag &= ~TS_ALLSTART;
963 				THREAD_TRANSITION(t);
964 				setfrontdq(t);
965 			}
966 			thread_unlock(t);
967 		}
968 	}
969 
970 	/*
971 	 * Wake up the swapper if any high priority swapped-out threads
972 	 * became runable during the last tick.
973 	 */
974 	if (wake_sched) {
975 		t = &t0;
976 		thread_lock(t);
977 		if (t->t_state == TS_STOPPED) {
978 			runin = runout = 0;
979 			wake_sched = 0;
980 			t->t_whystop = 0;
981 			t->t_whatstop = 0;
982 			t->t_schedflag &= ~TS_ALLSTART;
983 			THREAD_TRANSITION(t);
984 			setfrontdq(t);
985 		}
986 		thread_unlock(t);
987 	}
988 }
989 
990 void
991 clock_init(void)
992 {
993 	cyc_handler_t hdlr;
994 	cyc_time_t when;
995 
996 	hdlr.cyh_func = (cyc_func_t)clock;
997 	hdlr.cyh_level = CY_LOCK_LEVEL;
998 	hdlr.cyh_arg = NULL;
999 
1000 	when.cyt_when = 0;
1001 	when.cyt_interval = nsec_per_tick;
1002 
1003 	mutex_enter(&cpu_lock);
1004 	clock_cyclic = cyclic_add(&hdlr, &when);
1005 	mutex_exit(&cpu_lock);
1006 }
1007 
1008 /*
1009  * Called before calcloadavg to get 10-sec moving loadavg together
1010  */
1011 
1012 static int
1013 genloadavg(struct loadavg_s *avgs)
1014 {
1015 	int avg;
1016 	int spos; /* starting position */
1017 	int cpos; /* moving current position */
1018 	int i;
1019 	int slen;
1020 	hrtime_t hr_avg;
1021 
1022 	/* 10-second snapshot, calculate first positon */
1023 	if (avgs->lg_len == 0) {
1024 		return (0);
1025 	}
1026 	slen = avgs->lg_len < S_MOVAVG_SZ ? avgs->lg_len : S_MOVAVG_SZ;
1027 
1028 	spos = (avgs->lg_cur - 1) >= 0 ? avgs->lg_cur - 1 :
1029 	    S_LOADAVG_SZ + (avgs->lg_cur - 1);
1030 	for (i = hr_avg = 0; i < slen; i++) {
1031 		cpos = (spos - i) >= 0 ? spos - i : S_LOADAVG_SZ + (spos - i);
1032 		hr_avg += avgs->lg_loads[cpos];
1033 	}
1034 
1035 	hr_avg = hr_avg / slen;
1036 	avg = hr_avg / (NANOSEC / LGRP_LOADAVG_IN_THREAD_MAX);
1037 
1038 	return (avg);
1039 }
1040 
1041 /*
1042  * Run every second from clock () to update the loadavg count available to the
1043  * system and cpu-partitions.
1044  *
1045  * This works by sampling the previous usr, sys, wait time elapsed,
1046  * computing a delta, and adding that delta to the elapsed usr, sys,
1047  * wait increase.
1048  */
1049 
1050 static void
1051 loadavg_update()
1052 {
1053 	cpu_t *cp;
1054 	cpupart_t *cpupart;
1055 	hrtime_t cpu_total;
1056 	int prev;
1057 
1058 	cp = cpu_list;
1059 	loadavg.lg_total = 0;
1060 
1061 	/*
1062 	 * first pass totals up per-cpu statistics for system and cpu
1063 	 * partitions
1064 	 */
1065 
1066 	do {
1067 		struct loadavg_s *lavg;
1068 
1069 		lavg = &cp->cpu_loadavg;
1070 
1071 		cpu_total = cp->cpu_acct[CMS_USER] +
1072 		    cp->cpu_acct[CMS_SYSTEM] + cp->cpu_waitrq;
1073 		/* compute delta against last total */
1074 		scalehrtime(&cpu_total);
1075 		prev = (lavg->lg_cur - 1) >= 0 ? lavg->lg_cur - 1 :
1076 		    S_LOADAVG_SZ + (lavg->lg_cur - 1);
1077 		if (lavg->lg_loads[prev] <= 0) {
1078 			lavg->lg_loads[lavg->lg_cur] = cpu_total;
1079 			cpu_total = 0;
1080 		} else {
1081 			lavg->lg_loads[lavg->lg_cur] = cpu_total;
1082 			cpu_total = cpu_total - lavg->lg_loads[prev];
1083 			if (cpu_total < 0)
1084 				cpu_total = 0;
1085 		}
1086 
1087 		lavg->lg_cur = (lavg->lg_cur + 1) % S_LOADAVG_SZ;
1088 		lavg->lg_len = (lavg->lg_len + 1) < S_LOADAVG_SZ ?
1089 		    lavg->lg_len + 1 : S_LOADAVG_SZ;
1090 
1091 		loadavg.lg_total += cpu_total;
1092 		cp->cpu_part->cp_loadavg.lg_total += cpu_total;
1093 
1094 	} while ((cp = cp->cpu_next) != cpu_list);
1095 
1096 	loadavg.lg_loads[loadavg.lg_cur] = loadavg.lg_total;
1097 	loadavg.lg_cur = (loadavg.lg_cur + 1) % S_LOADAVG_SZ;
1098 	loadavg.lg_len = (loadavg.lg_len + 1) < S_LOADAVG_SZ ?
1099 	    loadavg.lg_len + 1 : S_LOADAVG_SZ;
1100 	/*
1101 	 * Second pass updates counts
1102 	 */
1103 	cpupart = cp_list_head;
1104 
1105 	do {
1106 		struct loadavg_s *lavg;
1107 
1108 		lavg = &cpupart->cp_loadavg;
1109 		lavg->lg_loads[lavg->lg_cur] = lavg->lg_total;
1110 		lavg->lg_total = 0;
1111 		lavg->lg_cur = (lavg->lg_cur + 1) % S_LOADAVG_SZ;
1112 		lavg->lg_len = (lavg->lg_len + 1) < S_LOADAVG_SZ ?
1113 		    lavg->lg_len + 1 : S_LOADAVG_SZ;
1114 
1115 	} while ((cpupart = cpupart->cp_next) != cp_list_head);
1116 
1117 }
1118 
1119 /*
1120  * clock_update() - local clock update
1121  *
1122  * This routine is called by ntp_adjtime() to update the local clock
1123  * phase and frequency. The implementation is of an
1124  * adaptive-parameter, hybrid phase/frequency-lock loop (PLL/FLL). The
1125  * routine computes new time and frequency offset estimates for each
1126  * call.  The PPS signal itself determines the new time offset,
1127  * instead of the calling argument.  Presumably, calls to
1128  * ntp_adjtime() occur only when the caller believes the local clock
1129  * is valid within some bound (+-128 ms with NTP). If the caller's
1130  * time is far different than the PPS time, an argument will ensue,
1131  * and it's not clear who will lose.
1132  *
1133  * For uncompensated quartz crystal oscillatores and nominal update
1134  * intervals less than 1024 s, operation should be in phase-lock mode
1135  * (STA_FLL = 0), where the loop is disciplined to phase. For update
1136  * intervals greater than this, operation should be in frequency-lock
1137  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1138  *
1139  * Note: mutex(&tod_lock) is in effect.
1140  */
1141 void
1142 clock_update(int offset)
1143 {
1144 	int ltemp, mtemp, s;
1145 
1146 	ASSERT(MUTEX_HELD(&tod_lock));
1147 
1148 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1149 		return;
1150 	ltemp = offset;
1151 	if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL))
1152 		ltemp = pps_offset;
1153 
1154 	/*
1155 	 * Scale the phase adjustment and clamp to the operating range.
1156 	 */
1157 	if (ltemp > MAXPHASE)
1158 		time_offset = MAXPHASE * SCALE_UPDATE;
1159 	else if (ltemp < -MAXPHASE)
1160 		time_offset = -(MAXPHASE * SCALE_UPDATE);
1161 	else
1162 		time_offset = ltemp * SCALE_UPDATE;
1163 
1164 	/*
1165 	 * Select whether the frequency is to be controlled and in which
1166 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
1167 	 * multiply/divide should be replaced someday.
1168 	 */
1169 	if (time_status & STA_FREQHOLD || time_reftime == 0)
1170 		time_reftime = hrestime.tv_sec;
1171 
1172 	mtemp = hrestime.tv_sec - time_reftime;
1173 	time_reftime = hrestime.tv_sec;
1174 
1175 	if (time_status & STA_FLL) {
1176 		if (mtemp >= MINSEC) {
1177 			ltemp = ((time_offset / mtemp) * (SCALE_USEC /
1178 			    SCALE_UPDATE));
1179 			if (ltemp)
1180 				time_freq += ltemp / SCALE_KH;
1181 		}
1182 	} else {
1183 		if (mtemp < MAXSEC) {
1184 			ltemp *= mtemp;
1185 			if (ltemp)
1186 				time_freq += (int)(((int64_t)ltemp *
1187 				    SCALE_USEC) / SCALE_KF)
1188 				    / (1 << (time_constant * 2));
1189 		}
1190 	}
1191 	if (time_freq > time_tolerance)
1192 		time_freq = time_tolerance;
1193 	else if (time_freq < -time_tolerance)
1194 		time_freq = -time_tolerance;
1195 
1196 	s = hr_clock_lock();
1197 	tod_needsync = 1;
1198 	hr_clock_unlock(s);
1199 }
1200 
1201 /*
1202  * ddi_hardpps() - discipline CPU clock oscillator to external PPS signal
1203  *
1204  * This routine is called at each PPS interrupt in order to discipline
1205  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1206  * and leaves it in a handy spot for the clock() routine. It
1207  * integrates successive PPS phase differences and calculates the
1208  * frequency offset. This is used in clock() to discipline the CPU
1209  * clock oscillator so that intrinsic frequency error is cancelled out.
1210  * The code requires the caller to capture the time and hardware counter
1211  * value at the on-time PPS signal transition.
1212  *
1213  * Note that, on some Unix systems, this routine runs at an interrupt
1214  * priority level higher than the timer interrupt routine clock().
1215  * Therefore, the variables used are distinct from the clock()
1216  * variables, except for certain exceptions: The PPS frequency pps_freq
1217  * and phase pps_offset variables are determined by this routine and
1218  * updated atomically. The time_tolerance variable can be considered a
1219  * constant, since it is infrequently changed, and then only when the
1220  * PPS signal is disabled. The watchdog counter pps_valid is updated
1221  * once per second by clock() and is atomically cleared in this
1222  * routine.
1223  *
1224  * tvp is the time of the last tick; usec is a microsecond count since the
1225  * last tick.
1226  *
1227  * Note: In Solaris systems, the tick value is actually given by
1228  *       usec_per_tick.  This is called from the serial driver cdintr(),
1229  *	 or equivalent, at a high PIL.  Because the kernel keeps a
1230  *	 highresolution time, the following code can accept either
1231  *	 the traditional argument pair, or the current highres timestamp
1232  *       in tvp and zero in usec.
1233  */
1234 void
1235 ddi_hardpps(struct timeval *tvp, int usec)
1236 {
1237 	int u_usec, v_usec, bigtick;
1238 	time_t cal_sec;
1239 	int cal_usec;
1240 
1241 	/*
1242 	 * An occasional glitch can be produced when the PPS interrupt
1243 	 * occurs in the clock() routine before the time variable is
1244 	 * updated. Here the offset is discarded when the difference
1245 	 * between it and the last one is greater than tick/2, but not
1246 	 * if the interval since the first discard exceeds 30 s.
1247 	 */
1248 	time_status |= STA_PPSSIGNAL;
1249 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1250 	pps_valid = 0;
1251 	u_usec = -tvp->tv_usec;
1252 	if (u_usec < -(MICROSEC/2))
1253 		u_usec += MICROSEC;
1254 	v_usec = pps_offset - u_usec;
1255 	if (v_usec < 0)
1256 		v_usec = -v_usec;
1257 	if (v_usec > (usec_per_tick >> 1)) {
1258 		if (pps_glitch > MAXGLITCH) {
1259 			pps_glitch = 0;
1260 			pps_tf[2] = u_usec;
1261 			pps_tf[1] = u_usec;
1262 		} else {
1263 			pps_glitch++;
1264 			u_usec = pps_offset;
1265 		}
1266 	} else
1267 		pps_glitch = 0;
1268 
1269 	/*
1270 	 * A three-stage median filter is used to help deglitch the pps
1271 	 * time. The median sample becomes the time offset estimate; the
1272 	 * difference between the other two samples becomes the time
1273 	 * dispersion (jitter) estimate.
1274 	 */
1275 	pps_tf[2] = pps_tf[1];
1276 	pps_tf[1] = pps_tf[0];
1277 	pps_tf[0] = u_usec;
1278 	if (pps_tf[0] > pps_tf[1]) {
1279 		if (pps_tf[1] > pps_tf[2]) {
1280 			pps_offset = pps_tf[1];		/* 0 1 2 */
1281 			v_usec = pps_tf[0] - pps_tf[2];
1282 		} else if (pps_tf[2] > pps_tf[0]) {
1283 			pps_offset = pps_tf[0];		/* 2 0 1 */
1284 			v_usec = pps_tf[2] - pps_tf[1];
1285 		} else {
1286 			pps_offset = pps_tf[2];		/* 0 2 1 */
1287 			v_usec = pps_tf[0] - pps_tf[1];
1288 		}
1289 	} else {
1290 		if (pps_tf[1] < pps_tf[2]) {
1291 			pps_offset = pps_tf[1];		/* 2 1 0 */
1292 			v_usec = pps_tf[2] - pps_tf[0];
1293 		} else  if (pps_tf[2] < pps_tf[0]) {
1294 			pps_offset = pps_tf[0];		/* 1 0 2 */
1295 			v_usec = pps_tf[1] - pps_tf[2];
1296 		} else {
1297 			pps_offset = pps_tf[2];		/* 1 2 0 */
1298 			v_usec = pps_tf[1] - pps_tf[0];
1299 		}
1300 	}
1301 	if (v_usec > MAXTIME)
1302 		pps_jitcnt++;
1303 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1304 	pps_jitter += v_usec / (1 << PPS_AVG);
1305 	if (pps_jitter > (MAXTIME >> 1))
1306 		time_status |= STA_PPSJITTER;
1307 
1308 	/*
1309 	 * During the calibration interval adjust the starting time when
1310 	 * the tick overflows. At the end of the interval compute the
1311 	 * duration of the interval and the difference of the hardware
1312 	 * counters at the beginning and end of the interval. This code
1313 	 * is deliciously complicated by the fact valid differences may
1314 	 * exceed the value of tick when using long calibration
1315 	 * intervals and small ticks. Note that the counter can be
1316 	 * greater than tick if caught at just the wrong instant, but
1317 	 * the values returned and used here are correct.
1318 	 */
1319 	bigtick = (int)usec_per_tick * SCALE_USEC;
1320 	pps_usec -= pps_freq;
1321 	if (pps_usec >= bigtick)
1322 		pps_usec -= bigtick;
1323 	if (pps_usec < 0)
1324 		pps_usec += bigtick;
1325 	pps_time.tv_sec++;
1326 	pps_count++;
1327 	if (pps_count < (1 << pps_shift))
1328 		return;
1329 	pps_count = 0;
1330 	pps_calcnt++;
1331 	u_usec = usec * SCALE_USEC;
1332 	v_usec = pps_usec - u_usec;
1333 	if (v_usec >= bigtick >> 1)
1334 		v_usec -= bigtick;
1335 	if (v_usec < -(bigtick >> 1))
1336 		v_usec += bigtick;
1337 	if (v_usec < 0)
1338 		v_usec = -(-v_usec >> pps_shift);
1339 	else
1340 		v_usec = v_usec >> pps_shift;
1341 	pps_usec = u_usec;
1342 	cal_sec = tvp->tv_sec;
1343 	cal_usec = tvp->tv_usec;
1344 	cal_sec -= pps_time.tv_sec;
1345 	cal_usec -= pps_time.tv_usec;
1346 	if (cal_usec < 0) {
1347 		cal_usec += MICROSEC;
1348 		cal_sec--;
1349 	}
1350 	pps_time = *tvp;
1351 
1352 	/*
1353 	 * Check for lost interrupts, noise, excessive jitter and
1354 	 * excessive frequency error. The number of timer ticks during
1355 	 * the interval may vary +-1 tick. Add to this a margin of one
1356 	 * tick for the PPS signal jitter and maximum frequency
1357 	 * deviation. If the limits are exceeded, the calibration
1358 	 * interval is reset to the minimum and we start over.
1359 	 */
1360 	u_usec = (int)usec_per_tick << 1;
1361 	if (!((cal_sec == -1 && cal_usec > (MICROSEC - u_usec)) ||
1362 	    (cal_sec == 0 && cal_usec < u_usec)) ||
1363 	    v_usec > time_tolerance || v_usec < -time_tolerance) {
1364 		pps_errcnt++;
1365 		pps_shift = PPS_SHIFT;
1366 		pps_intcnt = 0;
1367 		time_status |= STA_PPSERROR;
1368 		return;
1369 	}
1370 
1371 	/*
1372 	 * A three-stage median filter is used to help deglitch the pps
1373 	 * frequency. The median sample becomes the frequency offset
1374 	 * estimate; the difference between the other two samples
1375 	 * becomes the frequency dispersion (stability) estimate.
1376 	 */
1377 	pps_ff[2] = pps_ff[1];
1378 	pps_ff[1] = pps_ff[0];
1379 	pps_ff[0] = v_usec;
1380 	if (pps_ff[0] > pps_ff[1]) {
1381 		if (pps_ff[1] > pps_ff[2]) {
1382 			u_usec = pps_ff[1];		/* 0 1 2 */
1383 			v_usec = pps_ff[0] - pps_ff[2];
1384 		} else if (pps_ff[2] > pps_ff[0]) {
1385 			u_usec = pps_ff[0];		/* 2 0 1 */
1386 			v_usec = pps_ff[2] - pps_ff[1];
1387 		} else {
1388 			u_usec = pps_ff[2];		/* 0 2 1 */
1389 			v_usec = pps_ff[0] - pps_ff[1];
1390 		}
1391 	} else {
1392 		if (pps_ff[1] < pps_ff[2]) {
1393 			u_usec = pps_ff[1];		/* 2 1 0 */
1394 			v_usec = pps_ff[2] - pps_ff[0];
1395 		} else  if (pps_ff[2] < pps_ff[0]) {
1396 			u_usec = pps_ff[0];		/* 1 0 2 */
1397 			v_usec = pps_ff[1] - pps_ff[2];
1398 		} else {
1399 			u_usec = pps_ff[2];		/* 1 2 0 */
1400 			v_usec = pps_ff[1] - pps_ff[0];
1401 		}
1402 	}
1403 
1404 	/*
1405 	 * Here the frequency dispersion (stability) is updated. If it
1406 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1407 	 * offset is updated as well, but clamped to the tolerance. It
1408 	 * will be processed later by the clock() routine.
1409 	 */
1410 	v_usec = (v_usec >> 1) - pps_stabil;
1411 	if (v_usec < 0)
1412 		pps_stabil -= -v_usec >> PPS_AVG;
1413 	else
1414 		pps_stabil += v_usec >> PPS_AVG;
1415 	if (pps_stabil > MAXFREQ >> 2) {
1416 		pps_stbcnt++;
1417 		time_status |= STA_PPSWANDER;
1418 		return;
1419 	}
1420 	if (time_status & STA_PPSFREQ) {
1421 		if (u_usec < 0) {
1422 			pps_freq -= -u_usec >> PPS_AVG;
1423 			if (pps_freq < -time_tolerance)
1424 				pps_freq = -time_tolerance;
1425 			u_usec = -u_usec;
1426 		} else {
1427 			pps_freq += u_usec >> PPS_AVG;
1428 			if (pps_freq > time_tolerance)
1429 				pps_freq = time_tolerance;
1430 		}
1431 	}
1432 
1433 	/*
1434 	 * Here the calibration interval is adjusted. If the maximum
1435 	 * time difference is greater than tick / 4, reduce the interval
1436 	 * by half. If this is not the case for four consecutive
1437 	 * intervals, double the interval.
1438 	 */
1439 	if (u_usec << pps_shift > bigtick >> 2) {
1440 		pps_intcnt = 0;
1441 		if (pps_shift > PPS_SHIFT)
1442 			pps_shift--;
1443 	} else if (pps_intcnt >= 4) {
1444 		pps_intcnt = 0;
1445 		if (pps_shift < PPS_SHIFTMAX)
1446 			pps_shift++;
1447 	} else
1448 		pps_intcnt++;
1449 
1450 	/*
1451 	 * If recovering from kmdb, then make sure the tod chip gets resynced.
1452 	 * If we took an early exit above, then we don't yet have a stable
1453 	 * calibration signal to lock onto, so don't mark the tod for sync
1454 	 * until we get all the way here.
1455 	 */
1456 	{
1457 		int s = hr_clock_lock();
1458 
1459 		tod_needsync = 1;
1460 		hr_clock_unlock(s);
1461 	}
1462 }
1463 
1464 /*
1465  * Handle clock tick processing for a thread.
1466  * Check for timer action, enforce CPU rlimit, do profiling etc.
1467  */
1468 void
1469 clock_tick(kthread_t *t)
1470 {
1471 	struct proc *pp;
1472 	klwp_id_t    lwp;
1473 	struct as *as;
1474 	clock_t	utime;
1475 	clock_t	stime;
1476 	int	poke = 0;		/* notify another CPU */
1477 	int	user_mode;
1478 	size_t	 rss;
1479 
1480 	/* Must be operating on a lwp/thread */
1481 	if ((lwp = ttolwp(t)) == NULL) {
1482 		panic("clock_tick: no lwp");
1483 		/*NOTREACHED*/
1484 	}
1485 
1486 	CL_TICK(t);	/* Class specific tick processing */
1487 	DTRACE_SCHED1(tick, kthread_t *, t);
1488 
1489 	pp = ttoproc(t);
1490 
1491 	/* pp->p_lock makes sure that the thread does not exit */
1492 	ASSERT(MUTEX_HELD(&pp->p_lock));
1493 
1494 	user_mode = (lwp->lwp_state == LWP_USER);
1495 
1496 	/*
1497 	 * Update process times. Should use high res clock and state
1498 	 * changes instead of statistical sampling method. XXX
1499 	 */
1500 	if (user_mode) {
1501 		pp->p_utime++;
1502 		pp->p_task->tk_cpu_time++;
1503 	} else {
1504 		pp->p_stime++;
1505 		pp->p_task->tk_cpu_time++;
1506 	}
1507 	as = pp->p_as;
1508 
1509 	/*
1510 	 * Update user profiling statistics. Get the pc from the
1511 	 * lwp when the AST happens.
1512 	 */
1513 	if (pp->p_prof.pr_scale) {
1514 		atomic_add_32(&lwp->lwp_oweupc, 1);
1515 		if (user_mode) {
1516 			poke = 1;
1517 			aston(t);
1518 		}
1519 	}
1520 
1521 	utime = pp->p_utime;
1522 	stime = pp->p_stime;
1523 
1524 	/*
1525 	 * If CPU was in user state, process lwp-virtual time
1526 	 * interval timer.
1527 	 */
1528 	if (user_mode &&
1529 	    timerisset(&lwp->lwp_timer[ITIMER_VIRTUAL].it_value) &&
1530 	    itimerdecr(&lwp->lwp_timer[ITIMER_VIRTUAL], usec_per_tick) == 0) {
1531 		poke = 1;
1532 		sigtoproc(pp, t, SIGVTALRM);
1533 	}
1534 
1535 	if (timerisset(&lwp->lwp_timer[ITIMER_PROF].it_value) &&
1536 	    itimerdecr(&lwp->lwp_timer[ITIMER_PROF], usec_per_tick) == 0) {
1537 		poke = 1;
1538 		sigtoproc(pp, t, SIGPROF);
1539 	}
1540 
1541 	/*
1542 	 * Enforce CPU resource controls:
1543 	 *   (a) process.max-cpu-time resource control
1544 	 */
1545 	(void) rctl_test(rctlproc_legacy[RLIMIT_CPU], pp->p_rctls, pp,
1546 	    (utime + stime)/hz, RCA_UNSAFE_SIGINFO);
1547 
1548 	/*
1549 	 *   (b) task.max-cpu-time resource control
1550 	 */
1551 	(void) rctl_test(rc_task_cpu_time, pp->p_task->tk_rctls, pp, 1,
1552 	    RCA_UNSAFE_SIGINFO);
1553 
1554 	/*
1555 	 * Update memory usage for the currently running process.
1556 	 */
1557 	rss = rm_asrss(as);
1558 	PTOU(pp)->u_mem += rss;
1559 	if (rss > PTOU(pp)->u_mem_max)
1560 		PTOU(pp)->u_mem_max = rss;
1561 
1562 	/*
1563 	 * Notify the CPU the thread is running on.
1564 	 */
1565 	if (poke && t->t_cpu != CPU)
1566 		poke_cpu(t->t_cpu->cpu_id);
1567 }
1568 
1569 void
1570 profil_tick(uintptr_t upc)
1571 {
1572 	int ticks;
1573 	proc_t *p = ttoproc(curthread);
1574 	klwp_t *lwp = ttolwp(curthread);
1575 	struct prof *pr = &p->p_prof;
1576 
1577 	do {
1578 		ticks = lwp->lwp_oweupc;
1579 	} while (cas32(&lwp->lwp_oweupc, ticks, 0) != ticks);
1580 
1581 	mutex_enter(&p->p_pflock);
1582 	if (pr->pr_scale >= 2 && upc >= pr->pr_off) {
1583 		/*
1584 		 * Old-style profiling
1585 		 */
1586 		uint16_t *slot = pr->pr_base;
1587 		uint16_t old, new;
1588 		if (pr->pr_scale != 2) {
1589 			uintptr_t delta = upc - pr->pr_off;
1590 			uintptr_t byteoff = ((delta >> 16) * pr->pr_scale) +
1591 			    (((delta & 0xffff) * pr->pr_scale) >> 16);
1592 			if (byteoff >= (uintptr_t)pr->pr_size) {
1593 				mutex_exit(&p->p_pflock);
1594 				return;
1595 			}
1596 			slot += byteoff / sizeof (uint16_t);
1597 		}
1598 		if (fuword16(slot, &old) < 0 ||
1599 		    (new = old + ticks) > SHRT_MAX ||
1600 		    suword16(slot, new) < 0) {
1601 			pr->pr_scale = 0;
1602 		}
1603 	} else if (pr->pr_scale == 1) {
1604 		/*
1605 		 * PC Sampling
1606 		 */
1607 		model_t model = lwp_getdatamodel(lwp);
1608 		int result;
1609 #ifdef __lint
1610 		model = model;
1611 #endif
1612 		while (ticks-- > 0) {
1613 			if (pr->pr_samples == pr->pr_size) {
1614 				/* buffer full, turn off sampling */
1615 				pr->pr_scale = 0;
1616 				break;
1617 			}
1618 			switch (SIZEOF_PTR(model)) {
1619 			case sizeof (uint32_t):
1620 				result = suword32(pr->pr_base, (uint32_t)upc);
1621 				break;
1622 #ifdef _LP64
1623 			case sizeof (uint64_t):
1624 				result = suword64(pr->pr_base, (uint64_t)upc);
1625 				break;
1626 #endif
1627 			default:
1628 				cmn_err(CE_WARN, "profil_tick: unexpected "
1629 				    "data model");
1630 				result = -1;
1631 				break;
1632 			}
1633 			if (result != 0) {
1634 				pr->pr_scale = 0;
1635 				break;
1636 			}
1637 			pr->pr_base = (caddr_t)pr->pr_base + SIZEOF_PTR(model);
1638 			pr->pr_samples++;
1639 		}
1640 	}
1641 	mutex_exit(&p->p_pflock);
1642 }
1643 
1644 static void
1645 delay_wakeup(void *arg)
1646 {
1647 	kthread_t *t = arg;
1648 
1649 	mutex_enter(&t->t_delay_lock);
1650 	cv_signal(&t->t_delay_cv);
1651 	mutex_exit(&t->t_delay_lock);
1652 }
1653 
1654 void
1655 delay(clock_t ticks)
1656 {
1657 	kthread_t *t = curthread;
1658 	clock_t deadline = lbolt + ticks;
1659 	clock_t timeleft;
1660 	timeout_id_t id;
1661 
1662 	if (panicstr && ticks > 0) {
1663 		/*
1664 		 * Timeouts aren't running, so all we can do is spin.
1665 		 */
1666 		drv_usecwait(TICK_TO_USEC(ticks));
1667 		return;
1668 	}
1669 
1670 	while ((timeleft = deadline - lbolt) > 0) {
1671 		mutex_enter(&t->t_delay_lock);
1672 		id = timeout(delay_wakeup, t, timeleft);
1673 		cv_wait(&t->t_delay_cv, &t->t_delay_lock);
1674 		mutex_exit(&t->t_delay_lock);
1675 		(void) untimeout(id);
1676 	}
1677 }
1678 
1679 /*
1680  * Like delay, but interruptible by a signal.
1681  */
1682 int
1683 delay_sig(clock_t ticks)
1684 {
1685 	clock_t deadline = lbolt + ticks;
1686 	clock_t rc;
1687 
1688 	mutex_enter(&curthread->t_delay_lock);
1689 	do {
1690 		rc = cv_timedwait_sig(&curthread->t_delay_cv,
1691 		    &curthread->t_delay_lock, deadline);
1692 	} while (rc > 0);
1693 	mutex_exit(&curthread->t_delay_lock);
1694 	if (rc == 0)
1695 		return (EINTR);
1696 	return (0);
1697 }
1698 
1699 #define	SECONDS_PER_DAY 86400
1700 
1701 /*
1702  * Initialize the system time based on the TOD chip.  approx is used as
1703  * an approximation of time (e.g. from the filesystem) in the event that
1704  * the TOD chip has been cleared or is unresponsive.  An approx of -1
1705  * means the filesystem doesn't keep time.
1706  */
1707 void
1708 clkset(time_t approx)
1709 {
1710 	timestruc_t ts;
1711 	int spl;
1712 	int set_clock = 0;
1713 
1714 	mutex_enter(&tod_lock);
1715 	ts = tod_get();
1716 
1717 	if (ts.tv_sec > 365 * SECONDS_PER_DAY) {
1718 		/*
1719 		 * If the TOD chip is reporting some time after 1971,
1720 		 * then it probably didn't lose power or become otherwise
1721 		 * cleared in the recent past;  check to assure that
1722 		 * the time coming from the filesystem isn't in the future
1723 		 * according to the TOD chip.
1724 		 */
1725 		if (approx != -1 && approx > ts.tv_sec) {
1726 			cmn_err(CE_WARN, "Last shutdown is later "
1727 			    "than time on time-of-day chip; check date.");
1728 		}
1729 	} else {
1730 		/*
1731 		 * If the TOD chip isn't giving correct time, then set it to
1732 		 * the time that was passed in as a rough estimate.  If we
1733 		 * don't have an estimate, then set the clock back to a time
1734 		 * when Oliver North, ALF and Dire Straits were all on the
1735 		 * collective brain:  1987.
1736 		 */
1737 		timestruc_t tmp;
1738 		if (approx == -1)
1739 			ts.tv_sec = (1987 - 1970) * 365 * SECONDS_PER_DAY;
1740 		else
1741 			ts.tv_sec = approx;
1742 		ts.tv_nsec = 0;
1743 
1744 		/*
1745 		 * Attempt to write the new time to the TOD chip.  Set spl high
1746 		 * to avoid getting preempted between the tod_set and tod_get.
1747 		 */
1748 		spl = splhi();
1749 		tod_set(ts);
1750 		tmp = tod_get();
1751 		splx(spl);
1752 
1753 		if (tmp.tv_sec != ts.tv_sec && tmp.tv_sec != ts.tv_sec + 1) {
1754 			tod_broken = 1;
1755 			dosynctodr = 0;
1756 			cmn_err(CE_WARN, "Time-of-day chip unresponsive;"
1757 			    " dead batteries?");
1758 		} else {
1759 			cmn_err(CE_WARN, "Time-of-day chip had "
1760 			    "incorrect date; check and reset.");
1761 		}
1762 		set_clock = 1;
1763 	}
1764 
1765 	if (!boot_time) {
1766 		boot_time = ts.tv_sec;
1767 		set_clock = 1;
1768 	}
1769 
1770 	if (set_clock)
1771 		set_hrestime(&ts);
1772 
1773 	mutex_exit(&tod_lock);
1774 }
1775 
1776 int	hrestime_isvalid = 0;
1777 
1778 void
1779 set_hrestime(timestruc_t *ts)
1780 {
1781 	int spl = hr_clock_lock();
1782 	hrestime = *ts;
1783 	/*
1784 	 * hrestime must be visible before hrestime_isvalid
1785 	 * is set to 1
1786 	 */
1787 	membar_enter();
1788 	timedelta = 0;
1789 	hrestime_isvalid = 1;
1790 	hr_clock_unlock(spl);
1791 }
1792 
1793 static uint_t deadman_seconds;
1794 static uint32_t deadman_panics;
1795 static int deadman_enabled = 0;
1796 static int deadman_panic_timers = 1;
1797 
1798 static void
1799 deadman(void)
1800 {
1801 	if (panicstr) {
1802 		/*
1803 		 * During panic, other CPUs besides the panic
1804 		 * master continue to handle cyclics and some other
1805 		 * interrupts.  The code below is intended to be
1806 		 * single threaded, so any CPU other than the master
1807 		 * must keep out.
1808 		 */
1809 		if (CPU->cpu_id != panic_cpu.cpu_id)
1810 			return;
1811 
1812 		/*
1813 		 * If we're panicking, the deadman cyclic continues to increase
1814 		 * lbolt in case the dump device driver relies on this for
1815 		 * timeouts.  Note that we rely on deadman() being invoked once
1816 		 * per second, and credit lbolt and lbolt64 with hz ticks each.
1817 		 */
1818 		lbolt += hz;
1819 		lbolt64 += hz;
1820 
1821 		if (!deadman_panic_timers)
1822 			return; /* allow all timers to be manually disabled */
1823 
1824 		/*
1825 		 * If we are generating a crash dump or syncing filesystems and
1826 		 * the corresponding timer is set, decrement it and re-enter
1827 		 * the panic code to abort it and advance to the next state.
1828 		 * The panic states and triggers are explained in panic.c.
1829 		 */
1830 		if (panic_dump) {
1831 			if (dump_timeleft && (--dump_timeleft == 0)) {
1832 				panic("panic dump timeout");
1833 				/*NOTREACHED*/
1834 			}
1835 		} else if (panic_sync) {
1836 			if (sync_timeleft && (--sync_timeleft == 0)) {
1837 				panic("panic sync timeout");
1838 				/*NOTREACHED*/
1839 			}
1840 		}
1841 
1842 		return;
1843 	}
1844 
1845 	if (lbolt != CPU->cpu_deadman_lbolt) {
1846 		CPU->cpu_deadman_lbolt = lbolt;
1847 		CPU->cpu_deadman_countdown = deadman_seconds;
1848 		return;
1849 	}
1850 
1851 	if (CPU->cpu_deadman_countdown-- > 0)
1852 		return;
1853 
1854 	/*
1855 	 * Regardless of whether or not we actually bring the system down,
1856 	 * bump the deadman_panics variable.
1857 	 *
1858 	 * N.B. deadman_panics is incremented once for each CPU that
1859 	 * passes through here.  It's expected that all the CPUs will
1860 	 * detect this condition within one second of each other, so
1861 	 * when deadman_enabled is off, deadman_panics will
1862 	 * typically be a multiple of the total number of CPUs in
1863 	 * the system.
1864 	 */
1865 	atomic_add_32(&deadman_panics, 1);
1866 
1867 	if (!deadman_enabled) {
1868 		CPU->cpu_deadman_countdown = deadman_seconds;
1869 		return;
1870 	}
1871 
1872 	/*
1873 	 * If we're here, we want to bring the system down.
1874 	 */
1875 	panic("deadman: timed out after %d seconds of clock "
1876 	    "inactivity", deadman_seconds);
1877 	/*NOTREACHED*/
1878 }
1879 
1880 /*ARGSUSED*/
1881 static void
1882 deadman_online(void *arg, cpu_t *cpu, cyc_handler_t *hdlr, cyc_time_t *when)
1883 {
1884 	cpu->cpu_deadman_lbolt = 0;
1885 	cpu->cpu_deadman_countdown = deadman_seconds;
1886 
1887 	hdlr->cyh_func = (cyc_func_t)deadman;
1888 	hdlr->cyh_level = CY_HIGH_LEVEL;
1889 	hdlr->cyh_arg = NULL;
1890 
1891 	/*
1892 	 * Stagger the CPUs so that they don't all run deadman() at
1893 	 * the same time.  Simplest reason to do this is to make it
1894 	 * more likely that only one CPU will panic in case of a
1895 	 * timeout.  This is (strictly speaking) an aesthetic, not a
1896 	 * technical consideration.
1897 	 *
1898 	 * The interval must be one second in accordance with the
1899 	 * code in deadman() above to increase lbolt during panic.
1900 	 */
1901 	when->cyt_when = cpu->cpu_id * (NANOSEC / NCPU);
1902 	when->cyt_interval = NANOSEC;
1903 }
1904 
1905 
1906 void
1907 deadman_init(void)
1908 {
1909 	cyc_omni_handler_t hdlr;
1910 
1911 	if (deadman_seconds == 0)
1912 		deadman_seconds = snoop_interval / MICROSEC;
1913 
1914 	if (snooping)
1915 		deadman_enabled = 1;
1916 
1917 	hdlr.cyo_online = deadman_online;
1918 	hdlr.cyo_offline = NULL;
1919 	hdlr.cyo_arg = NULL;
1920 
1921 	mutex_enter(&cpu_lock);
1922 	deadman_cyclic = cyclic_add_omni(&hdlr);
1923 	mutex_exit(&cpu_lock);
1924 }
1925 
1926 /*
1927  * tod_fault() is for updating tod validate mechanism state:
1928  * (1) TOD_NOFAULT: for resetting the state to 'normal'.
1929  *     currently used for debugging only
1930  * (2) The following four cases detected by tod validate mechanism:
1931  *       TOD_REVERSED: current tod value is less than previous value.
1932  *       TOD_STALLED: current tod value hasn't advanced.
1933  *       TOD_JUMPED: current tod value advanced too far from previous value.
1934  *       TOD_RATECHANGED: the ratio between average tod delta and
1935  *       average tick delta has changed.
1936  */
1937 enum tod_fault_type
1938 tod_fault(enum tod_fault_type ftype, int off)
1939 {
1940 	ASSERT(MUTEX_HELD(&tod_lock));
1941 
1942 	if (tod_faulted != ftype) {
1943 		switch (ftype) {
1944 		case TOD_NOFAULT:
1945 			plat_tod_fault(TOD_NOFAULT);
1946 			cmn_err(CE_NOTE, "Restarted tracking "
1947 					"Time of Day clock.");
1948 			tod_faulted = ftype;
1949 			break;
1950 		case TOD_REVERSED:
1951 		case TOD_JUMPED:
1952 			if (tod_faulted == TOD_NOFAULT) {
1953 				plat_tod_fault(ftype);
1954 				cmn_err(CE_WARN, "Time of Day clock error: "
1955 				    "reason [%s by 0x%x]. -- "
1956 				    " Stopped tracking Time Of Day clock.",
1957 				    tod_fault_table[ftype], off);
1958 				tod_faulted = ftype;
1959 			}
1960 			break;
1961 		case TOD_STALLED:
1962 		case TOD_RATECHANGED:
1963 			if (tod_faulted == TOD_NOFAULT) {
1964 				plat_tod_fault(ftype);
1965 				cmn_err(CE_WARN, "Time of Day clock error: "
1966 				    "reason [%s]. -- "
1967 				    " Stopped tracking Time Of Day clock.",
1968 				    tod_fault_table[ftype]);
1969 				tod_faulted = ftype;
1970 			}
1971 			break;
1972 		default:
1973 			break;
1974 		}
1975 	}
1976 	return (tod_faulted);
1977 }
1978 
1979 void
1980 tod_fault_reset()
1981 {
1982 	tod_fault_reset_flag = 1;
1983 }
1984 
1985 
1986 /*
1987  * tod_validate() is used for checking values returned by tod_get().
1988  * Four error cases can be detected by this routine:
1989  *   TOD_REVERSED: current tod value is less than previous.
1990  *   TOD_STALLED: current tod value hasn't advanced.
1991  *   TOD_JUMPED: current tod value advanced too far from previous value.
1992  *   TOD_RATECHANGED: the ratio between average tod delta and
1993  *   average tick delta has changed.
1994  */
1995 time_t
1996 tod_validate(time_t tod)
1997 {
1998 	time_t diff_tod;
1999 	hrtime_t diff_tick;
2000 
2001 	long dtick;
2002 	int dtick_delta;
2003 
2004 	int off = 0;
2005 	enum tod_fault_type tod_bad = TOD_NOFAULT;
2006 
2007 	static int firsttime = 1;
2008 
2009 	static time_t prev_tod = 0;
2010 	static hrtime_t prev_tick = 0;
2011 	static long dtick_avg = TOD_REF_FREQ;
2012 
2013 	hrtime_t tick = gethrtime();
2014 
2015 	ASSERT(MUTEX_HELD(&tod_lock));
2016 
2017 	/*
2018 	 * tod_validate_enable is patchable via /etc/system.
2019 	 * If TOD is already faulted, or if TOD validation is deferred,
2020 	 * there is nothing to do.
2021 	 */
2022 	if ((tod_validate_enable == 0) || (tod_faulted != TOD_NOFAULT) ||
2023 	    tod_validate_deferred) {
2024 		return (tod);
2025 	}
2026 
2027 	/*
2028 	 * Update prev_tod and prev_tick values for first run
2029 	 */
2030 	if (firsttime) {
2031 		firsttime = 0;
2032 		prev_tod = tod;
2033 		prev_tick = tick;
2034 		return (tod);
2035 	}
2036 
2037 	/*
2038 	 * For either of these conditions, we need to reset ourself
2039 	 * and start validation from zero since each condition
2040 	 * indicates that the TOD will be updated with new value
2041 	 * Also, note that tod_needsync will be reset in clock()
2042 	 */
2043 	if (tod_needsync || tod_fault_reset_flag) {
2044 		firsttime = 1;
2045 		prev_tod = 0;
2046 		prev_tick = 0;
2047 		dtick_avg = TOD_REF_FREQ;
2048 
2049 		if (tod_fault_reset_flag)
2050 			tod_fault_reset_flag = 0;
2051 
2052 		return (tod);
2053 	}
2054 
2055 	/* test hook */
2056 	switch (tod_unit_test) {
2057 	case 1: /* for testing jumping tod */
2058 		tod += tod_test_injector;
2059 		tod_unit_test = 0;
2060 		break;
2061 	case 2:	/* for testing stuck tod bit */
2062 		tod |= 1 << tod_test_injector;
2063 		tod_unit_test = 0;
2064 		break;
2065 	case 3:	/* for testing stalled tod */
2066 		tod = prev_tod;
2067 		tod_unit_test = 0;
2068 		break;
2069 	case 4:	/* reset tod fault status */
2070 		(void) tod_fault(TOD_NOFAULT, 0);
2071 		tod_unit_test = 0;
2072 		break;
2073 	default:
2074 		break;
2075 	}
2076 
2077 	diff_tod = tod - prev_tod;
2078 	diff_tick = tick - prev_tick;
2079 
2080 	ASSERT(diff_tick >= 0);
2081 
2082 	if (diff_tod < 0) {
2083 		/* ERROR - tod reversed */
2084 		tod_bad = TOD_REVERSED;
2085 		off = (int)(prev_tod - tod);
2086 	} else if (diff_tod == 0) {
2087 		/* tod did not advance */
2088 		if (diff_tick > TOD_STALL_THRESHOLD) {
2089 			/* ERROR - tod stalled */
2090 			tod_bad = TOD_STALLED;
2091 		} else {
2092 			/*
2093 			 * Make sure we don't update prev_tick
2094 			 * so that diff_tick is calculated since
2095 			 * the first diff_tod == 0
2096 			 */
2097 			return (tod);
2098 		}
2099 	} else {
2100 		/* calculate dtick */
2101 		dtick = diff_tick / diff_tod;
2102 
2103 		/* update dtick averages */
2104 		dtick_avg += ((dtick - dtick_avg) / TOD_FILTER_N);
2105 
2106 		/*
2107 		 * Calculate dtick_delta as
2108 		 * variation from reference freq in quartiles
2109 		 */
2110 		dtick_delta = (dtick_avg - TOD_REF_FREQ) /
2111 			(TOD_REF_FREQ >> 2);
2112 
2113 		/*
2114 		 * Even with a perfectly functioning TOD device,
2115 		 * when the number of elapsed seconds is low the
2116 		 * algorithm can calculate a rate that is beyond
2117 		 * tolerance, causing an error.  The algorithm is
2118 		 * inaccurate when elapsed time is low (less than
2119 		 * 5 seconds).
2120 		 */
2121 		if (diff_tod > 4) {
2122 			if (dtick < TOD_JUMP_THRESHOLD) {
2123 				/* ERROR - tod jumped */
2124 				tod_bad = TOD_JUMPED;
2125 				off = (int)diff_tod;
2126 			} else if (dtick_delta) {
2127 				/* ERROR - change in clock rate */
2128 				tod_bad = TOD_RATECHANGED;
2129 			}
2130 		}
2131 	}
2132 
2133 	if (tod_bad != TOD_NOFAULT) {
2134 		(void) tod_fault(tod_bad, off);
2135 
2136 		/*
2137 		 * Disable dosynctodr since we are going to fault
2138 		 * the TOD chip anyway here
2139 		 */
2140 		dosynctodr = 0;
2141 
2142 		/*
2143 		 * Set tod to the correct value from hrestime
2144 		 */
2145 		tod = hrestime.tv_sec;
2146 	}
2147 
2148 	prev_tod = tod;
2149 	prev_tick = tick;
2150 	return (tod);
2151 }
2152 
2153 static void
2154 calcloadavg(int nrun, uint64_t *hp_ave)
2155 {
2156 	static int64_t f[3] = { 135, 27, 9 };
2157 	uint_t i;
2158 	int64_t q, r;
2159 
2160 	/*
2161 	 * Compute load average over the last 1, 5, and 15 minutes
2162 	 * (60, 300, and 900 seconds).  The constants in f[3] are for
2163 	 * exponential decay:
2164 	 * (1 - exp(-1/60)) << 13 = 135,
2165 	 * (1 - exp(-1/300)) << 13 = 27,
2166 	 * (1 - exp(-1/900)) << 13 = 9.
2167 	 */
2168 
2169 	/*
2170 	 * a little hoop-jumping to avoid integer overflow
2171 	 */
2172 	for (i = 0; i < 3; i++) {
2173 		q = (hp_ave[i]  >> 16) << 7;
2174 		r = (hp_ave[i]  & 0xffff) << 7;
2175 		hp_ave[i] += ((nrun - q) * f[i] - ((r * f[i]) >> 16)) >> 4;
2176 	}
2177 }
2178