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