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