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