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