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