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