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