xref: /illumos-gate/usr/src/uts/common/os/clock.c (revision 5ee6ac27d4fd4c9412183aa8cc1143f36ae04a8c)
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  * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
26  */
27 
28 #include <sys/param.h>
29 #include <sys/t_lock.h>
30 #include <sys/types.h>
31 #include <sys/tuneable.h>
32 #include <sys/sysmacros.h>
33 #include <sys/systm.h>
34 #include <sys/cpuvar.h>
35 #include <sys/lgrp.h>
36 #include <sys/user.h>
37 #include <sys/proc.h>
38 #include <sys/callo.h>
39 #include <sys/kmem.h>
40 #include <sys/var.h>
41 #include <sys/cmn_err.h>
42 #include <sys/swap.h>
43 #include <sys/vmsystm.h>
44 #include <sys/class.h>
45 #include <sys/time.h>
46 #include <sys/debug.h>
47 #include <sys/vtrace.h>
48 #include <sys/spl.h>
49 #include <sys/atomic.h>
50 #include <sys/dumphdr.h>
51 #include <sys/archsystm.h>
52 #include <sys/fs/swapnode.h>
53 #include <sys/panic.h>
54 #include <sys/disp.h>
55 #include <sys/msacct.h>
56 #include <sys/mem_cage.h>
57 
58 #include <vm/page.h>
59 #include <vm/anon.h>
60 #include <vm/rm.h>
61 #include <sys/cyclic.h>
62 #include <sys/cpupart.h>
63 #include <sys/rctl.h>
64 #include <sys/task.h>
65 #include <sys/sdt.h>
66 #include <sys/ddi_timer.h>
67 #include <sys/random.h>
68 #include <sys/modctl.h>
69 
70 /*
71  * for NTP support
72  */
73 #include <sys/timex.h>
74 #include <sys/inttypes.h>
75 
76 #include <sys/sunddi.h>
77 #include <sys/clock_impl.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 kcondvar_t lbolt_cv;
243 
244 /*
245  * Hybrid lbolt implementation:
246  *
247  * The service historically provided by the lbolt and lbolt64 variables has
248  * been replaced by the ddi_get_lbolt() and ddi_get_lbolt64() routines, and the
249  * original symbols removed from the system. The once clock driven variables are
250  * now implemented in an event driven fashion, backed by gethrtime() coarsed to
251  * the appropriate clock resolution. The default event driven implementation is
252  * complemented by a cyclic driven one, active only during periods of intense
253  * activity around the DDI lbolt routines, when a lbolt specific cyclic is
254  * reprogramed to fire at a clock tick interval to serve consumers of lbolt who
255  * rely on the original low cost of consulting a memory position.
256  *
257  * The implementation uses the number of calls to these routines and the
258  * frequency of these to determine when to transition from event to cyclic
259  * driven and vice-versa. These values are kept on a per CPU basis for
260  * scalability reasons and to prevent CPUs from constantly invalidating a single
261  * cache line when modifying a global variable. The transition from event to
262  * cyclic mode happens once the thresholds are crossed, and activity on any CPU
263  * can cause such transition.
264  *
265  * The lbolt_hybrid function pointer is called by ddi_get_lbolt() and
266  * ddi_get_lbolt64(), and will point to lbolt_event_driven() or
267  * lbolt_cyclic_driven() according to the current mode. When the thresholds
268  * are exceeded, lbolt_event_driven() will reprogram the lbolt cyclic to
269  * fire at a nsec_per_tick interval and increment an internal variable at
270  * each firing. lbolt_hybrid will then point to lbolt_cyclic_driven(), which
271  * will simply return the value of such variable. lbolt_cyclic() will attempt
272  * to shut itself off at each threshold interval (sampling period for calls
273  * to the DDI lbolt routines), and return to the event driven mode, but will
274  * be prevented from doing so if lbolt_cyclic_driven() is being heavily used.
275  *
276  * lbolt_bootstrap is used during boot to serve lbolt consumers who don't wait
277  * for the cyclic subsystem to be intialized.
278  *
279  */
280 int64_t lbolt_bootstrap(void);
281 int64_t lbolt_event_driven(void);
282 int64_t lbolt_cyclic_driven(void);
283 int64_t (*lbolt_hybrid)(void) = lbolt_bootstrap;
284 uint_t lbolt_ev_to_cyclic(caddr_t, caddr_t);
285 
286 /*
287  * lbolt's cyclic, installed by clock_init().
288  */
289 static void lbolt_cyclic(void);
290 
291 /*
292  * Tunable to keep lbolt in cyclic driven mode. This will prevent the system
293  * from switching back to event driven, once it reaches cyclic mode.
294  */
295 static boolean_t lbolt_cyc_only = B_FALSE;
296 
297 /*
298  * Cache aligned, per CPU structure with lbolt usage statistics.
299  */
300 static lbolt_cpu_t *lb_cpu;
301 
302 /*
303  * Single, cache aligned, structure with all the information required by
304  * the lbolt implementation.
305  */
306 lbolt_info_t *lb_info;
307 
308 
309 int one_sec = 1; /* turned on once every second */
310 static int fsflushcnt;	/* counter for t_fsflushr */
311 int	dosynctodr = 1;	/* patchable; enable/disable sync to TOD chip */
312 int	tod_needsync = 0;	/* need to sync tod chip with software time */
313 static int tod_broken = 0;	/* clock chip doesn't work */
314 time_t	boot_time = 0;		/* Boot time in seconds since 1970 */
315 cyclic_id_t clock_cyclic;	/* clock()'s cyclic_id */
316 cyclic_id_t deadman_cyclic;	/* deadman()'s cyclic_id */
317 cyclic_id_t ddi_timer_cyclic;	/* cyclic_timer()'s cyclic_id */
318 
319 extern void	clock_tick_schedule(int);
320 
321 static int lgrp_ticks;		/* counter to schedule lgrp load calcs */
322 
323 /*
324  * for tod fault detection
325  */
326 #define	TOD_REF_FREQ		((longlong_t)(NANOSEC))
327 #define	TOD_STALL_THRESHOLD	(TOD_REF_FREQ * 3 / 2)
328 #define	TOD_JUMP_THRESHOLD	(TOD_REF_FREQ / 2)
329 #define	TOD_FILTER_N		4
330 #define	TOD_FILTER_SETTLE	(4 * TOD_FILTER_N)
331 static int tod_faulted = TOD_NOFAULT;
332 
333 static int tod_status_flag = 0;		/* used by tod_validate() */
334 
335 static hrtime_t prev_set_tick = 0;	/* gethrtime() prior to tod_set() */
336 static time_t prev_set_tod = 0;		/* tv_sec value passed to tod_set() */
337 
338 /* patchable via /etc/system */
339 int tod_validate_enable = 1;
340 
341 /* Diagnose/Limit messages about delay(9F) called from interrupt context */
342 int			delay_from_interrupt_diagnose = 0;
343 volatile uint32_t	delay_from_interrupt_msg = 20;
344 
345 /*
346  * On non-SPARC systems, TOD validation must be deferred until gethrtime
347  * returns non-zero values (after mach_clkinit's execution).
348  * On SPARC systems, it must be deferred until after hrtime_base
349  * and hres_last_tick are set (in the first invocation of hres_tick).
350  * Since in both cases the prerequisites occur before the invocation of
351  * tod_get() in clock(), the deferment is lifted there.
352  */
353 static boolean_t tod_validate_deferred = B_TRUE;
354 
355 /*
356  * tod_fault_table[] must be aligned with
357  * enum tod_fault_type in systm.h
358  */
359 static char *tod_fault_table[] = {
360 	"Reversed",			/* TOD_REVERSED */
361 	"Stalled",			/* TOD_STALLED */
362 	"Jumped",			/* TOD_JUMPED */
363 	"Changed in Clock Rate",	/* TOD_RATECHANGED */
364 	"Is Read-Only"			/* TOD_RDONLY */
365 	/*
366 	 * no strings needed for TOD_NOFAULT
367 	 */
368 };
369 
370 /*
371  * test hook for tod broken detection in tod_validate
372  */
373 int tod_unit_test = 0;
374 time_t tod_test_injector;
375 
376 #define	CLOCK_ADJ_HIST_SIZE	4
377 
378 static int	adj_hist_entry;
379 
380 int64_t clock_adj_hist[CLOCK_ADJ_HIST_SIZE];
381 
382 static void calcloadavg(int, uint64_t *);
383 static int genloadavg(struct loadavg_s *);
384 static void loadavg_update();
385 
386 void (*cmm_clock_callout)() = NULL;
387 void (*cpucaps_clock_callout)() = NULL;
388 
389 extern clock_t clock_tick_proc_max;
390 
391 static int64_t deadman_counter = 0;
392 
393 static void
394 clock(void)
395 {
396 	kthread_t	*t;
397 	uint_t	nrunnable;
398 	uint_t	w_io;
399 	cpu_t	*cp;
400 	cpupart_t *cpupart;
401 	extern	void	set_freemem();
402 	void	(*funcp)();
403 	int32_t ltemp;
404 	int64_t lltemp;
405 	int s;
406 	int do_lgrp_load;
407 	int i;
408 	clock_t now = LBOLT_NO_ACCOUNT;	/* current tick */
409 
410 	if (panicstr)
411 		return;
412 
413 	/*
414 	 * Make sure that 'freemem' do not drift too far from the truth
415 	 */
416 	set_freemem();
417 
418 
419 	/*
420 	 * Before the section which is repeated is executed, we do
421 	 * the time delta processing which occurs every clock tick
422 	 *
423 	 * There is additional processing which happens every time
424 	 * the nanosecond counter rolls over which is described
425 	 * below - see the section which begins with : if (one_sec)
426 	 *
427 	 * This section marks the beginning of the precision-kernel
428 	 * code fragment.
429 	 *
430 	 * First, compute the phase adjustment. If the low-order bits
431 	 * (time_phase) of the update overflow, bump the higher order
432 	 * bits (time_update).
433 	 */
434 	time_phase += time_adj;
435 	if (time_phase <= -FINEUSEC) {
436 		ltemp = -time_phase / SCALE_PHASE;
437 		time_phase += ltemp * SCALE_PHASE;
438 		s = hr_clock_lock();
439 		timedelta -= ltemp * (NANOSEC/MICROSEC);
440 		hr_clock_unlock(s);
441 	} else if (time_phase >= FINEUSEC) {
442 		ltemp = time_phase / SCALE_PHASE;
443 		time_phase -= ltemp * SCALE_PHASE;
444 		s = hr_clock_lock();
445 		timedelta += ltemp * (NANOSEC/MICROSEC);
446 		hr_clock_unlock(s);
447 	}
448 
449 	/*
450 	 * End of precision-kernel code fragment which is processed
451 	 * every timer interrupt.
452 	 *
453 	 * Continue with the interrupt processing as scheduled.
454 	 */
455 	/*
456 	 * Count the number of runnable threads and the number waiting
457 	 * for some form of I/O to complete -- gets added to
458 	 * sysinfo.waiting.  To know the state of the system, must add
459 	 * wait counts from all CPUs.  Also add up the per-partition
460 	 * statistics.
461 	 */
462 	w_io = 0;
463 	nrunnable = 0;
464 
465 	/*
466 	 * keep track of when to update lgrp/part loads
467 	 */
468 
469 	do_lgrp_load = 0;
470 	if (lgrp_ticks++ >= hz / 10) {
471 		lgrp_ticks = 0;
472 		do_lgrp_load = 1;
473 	}
474 
475 	if (one_sec) {
476 		loadavg_update();
477 		deadman_counter++;
478 	}
479 
480 	/*
481 	 * First count the threads waiting on kpreempt queues in each
482 	 * CPU partition.
483 	 */
484 
485 	cpupart = cp_list_head;
486 	do {
487 		uint_t cpupart_nrunnable = cpupart->cp_kp_queue.disp_nrunnable;
488 
489 		cpupart->cp_updates++;
490 		nrunnable += cpupart_nrunnable;
491 		cpupart->cp_nrunnable_cum += cpupart_nrunnable;
492 		if (one_sec) {
493 			cpupart->cp_nrunning = 0;
494 			cpupart->cp_nrunnable = cpupart_nrunnable;
495 		}
496 	} while ((cpupart = cpupart->cp_next) != cp_list_head);
497 
498 
499 	/* Now count the per-CPU statistics. */
500 	cp = cpu_list;
501 	do {
502 		uint_t cpu_nrunnable = cp->cpu_disp->disp_nrunnable;
503 
504 		nrunnable += cpu_nrunnable;
505 		cpupart = cp->cpu_part;
506 		cpupart->cp_nrunnable_cum += cpu_nrunnable;
507 		if (one_sec) {
508 			cpupart->cp_nrunnable += cpu_nrunnable;
509 			/*
510 			 * Update user, system, and idle cpu times.
511 			 */
512 			cpupart->cp_nrunning++;
513 			/*
514 			 * w_io is used to update sysinfo.waiting during
515 			 * one_second processing below.  Only gather w_io
516 			 * information when we walk the list of cpus if we're
517 			 * going to perform one_second processing.
518 			 */
519 			w_io += CPU_STATS(cp, sys.iowait);
520 		}
521 
522 		if (one_sec && (cp->cpu_flags & CPU_EXISTS)) {
523 			int i, load, change;
524 			hrtime_t intracct, intrused;
525 			const hrtime_t maxnsec = 1000000000;
526 			const int precision = 100;
527 
528 			/*
529 			 * Estimate interrupt load on this cpu each second.
530 			 * Computes cpu_intrload as %utilization (0-99).
531 			 */
532 
533 			/* add up interrupt time from all micro states */
534 			for (intracct = 0, i = 0; i < NCMSTATES; i++)
535 				intracct += cp->cpu_intracct[i];
536 			scalehrtime(&intracct);
537 
538 			/* compute nsec used in the past second */
539 			intrused = intracct - cp->cpu_intrlast;
540 			cp->cpu_intrlast = intracct;
541 
542 			/* limit the value for safety (and the first pass) */
543 			if (intrused >= maxnsec)
544 				intrused = maxnsec - 1;
545 
546 			/* calculate %time in interrupt */
547 			load = (precision * intrused) / maxnsec;
548 			ASSERT(load >= 0 && load < precision);
549 			change = cp->cpu_intrload - load;
550 
551 			/* jump to new max, or decay the old max */
552 			if (change < 0)
553 				cp->cpu_intrload = load;
554 			else if (change > 0)
555 				cp->cpu_intrload -= (change + 3) / 4;
556 
557 			DTRACE_PROBE3(cpu_intrload,
558 			    cpu_t *, cp,
559 			    hrtime_t, intracct,
560 			    hrtime_t, intrused);
561 		}
562 
563 		if (do_lgrp_load &&
564 		    (cp->cpu_flags & CPU_EXISTS)) {
565 			/*
566 			 * When updating the lgroup's load average,
567 			 * account for the thread running on the CPU.
568 			 * If the CPU is the current one, then we need
569 			 * to account for the underlying thread which
570 			 * got the clock interrupt not the thread that is
571 			 * handling the interrupt and caculating the load
572 			 * average
573 			 */
574 			t = cp->cpu_thread;
575 			if (CPU == cp)
576 				t = t->t_intr;
577 
578 			/*
579 			 * Account for the load average for this thread if
580 			 * it isn't the idle thread or it is on the interrupt
581 			 * stack and not the current CPU handling the clock
582 			 * interrupt
583 			 */
584 			if ((t && t != cp->cpu_idle_thread) || (CPU != cp &&
585 			    CPU_ON_INTR(cp))) {
586 				if (t->t_lpl == cp->cpu_lpl) {
587 					/* local thread */
588 					cpu_nrunnable++;
589 				} else {
590 					/*
591 					 * This is a remote thread, charge it
592 					 * against its home lgroup.  Note that
593 					 * we notice that a thread is remote
594 					 * only if it's currently executing.
595 					 * This is a reasonable approximation,
596 					 * since queued remote threads are rare.
597 					 * Note also that if we didn't charge
598 					 * it to its home lgroup, remote
599 					 * execution would often make a system
600 					 * appear balanced even though it was
601 					 * not, and thread placement/migration
602 					 * would often not be done correctly.
603 					 */
604 					lgrp_loadavg(t->t_lpl,
605 					    LGRP_LOADAVG_IN_THREAD_MAX, 0);
606 				}
607 			}
608 			lgrp_loadavg(cp->cpu_lpl,
609 			    cpu_nrunnable * LGRP_LOADAVG_IN_THREAD_MAX, 1);
610 		}
611 	} while ((cp = cp->cpu_next) != cpu_list);
612 
613 	clock_tick_schedule(one_sec);
614 
615 	/*
616 	 * Check for a callout that needs be called from the clock
617 	 * thread to support the membership protocol in a clustered
618 	 * system.  Copy the function pointer so that we can reset
619 	 * this to NULL if needed.
620 	 */
621 	if ((funcp = cmm_clock_callout) != NULL)
622 		(*funcp)();
623 
624 	if ((funcp = cpucaps_clock_callout) != NULL)
625 		(*funcp)();
626 
627 	/*
628 	 * Wakeup the cageout thread waiters once per second.
629 	 */
630 	if (one_sec)
631 		kcage_tick();
632 
633 	if (one_sec) {
634 
635 		int drift, absdrift;
636 		timestruc_t tod;
637 		int s;
638 
639 		/*
640 		 * Beginning of precision-kernel code fragment executed
641 		 * every second.
642 		 *
643 		 * On rollover of the second the phase adjustment to be
644 		 * used for the next second is calculated.  Also, the
645 		 * maximum error is increased by the tolerance.  If the
646 		 * PPS frequency discipline code is present, the phase is
647 		 * increased to compensate for the CPU clock oscillator
648 		 * frequency error.
649 		 *
650 		 * On a 32-bit machine and given parameters in the timex.h
651 		 * header file, the maximum phase adjustment is +-512 ms
652 		 * and maximum frequency offset is (a tad less than)
653 		 * +-512 ppm. On a 64-bit machine, you shouldn't need to ask.
654 		 */
655 		time_maxerror += time_tolerance / SCALE_USEC;
656 
657 		/*
658 		 * Leap second processing. If in leap-insert state at
659 		 * the end of the day, the system clock is set back one
660 		 * second; if in leap-delete state, the system clock is
661 		 * set ahead one second. The microtime() routine or
662 		 * external clock driver will insure that reported time
663 		 * is always monotonic. The ugly divides should be
664 		 * replaced.
665 		 */
666 		switch (time_state) {
667 
668 		case TIME_OK:
669 			if (time_status & STA_INS)
670 				time_state = TIME_INS;
671 			else if (time_status & STA_DEL)
672 				time_state = TIME_DEL;
673 			break;
674 
675 		case TIME_INS:
676 			if (hrestime.tv_sec % 86400 == 0) {
677 				s = hr_clock_lock();
678 				hrestime.tv_sec--;
679 				hr_clock_unlock(s);
680 				time_state = TIME_OOP;
681 			}
682 			break;
683 
684 		case TIME_DEL:
685 			if ((hrestime.tv_sec + 1) % 86400 == 0) {
686 				s = hr_clock_lock();
687 				hrestime.tv_sec++;
688 				hr_clock_unlock(s);
689 				time_state = TIME_WAIT;
690 			}
691 			break;
692 
693 		case TIME_OOP:
694 			time_state = TIME_WAIT;
695 			break;
696 
697 		case TIME_WAIT:
698 			if (!(time_status & (STA_INS | STA_DEL)))
699 				time_state = TIME_OK;
700 		default:
701 			break;
702 		}
703 
704 		/*
705 		 * Compute the phase adjustment for the next second. In
706 		 * PLL mode, the offset is reduced by a fixed factor
707 		 * times the time constant. In FLL mode the offset is
708 		 * used directly. In either mode, the maximum phase
709 		 * adjustment for each second is clamped so as to spread
710 		 * the adjustment over not more than the number of
711 		 * seconds between updates.
712 		 */
713 		if (time_offset == 0)
714 			time_adj = 0;
715 		else if (time_offset < 0) {
716 			lltemp = -time_offset;
717 			if (!(time_status & STA_FLL)) {
718 				if ((1 << time_constant) >= SCALE_KG)
719 					lltemp *= (1 << time_constant) /
720 					    SCALE_KG;
721 				else
722 					lltemp = (lltemp / SCALE_KG) >>
723 					    time_constant;
724 			}
725 			if (lltemp > (MAXPHASE / MINSEC) * SCALE_UPDATE)
726 				lltemp = (MAXPHASE / MINSEC) * SCALE_UPDATE;
727 			time_offset += lltemp;
728 			time_adj = -(lltemp * SCALE_PHASE) / hz / SCALE_UPDATE;
729 		} else {
730 			lltemp = time_offset;
731 			if (!(time_status & STA_FLL)) {
732 				if ((1 << time_constant) >= SCALE_KG)
733 					lltemp *= (1 << time_constant) /
734 					    SCALE_KG;
735 				else
736 					lltemp = (lltemp / SCALE_KG) >>
737 					    time_constant;
738 			}
739 			if (lltemp > (MAXPHASE / MINSEC) * SCALE_UPDATE)
740 				lltemp = (MAXPHASE / MINSEC) * SCALE_UPDATE;
741 			time_offset -= lltemp;
742 			time_adj = (lltemp * SCALE_PHASE) / hz / SCALE_UPDATE;
743 		}
744 
745 		/*
746 		 * Compute the frequency estimate and additional phase
747 		 * adjustment due to frequency error for the next
748 		 * second. When the PPS signal is engaged, gnaw on the
749 		 * watchdog counter and update the frequency computed by
750 		 * the pll and the PPS signal.
751 		 */
752 		pps_valid++;
753 		if (pps_valid == PPS_VALID) {
754 			pps_jitter = MAXTIME;
755 			pps_stabil = MAXFREQ;
756 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
757 			    STA_PPSWANDER | STA_PPSERROR);
758 		}
759 		lltemp = time_freq + pps_freq;
760 
761 		if (lltemp)
762 			time_adj += (lltemp * SCALE_PHASE) / (SCALE_USEC * hz);
763 
764 		/*
765 		 * End of precision kernel-code fragment
766 		 *
767 		 * The section below should be modified if we are planning
768 		 * to use NTP for synchronization.
769 		 *
770 		 * Note: the clock synchronization code now assumes
771 		 * the following:
772 		 *   - if dosynctodr is 1, then compute the drift between
773 		 *	the tod chip and software time and adjust one or
774 		 *	the other depending on the circumstances
775 		 *
776 		 *   - if dosynctodr is 0, then the tod chip is independent
777 		 *	of the software clock and should not be adjusted,
778 		 *	but allowed to free run.  this allows NTP to sync.
779 		 *	hrestime without any interference from the tod chip.
780 		 */
781 
782 		tod_validate_deferred = B_FALSE;
783 		mutex_enter(&tod_lock);
784 		tod = tod_get();
785 		drift = tod.tv_sec - hrestime.tv_sec;
786 		absdrift = (drift >= 0) ? drift : -drift;
787 		if (tod_needsync || absdrift > 1) {
788 			int s;
789 			if (absdrift > 2) {
790 				if (!tod_broken && tod_faulted == TOD_NOFAULT) {
791 					s = hr_clock_lock();
792 					hrestime = tod;
793 					membar_enter();	/* hrestime visible */
794 					timedelta = 0;
795 					timechanged++;
796 					tod_needsync = 0;
797 					hr_clock_unlock(s);
798 					callout_hrestime();
799 
800 				}
801 			} else {
802 				if (tod_needsync || !dosynctodr) {
803 					gethrestime(&tod);
804 					tod_set(tod);
805 					s = hr_clock_lock();
806 					if (timedelta == 0)
807 						tod_needsync = 0;
808 					hr_clock_unlock(s);
809 				} else {
810 					/*
811 					 * If the drift is 2 seconds on the
812 					 * money, then the TOD is adjusting
813 					 * the clock;  record that.
814 					 */
815 					clock_adj_hist[adj_hist_entry++ %
816 					    CLOCK_ADJ_HIST_SIZE] = now;
817 					s = hr_clock_lock();
818 					timedelta = (int64_t)drift*NANOSEC;
819 					hr_clock_unlock(s);
820 				}
821 			}
822 		}
823 		one_sec = 0;
824 		time = gethrestime_sec();  /* for crusty old kmem readers */
825 		mutex_exit(&tod_lock);
826 
827 		/*
828 		 * Some drivers still depend on this... XXX
829 		 */
830 		cv_broadcast(&lbolt_cv);
831 
832 		vminfo.freemem += freemem;
833 		{
834 			pgcnt_t maxswap, resv, free;
835 			pgcnt_t avail =
836 			    MAX((spgcnt_t)(availrmem - swapfs_minfree), 0);
837 
838 			maxswap = k_anoninfo.ani_mem_resv +
839 			    k_anoninfo.ani_max +avail;
840 			/* Update ani_free */
841 			set_anoninfo();
842 			free = k_anoninfo.ani_free + avail;
843 			resv = k_anoninfo.ani_phys_resv +
844 			    k_anoninfo.ani_mem_resv;
845 
846 			vminfo.swap_resv += resv;
847 			/* number of reserved and allocated pages */
848 #ifdef	DEBUG
849 			if (maxswap < free)
850 				cmn_err(CE_WARN, "clock: maxswap < free");
851 			if (maxswap < resv)
852 				cmn_err(CE_WARN, "clock: maxswap < resv");
853 #endif
854 			vminfo.swap_alloc += maxswap - free;
855 			vminfo.swap_avail += maxswap - resv;
856 			vminfo.swap_free += free;
857 		}
858 		vminfo.updates++;
859 		if (nrunnable) {
860 			sysinfo.runque += nrunnable;
861 			sysinfo.runocc++;
862 		}
863 		if (nswapped) {
864 			sysinfo.swpque += nswapped;
865 			sysinfo.swpocc++;
866 		}
867 		sysinfo.waiting += w_io;
868 		sysinfo.updates++;
869 
870 		/*
871 		 * Wake up fsflush to write out DELWRI
872 		 * buffers, dirty pages and other cached
873 		 * administrative data, e.g. inodes.
874 		 */
875 		if (--fsflushcnt <= 0) {
876 			fsflushcnt = tune.t_fsflushr;
877 			cv_signal(&fsflush_cv);
878 		}
879 
880 		vmmeter();
881 		calcloadavg(genloadavg(&loadavg), hp_avenrun);
882 		for (i = 0; i < 3; i++)
883 			/*
884 			 * At the moment avenrun[] can only hold 31
885 			 * bits of load average as it is a signed
886 			 * int in the API. We need to ensure that
887 			 * hp_avenrun[i] >> (16 - FSHIFT) will not be
888 			 * too large. If it is, we put the largest value
889 			 * that we can use into avenrun[i]. This is
890 			 * kludgey, but about all we can do until we
891 			 * avenrun[] is declared as an array of uint64[]
892 			 */
893 			if (hp_avenrun[i] < ((uint64_t)1<<(31+16-FSHIFT)))
894 				avenrun[i] = (int32_t)(hp_avenrun[i] >>
895 				    (16 - FSHIFT));
896 			else
897 				avenrun[i] = 0x7fffffff;
898 
899 		cpupart = cp_list_head;
900 		do {
901 			calcloadavg(genloadavg(&cpupart->cp_loadavg),
902 			    cpupart->cp_hp_avenrun);
903 		} while ((cpupart = cpupart->cp_next) != cp_list_head);
904 
905 		/*
906 		 * Wake up the swapper thread if necessary.
907 		 */
908 		if (runin ||
909 		    (runout && (avefree < desfree || wake_sched_sec))) {
910 			t = &t0;
911 			thread_lock(t);
912 			if (t->t_state == TS_STOPPED) {
913 				runin = runout = 0;
914 				wake_sched_sec = 0;
915 				t->t_whystop = 0;
916 				t->t_whatstop = 0;
917 				t->t_schedflag &= ~TS_ALLSTART;
918 				THREAD_TRANSITION(t);
919 				setfrontdq(t);
920 			}
921 			thread_unlock(t);
922 		}
923 	}
924 
925 	/*
926 	 * Wake up the swapper if any high priority swapped-out threads
927 	 * became runable during the last tick.
928 	 */
929 	if (wake_sched) {
930 		t = &t0;
931 		thread_lock(t);
932 		if (t->t_state == TS_STOPPED) {
933 			runin = runout = 0;
934 			wake_sched = 0;
935 			t->t_whystop = 0;
936 			t->t_whatstop = 0;
937 			t->t_schedflag &= ~TS_ALLSTART;
938 			THREAD_TRANSITION(t);
939 			setfrontdq(t);
940 		}
941 		thread_unlock(t);
942 	}
943 }
944 
945 void
946 clock_init(void)
947 {
948 	cyc_handler_t clk_hdlr, timer_hdlr, lbolt_hdlr;
949 	cyc_time_t clk_when, lbolt_when;
950 	int i, sz;
951 	intptr_t buf;
952 
953 	/*
954 	 * Setup handler and timer for the clock cyclic.
955 	 */
956 	clk_hdlr.cyh_func = (cyc_func_t)clock;
957 	clk_hdlr.cyh_level = CY_LOCK_LEVEL;
958 	clk_hdlr.cyh_arg = NULL;
959 
960 	clk_when.cyt_when = 0;
961 	clk_when.cyt_interval = nsec_per_tick;
962 
963 	/*
964 	 * cyclic_timer is dedicated to the ddi interface, which
965 	 * uses the same clock resolution as the system one.
966 	 */
967 	timer_hdlr.cyh_func = (cyc_func_t)cyclic_timer;
968 	timer_hdlr.cyh_level = CY_LOCK_LEVEL;
969 	timer_hdlr.cyh_arg = NULL;
970 
971 	/*
972 	 * The lbolt cyclic will be reprogramed to fire at a nsec_per_tick
973 	 * interval to satisfy performance needs of the DDI lbolt consumers.
974 	 * It is off by default.
975 	 */
976 	lbolt_hdlr.cyh_func = (cyc_func_t)lbolt_cyclic;
977 	lbolt_hdlr.cyh_level = CY_LOCK_LEVEL;
978 	lbolt_hdlr.cyh_arg = NULL;
979 
980 	lbolt_when.cyt_interval = nsec_per_tick;
981 
982 	/*
983 	 * Allocate cache line aligned space for the per CPU lbolt data and
984 	 * lbolt info structures, and initialize them with their default
985 	 * values. Note that these structures are also cache line sized.
986 	 */
987 	sz = sizeof (lbolt_info_t) + CPU_CACHE_COHERENCE_SIZE;
988 	buf = (intptr_t)kmem_zalloc(sz, KM_SLEEP);
989 	lb_info = (lbolt_info_t *)P2ROUNDUP(buf, CPU_CACHE_COHERENCE_SIZE);
990 
991 	if (hz != HZ_DEFAULT)
992 		lb_info->lbi_thresh_interval = LBOLT_THRESH_INTERVAL *
993 		    hz/HZ_DEFAULT;
994 	else
995 		lb_info->lbi_thresh_interval = LBOLT_THRESH_INTERVAL;
996 
997 	lb_info->lbi_thresh_calls = LBOLT_THRESH_CALLS;
998 
999 	sz = (sizeof (lbolt_cpu_t) * max_ncpus) + CPU_CACHE_COHERENCE_SIZE;
1000 	buf = (intptr_t)kmem_zalloc(sz, KM_SLEEP);
1001 	lb_cpu = (lbolt_cpu_t *)P2ROUNDUP(buf, CPU_CACHE_COHERENCE_SIZE);
1002 
1003 	for (i = 0; i < max_ncpus; i++)
1004 		lb_cpu[i].lbc_counter = lb_info->lbi_thresh_calls;
1005 
1006 	/*
1007 	 * Install the softint used to switch between event and cyclic driven
1008 	 * lbolt. We use a soft interrupt to make sure the context of the
1009 	 * cyclic reprogram call is safe.
1010 	 */
1011 	lbolt_softint_add();
1012 
1013 	/*
1014 	 * Since the hybrid lbolt implementation is based on a hardware counter
1015 	 * that is reset at every hardware reboot and that we'd like to have
1016 	 * the lbolt value starting at zero after both a hardware and a fast
1017 	 * reboot, we calculate the number of clock ticks the system's been up
1018 	 * and store it in the lbi_debug_time field of the lbolt info structure.
1019 	 * The value of this field will be subtracted from lbolt before
1020 	 * returning it.
1021 	 */
1022 	lb_info->lbi_internal = lb_info->lbi_debug_time =
1023 	    (gethrtime()/nsec_per_tick);
1024 
1025 	/*
1026 	 * lbolt_hybrid points at lbolt_bootstrap until now. The LBOLT_* macros
1027 	 * and lbolt_debug_{enter,return} use this value as an indication that
1028 	 * the initializaion above hasn't been completed. Setting lbolt_hybrid
1029 	 * to either lbolt_{cyclic,event}_driven here signals those code paths
1030 	 * that the lbolt related structures can be used.
1031 	 */
1032 	if (lbolt_cyc_only) {
1033 		lbolt_when.cyt_when = 0;
1034 		lbolt_hybrid = lbolt_cyclic_driven;
1035 	} else {
1036 		lbolt_when.cyt_when = CY_INFINITY;
1037 		lbolt_hybrid = lbolt_event_driven;
1038 	}
1039 
1040 	/*
1041 	 * Grab cpu_lock and install all three cyclics.
1042 	 */
1043 	mutex_enter(&cpu_lock);
1044 
1045 	clock_cyclic = cyclic_add(&clk_hdlr, &clk_when);
1046 	ddi_timer_cyclic = cyclic_add(&timer_hdlr, &clk_when);
1047 	lb_info->id.lbi_cyclic_id = cyclic_add(&lbolt_hdlr, &lbolt_when);
1048 
1049 	mutex_exit(&cpu_lock);
1050 }
1051 
1052 /*
1053  * Called before calcloadavg to get 10-sec moving loadavg together
1054  */
1055 
1056 static int
1057 genloadavg(struct loadavg_s *avgs)
1058 {
1059 	int avg;
1060 	int spos; /* starting position */
1061 	int cpos; /* moving current position */
1062 	int i;
1063 	int slen;
1064 	hrtime_t hr_avg;
1065 
1066 	/* 10-second snapshot, calculate first positon */
1067 	if (avgs->lg_len == 0) {
1068 		return (0);
1069 	}
1070 	slen = avgs->lg_len < S_MOVAVG_SZ ? avgs->lg_len : S_MOVAVG_SZ;
1071 
1072 	spos = (avgs->lg_cur - 1) >= 0 ? avgs->lg_cur - 1 :
1073 	    S_LOADAVG_SZ + (avgs->lg_cur - 1);
1074 	for (i = hr_avg = 0; i < slen; i++) {
1075 		cpos = (spos - i) >= 0 ? spos - i : S_LOADAVG_SZ + (spos - i);
1076 		hr_avg += avgs->lg_loads[cpos];
1077 	}
1078 
1079 	hr_avg = hr_avg / slen;
1080 	avg = hr_avg / (NANOSEC / LGRP_LOADAVG_IN_THREAD_MAX);
1081 
1082 	return (avg);
1083 }
1084 
1085 /*
1086  * Run every second from clock () to update the loadavg count available to the
1087  * system and cpu-partitions.
1088  *
1089  * This works by sampling the previous usr, sys, wait time elapsed,
1090  * computing a delta, and adding that delta to the elapsed usr, sys,
1091  * wait increase.
1092  */
1093 
1094 static void
1095 loadavg_update()
1096 {
1097 	cpu_t *cp;
1098 	cpupart_t *cpupart;
1099 	hrtime_t cpu_total;
1100 	int prev;
1101 
1102 	cp = cpu_list;
1103 	loadavg.lg_total = 0;
1104 
1105 	/*
1106 	 * first pass totals up per-cpu statistics for system and cpu
1107 	 * partitions
1108 	 */
1109 
1110 	do {
1111 		struct loadavg_s *lavg;
1112 
1113 		lavg = &cp->cpu_loadavg;
1114 
1115 		cpu_total = cp->cpu_acct[CMS_USER] +
1116 		    cp->cpu_acct[CMS_SYSTEM] + cp->cpu_waitrq;
1117 		/* compute delta against last total */
1118 		scalehrtime(&cpu_total);
1119 		prev = (lavg->lg_cur - 1) >= 0 ? lavg->lg_cur - 1 :
1120 		    S_LOADAVG_SZ + (lavg->lg_cur - 1);
1121 		if (lavg->lg_loads[prev] <= 0) {
1122 			lavg->lg_loads[lavg->lg_cur] = cpu_total;
1123 			cpu_total = 0;
1124 		} else {
1125 			lavg->lg_loads[lavg->lg_cur] = cpu_total;
1126 			cpu_total = cpu_total - lavg->lg_loads[prev];
1127 			if (cpu_total < 0)
1128 				cpu_total = 0;
1129 		}
1130 
1131 		lavg->lg_cur = (lavg->lg_cur + 1) % S_LOADAVG_SZ;
1132 		lavg->lg_len = (lavg->lg_len + 1) < S_LOADAVG_SZ ?
1133 		    lavg->lg_len + 1 : S_LOADAVG_SZ;
1134 
1135 		loadavg.lg_total += cpu_total;
1136 		cp->cpu_part->cp_loadavg.lg_total += cpu_total;
1137 
1138 	} while ((cp = cp->cpu_next) != cpu_list);
1139 
1140 	loadavg.lg_loads[loadavg.lg_cur] = loadavg.lg_total;
1141 	loadavg.lg_cur = (loadavg.lg_cur + 1) % S_LOADAVG_SZ;
1142 	loadavg.lg_len = (loadavg.lg_len + 1) < S_LOADAVG_SZ ?
1143 	    loadavg.lg_len + 1 : S_LOADAVG_SZ;
1144 	/*
1145 	 * Second pass updates counts
1146 	 */
1147 	cpupart = cp_list_head;
1148 
1149 	do {
1150 		struct loadavg_s *lavg;
1151 
1152 		lavg = &cpupart->cp_loadavg;
1153 		lavg->lg_loads[lavg->lg_cur] = lavg->lg_total;
1154 		lavg->lg_total = 0;
1155 		lavg->lg_cur = (lavg->lg_cur + 1) % S_LOADAVG_SZ;
1156 		lavg->lg_len = (lavg->lg_len + 1) < S_LOADAVG_SZ ?
1157 		    lavg->lg_len + 1 : S_LOADAVG_SZ;
1158 
1159 	} while ((cpupart = cpupart->cp_next) != cp_list_head);
1160 
1161 }
1162 
1163 /*
1164  * clock_update() - local clock update
1165  *
1166  * This routine is called by ntp_adjtime() to update the local clock
1167  * phase and frequency. The implementation is of an
1168  * adaptive-parameter, hybrid phase/frequency-lock loop (PLL/FLL). The
1169  * routine computes new time and frequency offset estimates for each
1170  * call.  The PPS signal itself determines the new time offset,
1171  * instead of the calling argument.  Presumably, calls to
1172  * ntp_adjtime() occur only when the caller believes the local clock
1173  * is valid within some bound (+-128 ms with NTP). If the caller's
1174  * time is far different than the PPS time, an argument will ensue,
1175  * and it's not clear who will lose.
1176  *
1177  * For uncompensated quartz crystal oscillatores and nominal update
1178  * intervals less than 1024 s, operation should be in phase-lock mode
1179  * (STA_FLL = 0), where the loop is disciplined to phase. For update
1180  * intervals greater than this, operation should be in frequency-lock
1181  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1182  *
1183  * Note: mutex(&tod_lock) is in effect.
1184  */
1185 void
1186 clock_update(int offset)
1187 {
1188 	int ltemp, mtemp, s;
1189 
1190 	ASSERT(MUTEX_HELD(&tod_lock));
1191 
1192 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1193 		return;
1194 	ltemp = offset;
1195 	if ((time_status & STA_PPSTIME) && (time_status & STA_PPSSIGNAL))
1196 		ltemp = pps_offset;
1197 
1198 	/*
1199 	 * Scale the phase adjustment and clamp to the operating range.
1200 	 */
1201 	if (ltemp > MAXPHASE)
1202 		time_offset = MAXPHASE * SCALE_UPDATE;
1203 	else if (ltemp < -MAXPHASE)
1204 		time_offset = -(MAXPHASE * SCALE_UPDATE);
1205 	else
1206 		time_offset = ltemp * SCALE_UPDATE;
1207 
1208 	/*
1209 	 * Select whether the frequency is to be controlled and in which
1210 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
1211 	 * multiply/divide should be replaced someday.
1212 	 */
1213 	if (time_status & STA_FREQHOLD || time_reftime == 0)
1214 		time_reftime = hrestime.tv_sec;
1215 
1216 	mtemp = hrestime.tv_sec - time_reftime;
1217 	time_reftime = hrestime.tv_sec;
1218 
1219 	if (time_status & STA_FLL) {
1220 		if (mtemp >= MINSEC) {
1221 			ltemp = ((time_offset / mtemp) * (SCALE_USEC /
1222 			    SCALE_UPDATE));
1223 			if (ltemp)
1224 				time_freq += ltemp / SCALE_KH;
1225 		}
1226 	} else {
1227 		if (mtemp < MAXSEC) {
1228 			ltemp *= mtemp;
1229 			if (ltemp)
1230 				time_freq += (int)(((int64_t)ltemp *
1231 				    SCALE_USEC) / SCALE_KF)
1232 				    / (1 << (time_constant * 2));
1233 		}
1234 	}
1235 	if (time_freq > time_tolerance)
1236 		time_freq = time_tolerance;
1237 	else if (time_freq < -time_tolerance)
1238 		time_freq = -time_tolerance;
1239 
1240 	s = hr_clock_lock();
1241 	tod_needsync = 1;
1242 	hr_clock_unlock(s);
1243 }
1244 
1245 /*
1246  * ddi_hardpps() - discipline CPU clock oscillator to external PPS signal
1247  *
1248  * This routine is called at each PPS interrupt in order to discipline
1249  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1250  * and leaves it in a handy spot for the clock() routine. It
1251  * integrates successive PPS phase differences and calculates the
1252  * frequency offset. This is used in clock() to discipline the CPU
1253  * clock oscillator so that intrinsic frequency error is cancelled out.
1254  * The code requires the caller to capture the time and hardware counter
1255  * value at the on-time PPS signal transition.
1256  *
1257  * Note that, on some Unix systems, this routine runs at an interrupt
1258  * priority level higher than the timer interrupt routine clock().
1259  * Therefore, the variables used are distinct from the clock()
1260  * variables, except for certain exceptions: The PPS frequency pps_freq
1261  * and phase pps_offset variables are determined by this routine and
1262  * updated atomically. The time_tolerance variable can be considered a
1263  * constant, since it is infrequently changed, and then only when the
1264  * PPS signal is disabled. The watchdog counter pps_valid is updated
1265  * once per second by clock() and is atomically cleared in this
1266  * routine.
1267  *
1268  * tvp is the time of the last tick; usec is a microsecond count since the
1269  * last tick.
1270  *
1271  * Note: In Solaris systems, the tick value is actually given by
1272  *       usec_per_tick.  This is called from the serial driver cdintr(),
1273  *	 or equivalent, at a high PIL.  Because the kernel keeps a
1274  *	 highresolution time, the following code can accept either
1275  *	 the traditional argument pair, or the current highres timestamp
1276  *       in tvp and zero in usec.
1277  */
1278 void
1279 ddi_hardpps(struct timeval *tvp, int usec)
1280 {
1281 	int u_usec, v_usec, bigtick;
1282 	time_t cal_sec;
1283 	int cal_usec;
1284 
1285 	/*
1286 	 * An occasional glitch can be produced when the PPS interrupt
1287 	 * occurs in the clock() routine before the time variable is
1288 	 * updated. Here the offset is discarded when the difference
1289 	 * between it and the last one is greater than tick/2, but not
1290 	 * if the interval since the first discard exceeds 30 s.
1291 	 */
1292 	time_status |= STA_PPSSIGNAL;
1293 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1294 	pps_valid = 0;
1295 	u_usec = -tvp->tv_usec;
1296 	if (u_usec < -(MICROSEC/2))
1297 		u_usec += MICROSEC;
1298 	v_usec = pps_offset - u_usec;
1299 	if (v_usec < 0)
1300 		v_usec = -v_usec;
1301 	if (v_usec > (usec_per_tick >> 1)) {
1302 		if (pps_glitch > MAXGLITCH) {
1303 			pps_glitch = 0;
1304 			pps_tf[2] = u_usec;
1305 			pps_tf[1] = u_usec;
1306 		} else {
1307 			pps_glitch++;
1308 			u_usec = pps_offset;
1309 		}
1310 	} else
1311 		pps_glitch = 0;
1312 
1313 	/*
1314 	 * A three-stage median filter is used to help deglitch the pps
1315 	 * time. The median sample becomes the time offset estimate; the
1316 	 * difference between the other two samples becomes the time
1317 	 * dispersion (jitter) estimate.
1318 	 */
1319 	pps_tf[2] = pps_tf[1];
1320 	pps_tf[1] = pps_tf[0];
1321 	pps_tf[0] = u_usec;
1322 	if (pps_tf[0] > pps_tf[1]) {
1323 		if (pps_tf[1] > pps_tf[2]) {
1324 			pps_offset = pps_tf[1];		/* 0 1 2 */
1325 			v_usec = pps_tf[0] - pps_tf[2];
1326 		} else if (pps_tf[2] > pps_tf[0]) {
1327 			pps_offset = pps_tf[0];		/* 2 0 1 */
1328 			v_usec = pps_tf[2] - pps_tf[1];
1329 		} else {
1330 			pps_offset = pps_tf[2];		/* 0 2 1 */
1331 			v_usec = pps_tf[0] - pps_tf[1];
1332 		}
1333 	} else {
1334 		if (pps_tf[1] < pps_tf[2]) {
1335 			pps_offset = pps_tf[1];		/* 2 1 0 */
1336 			v_usec = pps_tf[2] - pps_tf[0];
1337 		} else  if (pps_tf[2] < pps_tf[0]) {
1338 			pps_offset = pps_tf[0];		/* 1 0 2 */
1339 			v_usec = pps_tf[1] - pps_tf[2];
1340 		} else {
1341 			pps_offset = pps_tf[2];		/* 1 2 0 */
1342 			v_usec = pps_tf[1] - pps_tf[0];
1343 		}
1344 	}
1345 	if (v_usec > MAXTIME)
1346 		pps_jitcnt++;
1347 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1348 	pps_jitter += v_usec / (1 << PPS_AVG);
1349 	if (pps_jitter > (MAXTIME >> 1))
1350 		time_status |= STA_PPSJITTER;
1351 
1352 	/*
1353 	 * During the calibration interval adjust the starting time when
1354 	 * the tick overflows. At the end of the interval compute the
1355 	 * duration of the interval and the difference of the hardware
1356 	 * counters at the beginning and end of the interval. This code
1357 	 * is deliciously complicated by the fact valid differences may
1358 	 * exceed the value of tick when using long calibration
1359 	 * intervals and small ticks. Note that the counter can be
1360 	 * greater than tick if caught at just the wrong instant, but
1361 	 * the values returned and used here are correct.
1362 	 */
1363 	bigtick = (int)usec_per_tick * SCALE_USEC;
1364 	pps_usec -= pps_freq;
1365 	if (pps_usec >= bigtick)
1366 		pps_usec -= bigtick;
1367 	if (pps_usec < 0)
1368 		pps_usec += bigtick;
1369 	pps_time.tv_sec++;
1370 	pps_count++;
1371 	if (pps_count < (1 << pps_shift))
1372 		return;
1373 	pps_count = 0;
1374 	pps_calcnt++;
1375 	u_usec = usec * SCALE_USEC;
1376 	v_usec = pps_usec - u_usec;
1377 	if (v_usec >= bigtick >> 1)
1378 		v_usec -= bigtick;
1379 	if (v_usec < -(bigtick >> 1))
1380 		v_usec += bigtick;
1381 	if (v_usec < 0)
1382 		v_usec = -(-v_usec >> pps_shift);
1383 	else
1384 		v_usec = v_usec >> pps_shift;
1385 	pps_usec = u_usec;
1386 	cal_sec = tvp->tv_sec;
1387 	cal_usec = tvp->tv_usec;
1388 	cal_sec -= pps_time.tv_sec;
1389 	cal_usec -= pps_time.tv_usec;
1390 	if (cal_usec < 0) {
1391 		cal_usec += MICROSEC;
1392 		cal_sec--;
1393 	}
1394 	pps_time = *tvp;
1395 
1396 	/*
1397 	 * Check for lost interrupts, noise, excessive jitter and
1398 	 * excessive frequency error. The number of timer ticks during
1399 	 * the interval may vary +-1 tick. Add to this a margin of one
1400 	 * tick for the PPS signal jitter and maximum frequency
1401 	 * deviation. If the limits are exceeded, the calibration
1402 	 * interval is reset to the minimum and we start over.
1403 	 */
1404 	u_usec = (int)usec_per_tick << 1;
1405 	if (!((cal_sec == -1 && cal_usec > (MICROSEC - u_usec)) ||
1406 	    (cal_sec == 0 && cal_usec < u_usec)) ||
1407 	    v_usec > time_tolerance || v_usec < -time_tolerance) {
1408 		pps_errcnt++;
1409 		pps_shift = PPS_SHIFT;
1410 		pps_intcnt = 0;
1411 		time_status |= STA_PPSERROR;
1412 		return;
1413 	}
1414 
1415 	/*
1416 	 * A three-stage median filter is used to help deglitch the pps
1417 	 * frequency. The median sample becomes the frequency offset
1418 	 * estimate; the difference between the other two samples
1419 	 * becomes the frequency dispersion (stability) estimate.
1420 	 */
1421 	pps_ff[2] = pps_ff[1];
1422 	pps_ff[1] = pps_ff[0];
1423 	pps_ff[0] = v_usec;
1424 	if (pps_ff[0] > pps_ff[1]) {
1425 		if (pps_ff[1] > pps_ff[2]) {
1426 			u_usec = pps_ff[1];		/* 0 1 2 */
1427 			v_usec = pps_ff[0] - pps_ff[2];
1428 		} else if (pps_ff[2] > pps_ff[0]) {
1429 			u_usec = pps_ff[0];		/* 2 0 1 */
1430 			v_usec = pps_ff[2] - pps_ff[1];
1431 		} else {
1432 			u_usec = pps_ff[2];		/* 0 2 1 */
1433 			v_usec = pps_ff[0] - pps_ff[1];
1434 		}
1435 	} else {
1436 		if (pps_ff[1] < pps_ff[2]) {
1437 			u_usec = pps_ff[1];		/* 2 1 0 */
1438 			v_usec = pps_ff[2] - pps_ff[0];
1439 		} else  if (pps_ff[2] < pps_ff[0]) {
1440 			u_usec = pps_ff[0];		/* 1 0 2 */
1441 			v_usec = pps_ff[1] - pps_ff[2];
1442 		} else {
1443 			u_usec = pps_ff[2];		/* 1 2 0 */
1444 			v_usec = pps_ff[1] - pps_ff[0];
1445 		}
1446 	}
1447 
1448 	/*
1449 	 * Here the frequency dispersion (stability) is updated. If it
1450 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1451 	 * offset is updated as well, but clamped to the tolerance. It
1452 	 * will be processed later by the clock() routine.
1453 	 */
1454 	v_usec = (v_usec >> 1) - pps_stabil;
1455 	if (v_usec < 0)
1456 		pps_stabil -= -v_usec >> PPS_AVG;
1457 	else
1458 		pps_stabil += v_usec >> PPS_AVG;
1459 	if (pps_stabil > MAXFREQ >> 2) {
1460 		pps_stbcnt++;
1461 		time_status |= STA_PPSWANDER;
1462 		return;
1463 	}
1464 	if (time_status & STA_PPSFREQ) {
1465 		if (u_usec < 0) {
1466 			pps_freq -= -u_usec >> PPS_AVG;
1467 			if (pps_freq < -time_tolerance)
1468 				pps_freq = -time_tolerance;
1469 			u_usec = -u_usec;
1470 		} else {
1471 			pps_freq += u_usec >> PPS_AVG;
1472 			if (pps_freq > time_tolerance)
1473 				pps_freq = time_tolerance;
1474 		}
1475 	}
1476 
1477 	/*
1478 	 * Here the calibration interval is adjusted. If the maximum
1479 	 * time difference is greater than tick / 4, reduce the interval
1480 	 * by half. If this is not the case for four consecutive
1481 	 * intervals, double the interval.
1482 	 */
1483 	if (u_usec << pps_shift > bigtick >> 2) {
1484 		pps_intcnt = 0;
1485 		if (pps_shift > PPS_SHIFT)
1486 			pps_shift--;
1487 	} else if (pps_intcnt >= 4) {
1488 		pps_intcnt = 0;
1489 		if (pps_shift < PPS_SHIFTMAX)
1490 			pps_shift++;
1491 	} else
1492 		pps_intcnt++;
1493 
1494 	/*
1495 	 * If recovering from kmdb, then make sure the tod chip gets resynced.
1496 	 * If we took an early exit above, then we don't yet have a stable
1497 	 * calibration signal to lock onto, so don't mark the tod for sync
1498 	 * until we get all the way here.
1499 	 */
1500 	{
1501 		int s = hr_clock_lock();
1502 
1503 		tod_needsync = 1;
1504 		hr_clock_unlock(s);
1505 	}
1506 }
1507 
1508 /*
1509  * Handle clock tick processing for a thread.
1510  * Check for timer action, enforce CPU rlimit, do profiling etc.
1511  */
1512 void
1513 clock_tick(kthread_t *t, int pending)
1514 {
1515 	struct proc *pp;
1516 	klwp_id_t    lwp;
1517 	struct as *as;
1518 	clock_t	ticks;
1519 	int	poke = 0;		/* notify another CPU */
1520 	int	user_mode;
1521 	size_t	 rss;
1522 	int i, total_usec, usec;
1523 	rctl_qty_t secs;
1524 
1525 	ASSERT(pending > 0);
1526 
1527 	/* Must be operating on a lwp/thread */
1528 	if ((lwp = ttolwp(t)) == NULL) {
1529 		panic("clock_tick: no lwp");
1530 		/*NOTREACHED*/
1531 	}
1532 
1533 	for (i = 0; i < pending; i++) {
1534 		CL_TICK(t);	/* Class specific tick processing */
1535 		DTRACE_SCHED1(tick, kthread_t *, t);
1536 	}
1537 
1538 	pp = ttoproc(t);
1539 
1540 	/* pp->p_lock makes sure that the thread does not exit */
1541 	ASSERT(MUTEX_HELD(&pp->p_lock));
1542 
1543 	user_mode = (lwp->lwp_state == LWP_USER);
1544 
1545 	ticks = (pp->p_utime + pp->p_stime) % hz;
1546 	/*
1547 	 * Update process times. Should use high res clock and state
1548 	 * changes instead of statistical sampling method. XXX
1549 	 */
1550 	if (user_mode) {
1551 		pp->p_utime += pending;
1552 	} else {
1553 		pp->p_stime += pending;
1554 	}
1555 
1556 	pp->p_ttime += pending;
1557 	as = pp->p_as;
1558 
1559 	/*
1560 	 * Update user profiling statistics. Get the pc from the
1561 	 * lwp when the AST happens.
1562 	 */
1563 	if (pp->p_prof.pr_scale) {
1564 		atomic_add_32(&lwp->lwp_oweupc, (int32_t)pending);
1565 		if (user_mode) {
1566 			poke = 1;
1567 			aston(t);
1568 		}
1569 	}
1570 
1571 	/*
1572 	 * If CPU was in user state, process lwp-virtual time
1573 	 * interval timer. The value passed to itimerdecr() has to be
1574 	 * in microseconds and has to be less than one second. Hence
1575 	 * this loop.
1576 	 */
1577 	total_usec = usec_per_tick * pending;
1578 	while (total_usec > 0) {
1579 		usec = MIN(total_usec, (MICROSEC - 1));
1580 		if (user_mode &&
1581 		    timerisset(&lwp->lwp_timer[ITIMER_VIRTUAL].it_value) &&
1582 		    itimerdecr(&lwp->lwp_timer[ITIMER_VIRTUAL], usec) == 0) {
1583 			poke = 1;
1584 			sigtoproc(pp, t, SIGVTALRM);
1585 		}
1586 		total_usec -= usec;
1587 	}
1588 
1589 	/*
1590 	 * If CPU was in user state, process lwp-profile
1591 	 * interval timer.
1592 	 */
1593 	total_usec = usec_per_tick * pending;
1594 	while (total_usec > 0) {
1595 		usec = MIN(total_usec, (MICROSEC - 1));
1596 		if (timerisset(&lwp->lwp_timer[ITIMER_PROF].it_value) &&
1597 		    itimerdecr(&lwp->lwp_timer[ITIMER_PROF], usec) == 0) {
1598 			poke = 1;
1599 			sigtoproc(pp, t, SIGPROF);
1600 		}
1601 		total_usec -= usec;
1602 	}
1603 
1604 	/*
1605 	 * Enforce CPU resource controls:
1606 	 *   (a) process.max-cpu-time resource control
1607 	 *
1608 	 * Perform the check only if we have accumulated more a second.
1609 	 */
1610 	if ((ticks + pending) >= hz) {
1611 		(void) rctl_test(rctlproc_legacy[RLIMIT_CPU], pp->p_rctls, pp,
1612 		    (pp->p_utime + pp->p_stime)/hz, RCA_UNSAFE_SIGINFO);
1613 	}
1614 
1615 	/*
1616 	 *   (b) task.max-cpu-time resource control
1617 	 *
1618 	 * If we have accumulated enough ticks, increment the task CPU
1619 	 * time usage and test for the resource limit. This minimizes the
1620 	 * number of calls to the rct_test(). The task CPU time mutex
1621 	 * is highly contentious as many processes can be sharing a task.
1622 	 */
1623 	if (pp->p_ttime >= clock_tick_proc_max) {
1624 		secs = task_cpu_time_incr(pp->p_task, pp->p_ttime);
1625 		pp->p_ttime = 0;
1626 		if (secs) {
1627 			(void) rctl_test(rc_task_cpu_time, pp->p_task->tk_rctls,
1628 			    pp, secs, RCA_UNSAFE_SIGINFO);
1629 		}
1630 	}
1631 
1632 	/*
1633 	 * Update memory usage for the currently running process.
1634 	 */
1635 	rss = rm_asrss(as);
1636 	PTOU(pp)->u_mem += rss;
1637 	if (rss > PTOU(pp)->u_mem_max)
1638 		PTOU(pp)->u_mem_max = rss;
1639 
1640 	/*
1641 	 * Notify the CPU the thread is running on.
1642 	 */
1643 	if (poke && t->t_cpu != CPU)
1644 		poke_cpu(t->t_cpu->cpu_id);
1645 }
1646 
1647 void
1648 profil_tick(uintptr_t upc)
1649 {
1650 	int ticks;
1651 	proc_t *p = ttoproc(curthread);
1652 	klwp_t *lwp = ttolwp(curthread);
1653 	struct prof *pr = &p->p_prof;
1654 
1655 	do {
1656 		ticks = lwp->lwp_oweupc;
1657 	} while (cas32(&lwp->lwp_oweupc, ticks, 0) != ticks);
1658 
1659 	mutex_enter(&p->p_pflock);
1660 	if (pr->pr_scale >= 2 && upc >= pr->pr_off) {
1661 		/*
1662 		 * Old-style profiling
1663 		 */
1664 		uint16_t *slot = pr->pr_base;
1665 		uint16_t old, new;
1666 		if (pr->pr_scale != 2) {
1667 			uintptr_t delta = upc - pr->pr_off;
1668 			uintptr_t byteoff = ((delta >> 16) * pr->pr_scale) +
1669 			    (((delta & 0xffff) * pr->pr_scale) >> 16);
1670 			if (byteoff >= (uintptr_t)pr->pr_size) {
1671 				mutex_exit(&p->p_pflock);
1672 				return;
1673 			}
1674 			slot += byteoff / sizeof (uint16_t);
1675 		}
1676 		if (fuword16(slot, &old) < 0 ||
1677 		    (new = old + ticks) > SHRT_MAX ||
1678 		    suword16(slot, new) < 0) {
1679 			pr->pr_scale = 0;
1680 		}
1681 	} else if (pr->pr_scale == 1) {
1682 		/*
1683 		 * PC Sampling
1684 		 */
1685 		model_t model = lwp_getdatamodel(lwp);
1686 		int result;
1687 #ifdef __lint
1688 		model = model;
1689 #endif
1690 		while (ticks-- > 0) {
1691 			if (pr->pr_samples == pr->pr_size) {
1692 				/* buffer full, turn off sampling */
1693 				pr->pr_scale = 0;
1694 				break;
1695 			}
1696 			switch (SIZEOF_PTR(model)) {
1697 			case sizeof (uint32_t):
1698 				result = suword32(pr->pr_base, (uint32_t)upc);
1699 				break;
1700 #ifdef _LP64
1701 			case sizeof (uint64_t):
1702 				result = suword64(pr->pr_base, (uint64_t)upc);
1703 				break;
1704 #endif
1705 			default:
1706 				cmn_err(CE_WARN, "profil_tick: unexpected "
1707 				    "data model");
1708 				result = -1;
1709 				break;
1710 			}
1711 			if (result != 0) {
1712 				pr->pr_scale = 0;
1713 				break;
1714 			}
1715 			pr->pr_base = (caddr_t)pr->pr_base + SIZEOF_PTR(model);
1716 			pr->pr_samples++;
1717 		}
1718 	}
1719 	mutex_exit(&p->p_pflock);
1720 }
1721 
1722 static void
1723 delay_wakeup(void *arg)
1724 {
1725 	kthread_t	*t = arg;
1726 
1727 	mutex_enter(&t->t_delay_lock);
1728 	cv_signal(&t->t_delay_cv);
1729 	mutex_exit(&t->t_delay_lock);
1730 }
1731 
1732 /*
1733  * The delay(9F) man page indicates that it can only be called from user or
1734  * kernel context - detect and diagnose bad calls. The following macro will
1735  * produce a limited number of messages identifying bad callers.  This is done
1736  * in a macro so that caller() is meaningful. When a bad caller is identified,
1737  * switching to 'drv_usecwait(TICK_TO_USEC(ticks));' may be appropriate.
1738  */
1739 #define	DELAY_CONTEXT_CHECK()	{					\
1740 	uint32_t	m;						\
1741 	char		*f;						\
1742 	ulong_t		off;						\
1743 									\
1744 	m = delay_from_interrupt_msg;					\
1745 	if (delay_from_interrupt_diagnose && servicing_interrupt() &&	\
1746 	    !panicstr && !devinfo_freeze &&				\
1747 	    atomic_cas_32(&delay_from_interrupt_msg, m ? m : 1, m-1)) {	\
1748 		f = modgetsymname((uintptr_t)caller(), &off);		\
1749 		cmn_err(CE_WARN, "delay(9F) called from "		\
1750 		    "interrupt context: %s`%s",				\
1751 		    mod_containing_pc(caller()), f ? f : "...");	\
1752 	}								\
1753 }
1754 
1755 /*
1756  * delay_common: common delay code.
1757  */
1758 static void
1759 delay_common(clock_t ticks)
1760 {
1761 	kthread_t	*t = curthread;
1762 	clock_t		deadline;
1763 	clock_t		timeleft;
1764 	callout_id_t	id;
1765 
1766 	/* If timeouts aren't running all we can do is spin. */
1767 	if (panicstr || devinfo_freeze) {
1768 		/* Convert delay(9F) call into drv_usecwait(9F) call. */
1769 		if (ticks > 0)
1770 			drv_usecwait(TICK_TO_USEC(ticks));
1771 		return;
1772 	}
1773 
1774 	deadline = ddi_get_lbolt() + ticks;
1775 	while ((timeleft = deadline - ddi_get_lbolt()) > 0) {
1776 		mutex_enter(&t->t_delay_lock);
1777 		id = timeout_default(delay_wakeup, t, timeleft);
1778 		cv_wait(&t->t_delay_cv, &t->t_delay_lock);
1779 		mutex_exit(&t->t_delay_lock);
1780 		(void) untimeout_default(id, 0);
1781 	}
1782 }
1783 
1784 /*
1785  * Delay specified number of clock ticks.
1786  */
1787 void
1788 delay(clock_t ticks)
1789 {
1790 	DELAY_CONTEXT_CHECK();
1791 
1792 	delay_common(ticks);
1793 }
1794 
1795 /*
1796  * Delay a random number of clock ticks between 1 and ticks.
1797  */
1798 void
1799 delay_random(clock_t ticks)
1800 {
1801 	int	r;
1802 
1803 	DELAY_CONTEXT_CHECK();
1804 
1805 	(void) random_get_pseudo_bytes((void *)&r, sizeof (r));
1806 	if (ticks == 0)
1807 		ticks = 1;
1808 	ticks = (r % ticks) + 1;
1809 	delay_common(ticks);
1810 }
1811 
1812 /*
1813  * Like delay, but interruptible by a signal.
1814  */
1815 int
1816 delay_sig(clock_t ticks)
1817 {
1818 	kthread_t	*t = curthread;
1819 	clock_t		deadline;
1820 	clock_t		rc;
1821 
1822 	/* If timeouts aren't running all we can do is spin. */
1823 	if (panicstr || devinfo_freeze) {
1824 		if (ticks > 0)
1825 			drv_usecwait(TICK_TO_USEC(ticks));
1826 		return (0);
1827 	}
1828 
1829 	deadline = ddi_get_lbolt() + ticks;
1830 	mutex_enter(&t->t_delay_lock);
1831 	do {
1832 		rc = cv_timedwait_sig(&t->t_delay_cv,
1833 		    &t->t_delay_lock, deadline);
1834 		/* loop until past deadline or signaled */
1835 	} while (rc > 0);
1836 	mutex_exit(&t->t_delay_lock);
1837 	if (rc == 0)
1838 		return (EINTR);
1839 	return (0);
1840 }
1841 
1842 
1843 #define	SECONDS_PER_DAY 86400
1844 
1845 /*
1846  * Initialize the system time based on the TOD chip.  approx is used as
1847  * an approximation of time (e.g. from the filesystem) in the event that
1848  * the TOD chip has been cleared or is unresponsive.  An approx of -1
1849  * means the filesystem doesn't keep time.
1850  */
1851 void
1852 clkset(time_t approx)
1853 {
1854 	timestruc_t ts;
1855 	int spl;
1856 	int set_clock = 0;
1857 
1858 	mutex_enter(&tod_lock);
1859 	ts = tod_get();
1860 
1861 	if (ts.tv_sec > 365 * SECONDS_PER_DAY) {
1862 		/*
1863 		 * If the TOD chip is reporting some time after 1971,
1864 		 * then it probably didn't lose power or become otherwise
1865 		 * cleared in the recent past;  check to assure that
1866 		 * the time coming from the filesystem isn't in the future
1867 		 * according to the TOD chip.
1868 		 */
1869 		if (approx != -1 && approx > ts.tv_sec) {
1870 			cmn_err(CE_WARN, "Last shutdown is later "
1871 			    "than time on time-of-day chip; check date.");
1872 		}
1873 	} else {
1874 		/*
1875 		 * If the TOD chip isn't giving correct time, set it to the
1876 		 * greater of i) approx and ii) 1987. That way if approx
1877 		 * is negative or is earlier than 1987, we set the clock
1878 		 * back to a time when Oliver North, ALF and Dire Straits
1879 		 * were all on the collective brain:  1987.
1880 		 */
1881 		timestruc_t tmp;
1882 		time_t diagnose_date = (1987 - 1970) * 365 * SECONDS_PER_DAY;
1883 		ts.tv_sec = (approx > diagnose_date ? approx : diagnose_date);
1884 		ts.tv_nsec = 0;
1885 
1886 		/*
1887 		 * Attempt to write the new time to the TOD chip.  Set spl high
1888 		 * to avoid getting preempted between the tod_set and tod_get.
1889 		 */
1890 		spl = splhi();
1891 		tod_set(ts);
1892 		tmp = tod_get();
1893 		splx(spl);
1894 
1895 		if (tmp.tv_sec != ts.tv_sec && tmp.tv_sec != ts.tv_sec + 1) {
1896 			tod_broken = 1;
1897 			dosynctodr = 0;
1898 			cmn_err(CE_WARN, "Time-of-day chip unresponsive.");
1899 		} else {
1900 			cmn_err(CE_WARN, "Time-of-day chip had "
1901 			    "incorrect date; check and reset.");
1902 		}
1903 		set_clock = 1;
1904 	}
1905 
1906 	if (!boot_time) {
1907 		boot_time = ts.tv_sec;
1908 		set_clock = 1;
1909 	}
1910 
1911 	if (set_clock)
1912 		set_hrestime(&ts);
1913 
1914 	mutex_exit(&tod_lock);
1915 }
1916 
1917 int	timechanged;	/* for testing if the system time has been reset */
1918 
1919 void
1920 set_hrestime(timestruc_t *ts)
1921 {
1922 	int spl = hr_clock_lock();
1923 	hrestime = *ts;
1924 	membar_enter();	/* hrestime must be visible before timechanged++ */
1925 	timedelta = 0;
1926 	timechanged++;
1927 	hr_clock_unlock(spl);
1928 	callout_hrestime();
1929 }
1930 
1931 static uint_t deadman_seconds;
1932 static uint32_t deadman_panics;
1933 static int deadman_enabled = 0;
1934 static int deadman_panic_timers = 1;
1935 
1936 static void
1937 deadman(void)
1938 {
1939 	if (panicstr) {
1940 		/*
1941 		 * During panic, other CPUs besides the panic
1942 		 * master continue to handle cyclics and some other
1943 		 * interrupts.  The code below is intended to be
1944 		 * single threaded, so any CPU other than the master
1945 		 * must keep out.
1946 		 */
1947 		if (CPU->cpu_id != panic_cpu.cpu_id)
1948 			return;
1949 
1950 		if (!deadman_panic_timers)
1951 			return; /* allow all timers to be manually disabled */
1952 
1953 		/*
1954 		 * If we are generating a crash dump or syncing filesystems and
1955 		 * the corresponding timer is set, decrement it and re-enter
1956 		 * the panic code to abort it and advance to the next state.
1957 		 * The panic states and triggers are explained in panic.c.
1958 		 */
1959 		if (panic_dump) {
1960 			if (dump_timeleft && (--dump_timeleft == 0)) {
1961 				panic("panic dump timeout");
1962 				/*NOTREACHED*/
1963 			}
1964 		} else if (panic_sync) {
1965 			if (sync_timeleft && (--sync_timeleft == 0)) {
1966 				panic("panic sync timeout");
1967 				/*NOTREACHED*/
1968 			}
1969 		}
1970 
1971 		return;
1972 	}
1973 
1974 	if (deadman_counter != CPU->cpu_deadman_counter) {
1975 		CPU->cpu_deadman_counter = deadman_counter;
1976 		CPU->cpu_deadman_countdown = deadman_seconds;
1977 		return;
1978 	}
1979 
1980 	if (--CPU->cpu_deadman_countdown > 0)
1981 		return;
1982 
1983 	/*
1984 	 * Regardless of whether or not we actually bring the system down,
1985 	 * bump the deadman_panics variable.
1986 	 *
1987 	 * N.B. deadman_panics is incremented once for each CPU that
1988 	 * passes through here.  It's expected that all the CPUs will
1989 	 * detect this condition within one second of each other, so
1990 	 * when deadman_enabled is off, deadman_panics will
1991 	 * typically be a multiple of the total number of CPUs in
1992 	 * the system.
1993 	 */
1994 	atomic_add_32(&deadman_panics, 1);
1995 
1996 	if (!deadman_enabled) {
1997 		CPU->cpu_deadman_countdown = deadman_seconds;
1998 		return;
1999 	}
2000 
2001 	/*
2002 	 * If we're here, we want to bring the system down.
2003 	 */
2004 	panic("deadman: timed out after %d seconds of clock "
2005 	    "inactivity", deadman_seconds);
2006 	/*NOTREACHED*/
2007 }
2008 
2009 /*ARGSUSED*/
2010 static void
2011 deadman_online(void *arg, cpu_t *cpu, cyc_handler_t *hdlr, cyc_time_t *when)
2012 {
2013 	cpu->cpu_deadman_counter = 0;
2014 	cpu->cpu_deadman_countdown = deadman_seconds;
2015 
2016 	hdlr->cyh_func = (cyc_func_t)deadman;
2017 	hdlr->cyh_level = CY_HIGH_LEVEL;
2018 	hdlr->cyh_arg = NULL;
2019 
2020 	/*
2021 	 * Stagger the CPUs so that they don't all run deadman() at
2022 	 * the same time.  Simplest reason to do this is to make it
2023 	 * more likely that only one CPU will panic in case of a
2024 	 * timeout.  This is (strictly speaking) an aesthetic, not a
2025 	 * technical consideration.
2026 	 */
2027 	when->cyt_when = cpu->cpu_id * (NANOSEC / NCPU);
2028 	when->cyt_interval = NANOSEC;
2029 }
2030 
2031 
2032 void
2033 deadman_init(void)
2034 {
2035 	cyc_omni_handler_t hdlr;
2036 
2037 	if (deadman_seconds == 0)
2038 		deadman_seconds = snoop_interval / MICROSEC;
2039 
2040 	if (snooping)
2041 		deadman_enabled = 1;
2042 
2043 	hdlr.cyo_online = deadman_online;
2044 	hdlr.cyo_offline = NULL;
2045 	hdlr.cyo_arg = NULL;
2046 
2047 	mutex_enter(&cpu_lock);
2048 	deadman_cyclic = cyclic_add_omni(&hdlr);
2049 	mutex_exit(&cpu_lock);
2050 }
2051 
2052 /*
2053  * tod_fault() is for updating tod validate mechanism state:
2054  * (1) TOD_NOFAULT: for resetting the state to 'normal'.
2055  *     currently used for debugging only
2056  * (2) The following four cases detected by tod validate mechanism:
2057  *       TOD_REVERSED: current tod value is less than previous value.
2058  *       TOD_STALLED: current tod value hasn't advanced.
2059  *       TOD_JUMPED: current tod value advanced too far from previous value.
2060  *       TOD_RATECHANGED: the ratio between average tod delta and
2061  *       average tick delta has changed.
2062  * (3) TOD_RDONLY: when the TOD clock is not writeable e.g. because it is
2063  *     a virtual TOD provided by a hypervisor.
2064  */
2065 enum tod_fault_type
2066 tod_fault(enum tod_fault_type ftype, int off)
2067 {
2068 	ASSERT(MUTEX_HELD(&tod_lock));
2069 
2070 	if (tod_faulted != ftype) {
2071 		switch (ftype) {
2072 		case TOD_NOFAULT:
2073 			plat_tod_fault(TOD_NOFAULT);
2074 			cmn_err(CE_NOTE, "Restarted tracking "
2075 			    "Time of Day clock.");
2076 			tod_faulted = ftype;
2077 			break;
2078 		case TOD_REVERSED:
2079 		case TOD_JUMPED:
2080 			if (tod_faulted == TOD_NOFAULT) {
2081 				plat_tod_fault(ftype);
2082 				cmn_err(CE_WARN, "Time of Day clock error: "
2083 				    "reason [%s by 0x%x]. -- "
2084 				    " Stopped tracking Time Of Day clock.",
2085 				    tod_fault_table[ftype], off);
2086 				tod_faulted = ftype;
2087 			}
2088 			break;
2089 		case TOD_STALLED:
2090 		case TOD_RATECHANGED:
2091 			if (tod_faulted == TOD_NOFAULT) {
2092 				plat_tod_fault(ftype);
2093 				cmn_err(CE_WARN, "Time of Day clock error: "
2094 				    "reason [%s]. -- "
2095 				    " Stopped tracking Time Of Day clock.",
2096 				    tod_fault_table[ftype]);
2097 				tod_faulted = ftype;
2098 			}
2099 			break;
2100 		case TOD_RDONLY:
2101 			if (tod_faulted == TOD_NOFAULT) {
2102 				plat_tod_fault(ftype);
2103 				cmn_err(CE_NOTE, "!Time of Day clock is "
2104 				    "Read-Only; set of Date/Time will not "
2105 				    "persist across reboot.");
2106 				tod_faulted = ftype;
2107 			}
2108 			break;
2109 		default:
2110 			break;
2111 		}
2112 	}
2113 	return (tod_faulted);
2114 }
2115 
2116 /*
2117  * Two functions that allow tod_status_flag to be manipulated by functions
2118  * external to this file.
2119  */
2120 
2121 void
2122 tod_status_set(int tod_flag)
2123 {
2124 	tod_status_flag |= tod_flag;
2125 }
2126 
2127 void
2128 tod_status_clear(int tod_flag)
2129 {
2130 	tod_status_flag &= ~tod_flag;
2131 }
2132 
2133 /*
2134  * Record a timestamp and the value passed to tod_set().  The next call to
2135  * tod_validate() can use these values, prev_set_tick and prev_set_tod,
2136  * when checking the timestruc_t returned by tod_get().  Ordinarily,
2137  * tod_validate() will use prev_tick and prev_tod for this task but these
2138  * become obsolete, and will be re-assigned with the prev_set_* values,
2139  * in the case when the TOD is re-written.
2140  */
2141 void
2142 tod_set_prev(timestruc_t ts)
2143 {
2144 	if ((tod_validate_enable == 0) || (tod_faulted != TOD_NOFAULT) ||
2145 	    tod_validate_deferred) {
2146 		return;
2147 	}
2148 	prev_set_tick = gethrtime();
2149 	/*
2150 	 * A negative value will be set to zero in utc_to_tod() so we fake
2151 	 * a zero here in such a case.  This would need to change if the
2152 	 * behavior of utc_to_tod() changes.
2153 	 */
2154 	prev_set_tod = ts.tv_sec < 0 ? 0 : ts.tv_sec;
2155 }
2156 
2157 /*
2158  * tod_validate() is used for checking values returned by tod_get().
2159  * Four error cases can be detected by this routine:
2160  *   TOD_REVERSED: current tod value is less than previous.
2161  *   TOD_STALLED: current tod value hasn't advanced.
2162  *   TOD_JUMPED: current tod value advanced too far from previous value.
2163  *   TOD_RATECHANGED: the ratio between average tod delta and
2164  *   average tick delta has changed.
2165  */
2166 time_t
2167 tod_validate(time_t tod)
2168 {
2169 	time_t diff_tod;
2170 	hrtime_t diff_tick;
2171 
2172 	long dtick;
2173 	int dtick_delta;
2174 
2175 	int off = 0;
2176 	enum tod_fault_type tod_bad = TOD_NOFAULT;
2177 
2178 	static int firsttime = 1;
2179 
2180 	static time_t prev_tod = 0;
2181 	static hrtime_t prev_tick = 0;
2182 	static long dtick_avg = TOD_REF_FREQ;
2183 
2184 	int cpr_resume_done = 0;
2185 	int dr_resume_done = 0;
2186 
2187 	hrtime_t tick = gethrtime();
2188 
2189 	ASSERT(MUTEX_HELD(&tod_lock));
2190 
2191 	/*
2192 	 * tod_validate_enable is patchable via /etc/system.
2193 	 * If TOD is already faulted, or if TOD validation is deferred,
2194 	 * there is nothing to do.
2195 	 */
2196 	if ((tod_validate_enable == 0) || (tod_faulted != TOD_NOFAULT) ||
2197 	    tod_validate_deferred) {
2198 		return (tod);
2199 	}
2200 
2201 	/*
2202 	 * If this is the first time through, we just need to save the tod
2203 	 * we were called with and hrtime so we can use them next time to
2204 	 * validate tod_get().
2205 	 */
2206 	if (firsttime) {
2207 		firsttime = 0;
2208 		prev_tod = tod;
2209 		prev_tick = tick;
2210 		return (tod);
2211 	}
2212 
2213 	/*
2214 	 * Handle any flags that have been turned on by tod_status_set().
2215 	 * In the case where a tod_set() is done and then a subsequent
2216 	 * tod_get() fails (ie, both TOD_SET_DONE and TOD_GET_FAILED are
2217 	 * true), we treat the TOD_GET_FAILED with precedence by switching
2218 	 * off the flag, returning tod and leaving TOD_SET_DONE asserted
2219 	 * until such time as tod_get() completes successfully.
2220 	 */
2221 	if (tod_status_flag & TOD_GET_FAILED) {
2222 		/*
2223 		 * tod_get() has encountered an issue, possibly transitory,
2224 		 * when reading TOD.  We'll just return the incoming tod
2225 		 * value (which is actually hrestime.tv_sec in this case)
2226 		 * and when we get a genuine tod, following a successful
2227 		 * tod_get(), we can validate using prev_tod and prev_tick.
2228 		 */
2229 		tod_status_flag &= ~TOD_GET_FAILED;
2230 		return (tod);
2231 	} else if (tod_status_flag & TOD_SET_DONE) {
2232 		/*
2233 		 * TOD has been modified.  Just before the TOD was written,
2234 		 * tod_set_prev() saved tod and hrtime; we can now use
2235 		 * those values, prev_set_tod and prev_set_tick, to validate
2236 		 * the incoming tod that's just been read.
2237 		 */
2238 		prev_tod = prev_set_tod;
2239 		prev_tick = prev_set_tick;
2240 		dtick_avg = TOD_REF_FREQ;
2241 		tod_status_flag &= ~TOD_SET_DONE;
2242 		/*
2243 		 * If a tod_set() preceded a cpr_suspend() without an
2244 		 * intervening tod_validate(), we need to ensure that a
2245 		 * TOD_JUMPED condition is ignored.
2246 		 * Note this isn't a concern in the case of DR as we've
2247 		 * just reassigned dtick_avg, above.
2248 		 */
2249 		if (tod_status_flag & TOD_CPR_RESUME_DONE) {
2250 			cpr_resume_done = 1;
2251 			tod_status_flag &= ~TOD_CPR_RESUME_DONE;
2252 		}
2253 	} else if (tod_status_flag & TOD_CPR_RESUME_DONE) {
2254 		/*
2255 		 * The system's coming back from a checkpoint resume.
2256 		 */
2257 		cpr_resume_done = 1;
2258 		tod_status_flag &= ~TOD_CPR_RESUME_DONE;
2259 		/*
2260 		 * We need to handle the possibility of a CPR suspend
2261 		 * operation having been initiated whilst a DR event was
2262 		 * in-flight.
2263 		 */
2264 		if (tod_status_flag & TOD_DR_RESUME_DONE) {
2265 			dr_resume_done = 1;
2266 			tod_status_flag &= ~TOD_DR_RESUME_DONE;
2267 		}
2268 	} else if (tod_status_flag & TOD_DR_RESUME_DONE) {
2269 		/*
2270 		 * A Dynamic Reconfiguration event has taken place.
2271 		 */
2272 		dr_resume_done = 1;
2273 		tod_status_flag &= ~TOD_DR_RESUME_DONE;
2274 	}
2275 
2276 	/* test hook */
2277 	switch (tod_unit_test) {
2278 	case 1: /* for testing jumping tod */
2279 		tod += tod_test_injector;
2280 		tod_unit_test = 0;
2281 		break;
2282 	case 2:	/* for testing stuck tod bit */
2283 		tod |= 1 << tod_test_injector;
2284 		tod_unit_test = 0;
2285 		break;
2286 	case 3:	/* for testing stalled tod */
2287 		tod = prev_tod;
2288 		tod_unit_test = 0;
2289 		break;
2290 	case 4:	/* reset tod fault status */
2291 		(void) tod_fault(TOD_NOFAULT, 0);
2292 		tod_unit_test = 0;
2293 		break;
2294 	default:
2295 		break;
2296 	}
2297 
2298 	diff_tod = tod - prev_tod;
2299 	diff_tick = tick - prev_tick;
2300 
2301 	ASSERT(diff_tick >= 0);
2302 
2303 	if (diff_tod < 0) {
2304 		/* ERROR - tod reversed */
2305 		tod_bad = TOD_REVERSED;
2306 		off = (int)(prev_tod - tod);
2307 	} else if (diff_tod == 0) {
2308 		/* tod did not advance */
2309 		if (diff_tick > TOD_STALL_THRESHOLD) {
2310 			/* ERROR - tod stalled */
2311 			tod_bad = TOD_STALLED;
2312 		} else {
2313 			/*
2314 			 * Make sure we don't update prev_tick
2315 			 * so that diff_tick is calculated since
2316 			 * the first diff_tod == 0
2317 			 */
2318 			return (tod);
2319 		}
2320 	} else {
2321 		/* calculate dtick */
2322 		dtick = diff_tick / diff_tod;
2323 
2324 		/* update dtick averages */
2325 		dtick_avg += ((dtick - dtick_avg) / TOD_FILTER_N);
2326 
2327 		/*
2328 		 * Calculate dtick_delta as
2329 		 * variation from reference freq in quartiles
2330 		 */
2331 		dtick_delta = (dtick_avg - TOD_REF_FREQ) /
2332 		    (TOD_REF_FREQ >> 2);
2333 
2334 		/*
2335 		 * Even with a perfectly functioning TOD device,
2336 		 * when the number of elapsed seconds is low the
2337 		 * algorithm can calculate a rate that is beyond
2338 		 * tolerance, causing an error.  The algorithm is
2339 		 * inaccurate when elapsed time is low (less than
2340 		 * 5 seconds).
2341 		 */
2342 		if (diff_tod > 4) {
2343 			if (dtick < TOD_JUMP_THRESHOLD) {
2344 				/*
2345 				 * If we've just done a CPR resume, we detect
2346 				 * a jump in the TOD but, actually, what's
2347 				 * happened is that the TOD has been increasing
2348 				 * whilst the system was suspended and the tick
2349 				 * count hasn't kept up.  We consider the first
2350 				 * occurrence of this after a resume as normal
2351 				 * and ignore it; otherwise, in a non-resume
2352 				 * case, we regard it as a TOD problem.
2353 				 */
2354 				if (!cpr_resume_done) {
2355 					/* ERROR - tod jumped */
2356 					tod_bad = TOD_JUMPED;
2357 					off = (int)diff_tod;
2358 				}
2359 			}
2360 			if (dtick_delta) {
2361 				/*
2362 				 * If we've just done a DR resume, dtick_avg
2363 				 * can go a bit askew so we reset it and carry
2364 				 * on; otherwise, the TOD is in error.
2365 				 */
2366 				if (dr_resume_done) {
2367 					dtick_avg = TOD_REF_FREQ;
2368 				} else {
2369 					/* ERROR - change in clock rate */
2370 					tod_bad = TOD_RATECHANGED;
2371 				}
2372 			}
2373 		}
2374 	}
2375 
2376 	if (tod_bad != TOD_NOFAULT) {
2377 		(void) tod_fault(tod_bad, off);
2378 
2379 		/*
2380 		 * Disable dosynctodr since we are going to fault
2381 		 * the TOD chip anyway here
2382 		 */
2383 		dosynctodr = 0;
2384 
2385 		/*
2386 		 * Set tod to the correct value from hrestime
2387 		 */
2388 		tod = hrestime.tv_sec;
2389 	}
2390 
2391 	prev_tod = tod;
2392 	prev_tick = tick;
2393 	return (tod);
2394 }
2395 
2396 static void
2397 calcloadavg(int nrun, uint64_t *hp_ave)
2398 {
2399 	static int64_t f[3] = { 135, 27, 9 };
2400 	uint_t i;
2401 	int64_t q, r;
2402 
2403 	/*
2404 	 * Compute load average over the last 1, 5, and 15 minutes
2405 	 * (60, 300, and 900 seconds).  The constants in f[3] are for
2406 	 * exponential decay:
2407 	 * (1 - exp(-1/60)) << 13 = 135,
2408 	 * (1 - exp(-1/300)) << 13 = 27,
2409 	 * (1 - exp(-1/900)) << 13 = 9.
2410 	 */
2411 
2412 	/*
2413 	 * a little hoop-jumping to avoid integer overflow
2414 	 */
2415 	for (i = 0; i < 3; i++) {
2416 		q = (hp_ave[i]  >> 16) << 7;
2417 		r = (hp_ave[i]  & 0xffff) << 7;
2418 		hp_ave[i] += ((nrun - q) * f[i] - ((r * f[i]) >> 16)) >> 4;
2419 	}
2420 }
2421 
2422 /*
2423  * lbolt_hybrid() is used by ddi_get_lbolt() and ddi_get_lbolt64() to
2424  * calculate the value of lbolt according to the current mode. In the event
2425  * driven mode (the default), lbolt is calculated by dividing the current hires
2426  * time by the number of nanoseconds per clock tick. In the cyclic driven mode
2427  * an internal variable is incremented at each firing of the lbolt cyclic
2428  * and returned by lbolt_cyclic_driven().
2429  *
2430  * The system will transition from event to cyclic driven mode when the number
2431  * of calls to lbolt_event_driven() exceeds the (per CPU) threshold within a
2432  * window of time. It does so by reprograming lbolt_cyclic from CY_INFINITY to
2433  * nsec_per_tick. The lbolt cyclic will remain ON while at least one CPU is
2434  * causing enough activity to cross the thresholds.
2435  */
2436 int64_t
2437 lbolt_bootstrap(void)
2438 {
2439 	return (0);
2440 }
2441 
2442 /* ARGSUSED */
2443 uint_t
2444 lbolt_ev_to_cyclic(caddr_t arg1, caddr_t arg2)
2445 {
2446 	hrtime_t ts, exp;
2447 	int ret;
2448 
2449 	ASSERT(lbolt_hybrid != lbolt_cyclic_driven);
2450 
2451 	kpreempt_disable();
2452 
2453 	ts = gethrtime();
2454 	lb_info->lbi_internal = (ts/nsec_per_tick);
2455 
2456 	/*
2457 	 * Align the next expiration to a clock tick boundary.
2458 	 */
2459 	exp = ts + nsec_per_tick - 1;
2460 	exp = (exp/nsec_per_tick) * nsec_per_tick;
2461 
2462 	ret = cyclic_reprogram(lb_info->id.lbi_cyclic_id, exp);
2463 	ASSERT(ret);
2464 
2465 	lbolt_hybrid = lbolt_cyclic_driven;
2466 	lb_info->lbi_cyc_deactivate = B_FALSE;
2467 	lb_info->lbi_cyc_deac_start = lb_info->lbi_internal;
2468 
2469 	kpreempt_enable();
2470 
2471 	ret = atomic_dec_32_nv(&lb_info->lbi_token);
2472 	ASSERT(ret == 0);
2473 
2474 	return (1);
2475 }
2476 
2477 int64_t
2478 lbolt_event_driven(void)
2479 {
2480 	hrtime_t ts;
2481 	int64_t lb;
2482 	int ret, cpu = CPU->cpu_seqid;
2483 
2484 	ts = gethrtime();
2485 	ASSERT(ts > 0);
2486 
2487 	ASSERT(nsec_per_tick > 0);
2488 	lb = (ts/nsec_per_tick);
2489 
2490 	/*
2491 	 * Switch to cyclic mode if the number of calls to this routine
2492 	 * has reached the threshold within the interval.
2493 	 */
2494 	if ((lb - lb_cpu[cpu].lbc_cnt_start) < lb_info->lbi_thresh_interval) {
2495 
2496 		if (--lb_cpu[cpu].lbc_counter == 0) {
2497 			/*
2498 			 * Reached the threshold within the interval, reset
2499 			 * the usage statistics.
2500 			 */
2501 			lb_cpu[cpu].lbc_counter = lb_info->lbi_thresh_calls;
2502 			lb_cpu[cpu].lbc_cnt_start = lb;
2503 
2504 			/*
2505 			 * Make sure only one thread reprograms the
2506 			 * lbolt cyclic and changes the mode.
2507 			 */
2508 			if (panicstr == NULL &&
2509 			    atomic_cas_32(&lb_info->lbi_token, 0, 1) == 0) {
2510 
2511 				if (lbolt_hybrid == lbolt_cyclic_driven) {
2512 					ret = atomic_dec_32_nv(
2513 					    &lb_info->lbi_token);
2514 					ASSERT(ret == 0);
2515 				} else {
2516 					lbolt_softint_post();
2517 				}
2518 			}
2519 		}
2520 	} else {
2521 		/*
2522 		 * Exceeded the interval, reset the usage statistics.
2523 		 */
2524 		lb_cpu[cpu].lbc_counter = lb_info->lbi_thresh_calls;
2525 		lb_cpu[cpu].lbc_cnt_start = lb;
2526 	}
2527 
2528 	ASSERT(lb >= lb_info->lbi_debug_time);
2529 
2530 	return (lb - lb_info->lbi_debug_time);
2531 }
2532 
2533 int64_t
2534 lbolt_cyclic_driven(void)
2535 {
2536 	int64_t lb = lb_info->lbi_internal;
2537 	int cpu;
2538 
2539 	/*
2540 	 * If a CPU has already prevented the lbolt cyclic from deactivating
2541 	 * itself, don't bother tracking the usage. Otherwise check if we're
2542 	 * within the interval and how the per CPU counter is doing.
2543 	 */
2544 	if (lb_info->lbi_cyc_deactivate) {
2545 		cpu = CPU->cpu_seqid;
2546 		if ((lb - lb_cpu[cpu].lbc_cnt_start) <
2547 		    lb_info->lbi_thresh_interval) {
2548 
2549 			if (lb_cpu[cpu].lbc_counter == 0)
2550 				/*
2551 				 * Reached the threshold within the interval,
2552 				 * prevent the lbolt cyclic from turning itself
2553 				 * off.
2554 				 */
2555 				lb_info->lbi_cyc_deactivate = B_FALSE;
2556 			else
2557 				lb_cpu[cpu].lbc_counter--;
2558 		} else {
2559 			/*
2560 			 * Only reset the usage statistics when we have
2561 			 * exceeded the interval.
2562 			 */
2563 			lb_cpu[cpu].lbc_counter = lb_info->lbi_thresh_calls;
2564 			lb_cpu[cpu].lbc_cnt_start = lb;
2565 		}
2566 	}
2567 
2568 	ASSERT(lb >= lb_info->lbi_debug_time);
2569 
2570 	return (lb - lb_info->lbi_debug_time);
2571 }
2572 
2573 /*
2574  * The lbolt_cyclic() routine will fire at a nsec_per_tick interval to satisfy
2575  * performance needs of ddi_get_lbolt() and ddi_get_lbolt64() consumers.
2576  * It is inactive by default, and will be activated when switching from event
2577  * to cyclic driven lbolt. The cyclic will turn itself off unless signaled
2578  * by lbolt_cyclic_driven().
2579  */
2580 static void
2581 lbolt_cyclic(void)
2582 {
2583 	int ret;
2584 
2585 	lb_info->lbi_internal++;
2586 
2587 	if (!lbolt_cyc_only) {
2588 
2589 		if (lb_info->lbi_cyc_deactivate) {
2590 			/*
2591 			 * Switching from cyclic to event driven mode.
2592 			 */
2593 			if (panicstr == NULL &&
2594 			    atomic_cas_32(&lb_info->lbi_token, 0, 1) == 0) {
2595 
2596 				if (lbolt_hybrid == lbolt_event_driven) {
2597 					ret = atomic_dec_32_nv(
2598 					    &lb_info->lbi_token);
2599 					ASSERT(ret == 0);
2600 					return;
2601 				}
2602 
2603 				kpreempt_disable();
2604 
2605 				lbolt_hybrid = lbolt_event_driven;
2606 				ret = cyclic_reprogram(
2607 				    lb_info->id.lbi_cyclic_id,
2608 				    CY_INFINITY);
2609 				ASSERT(ret);
2610 
2611 				kpreempt_enable();
2612 
2613 				ret = atomic_dec_32_nv(&lb_info->lbi_token);
2614 				ASSERT(ret == 0);
2615 			}
2616 		}
2617 
2618 		/*
2619 		 * The lbolt cyclic should not try to deactivate itself before
2620 		 * the sampling period has elapsed.
2621 		 */
2622 		if (lb_info->lbi_internal - lb_info->lbi_cyc_deac_start >=
2623 		    lb_info->lbi_thresh_interval) {
2624 			lb_info->lbi_cyc_deactivate = B_TRUE;
2625 			lb_info->lbi_cyc_deac_start = lb_info->lbi_internal;
2626 		}
2627 	}
2628 }
2629 
2630 /*
2631  * Since the lbolt service was historically cyclic driven, it must be 'stopped'
2632  * when the system drops into the kernel debugger. lbolt_debug_entry() is
2633  * called by the KDI system claim callbacks to record a hires timestamp at
2634  * debug enter time. lbolt_debug_return() is called by the sistem release
2635  * callbacks to account for the time spent in the debugger. The value is then
2636  * accumulated in the lb_info structure and used by lbolt_event_driven() and
2637  * lbolt_cyclic_driven(), as well as the mdb_get_lbolt() routine.
2638  */
2639 void
2640 lbolt_debug_entry(void)
2641 {
2642 	if (lbolt_hybrid != lbolt_bootstrap) {
2643 		ASSERT(lb_info != NULL);
2644 		lb_info->lbi_debug_ts = gethrtime();
2645 	}
2646 }
2647 
2648 /*
2649  * Calculate the time spent in the debugger and add it to the lbolt info
2650  * structure. We also update the internal lbolt value in case we were in
2651  * cyclic driven mode going in.
2652  */
2653 void
2654 lbolt_debug_return(void)
2655 {
2656 	hrtime_t ts;
2657 
2658 	if (lbolt_hybrid != lbolt_bootstrap) {
2659 		ASSERT(lb_info != NULL);
2660 		ASSERT(nsec_per_tick > 0);
2661 
2662 		ts = gethrtime();
2663 		lb_info->lbi_internal = (ts/nsec_per_tick);
2664 		lb_info->lbi_debug_time +=
2665 		    ((ts - lb_info->lbi_debug_ts)/nsec_per_tick);
2666 
2667 		lb_info->lbi_debug_ts = 0;
2668 	}
2669 }
2670