xref: /illumos-gate/usr/src/uts/i86pc/os/timestamp.c (revision ac2250cb76bb32944fd2c8a3ba2cd3f79747748d)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright 2012 Nexenta Systems, Inc. All rights reserved.
27  * Copyright (c) 2014, 2016 by Delphix. All rights reserved.
28  * Copyright 2020 Joyent, Inc.
29  * Copyright 2026 Bill Sommerfeld <sommerfeld@hamachi.org>
30  */
31 
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/disp.h>
36 #include <sys/var.h>
37 #include <sys/cmn_err.h>
38 #include <sys/debug.h>
39 #include <sys/x86_archext.h>
40 #include <sys/archsystm.h>
41 #include <sys/cpuvar.h>
42 #include <sys/psm_defs.h>
43 #include <sys/clock.h>
44 #include <sys/atomic.h>
45 #include <sys/lockstat.h>
46 #include <sys/smp_impldefs.h>
47 #include <sys/dtrace.h>
48 #include <sys/time.h>
49 #include <sys/panic.h>
50 #include <sys/cpu.h>
51 #include <sys/sdt.h>
52 #include <sys/comm_page.h>
53 #include <sys/bootconf.h>
54 #include <sys/kobj.h>
55 #include <sys/kobj_lex.h>
56 #include <sys/tsc.h>
57 #include <sys/prom_debug.h>
58 #include <util/qsort.h>
59 
60 /*
61  * Using the Pentium's TSC register for gethrtime()
62  * ------------------------------------------------
63  *
64  * The Pentium family, like many chip architectures, has a high-resolution
65  * timestamp counter ("TSC") which increments once per CPU cycle.  The contents
66  * of the timestamp counter are read with the RDTSC instruction.
67  *
68  * As with its UltraSPARC equivalent (the %tick register), TSC's cycle count
69  * must be translated into nanoseconds in order to implement gethrtime().
70  * We avoid inducing floating point operations in this conversion by
71  * implementing the same nsec_scale algorithm as that found in the sun4u
72  * platform code.  The sun4u NATIVE_TIME_TO_NSEC_SCALE block comment contains
73  * a detailed description of the algorithm; the comment is not reproduced
74  * here.  This implementation differs only in its value for NSEC_SHIFT:
75  * we implement an NSEC_SHIFT of 5 (instead of sun4u's 4) to allow for
76  * 60 MHz Pentiums.
77  *
78  * While TSC and %tick are both cycle counting registers, TSC's functionality
79  * falls short in several critical ways:
80  *
81  *  (a)	TSCs on different CPUs are not guaranteed to be in sync.  While in
82  *	practice they often _are_ in sync, this isn't guaranteed by the
83  *	architecture.
84  *
85  *  (b)	The TSC cannot be reliably set to an arbitrary value.  The architecture
86  *	only supports writing the low 32-bits of TSC, making it impractical
87  *	to rewrite.
88  *
89  *  (c)	The architecture doesn't have the capacity to interrupt based on
90  *	arbitrary values of TSC; there is no TICK_CMPR equivalent.
91  *
92  * Together, (a) and (b) imply that software must track the skew between
93  * TSCs and account for it (it is assumed that while there may exist skew,
94  * there does not exist drift).  To determine the skew between CPUs, we
95  * have newly onlined CPUs call tsc_sync_slave(), while the CPU performing
96  * the online operation calls tsc_sync_master().
97  *
98  * In the absence of time-of-day clock adjustments, gethrtime() must stay in
99  * sync with gettimeofday().  This is problematic; given (c), the software
100  * cannot drive its time-of-day source from TSC, and yet they must somehow be
101  * kept in sync.  We implement this by having a routine, tsc_tick(), which
102  * is called once per second from the interrupt which drives time-of-day.
103  *
104  * Note that the hrtime base for gethrtime, tsc_hrtime_base, is modified
105  * atomically with nsec_scale under CLOCK_LOCK.  This assures that time
106  * monotonically increases.
107  */
108 
109 #define	NSEC_SHIFT 5
110 
111 static uint_t nsec_unscale;
112 
113 /*
114  * These two variables used to be grouped together inside of a structure that
115  * lived on a single cache line. A regression (bug ID 4623398) caused the
116  * compiler to emit code that "optimized" away the while-loops below. The
117  * result was that no synchronization between the onlining and onlined CPUs
118  * took place.
119  */
120 static volatile int tsc_ready;
121 static volatile int tsc_sync_go;
122 
123 /*
124  * Used as indices into the tsc_sync_snaps[] array.
125  */
126 #define	TSC_MASTER		0
127 #define	TSC_SLAVE		1
128 
129 /*
130  * Used in the tsc_master_sync()/tsc_slave_sync() rendezvous.
131  */
132 #define	TSC_SYNC_STOP		1
133 #define	TSC_SYNC_GO		2
134 #define	TSC_SYNC_DONE		3
135 #define	SYNC_ITERATIONS		10
136 
137 #define	TSC_CONVERT_AND_ADD(tsc, hrt, scale) {		\
138 	unsigned int *_l = (unsigned int *)&(tsc);	\
139 	(hrt) += mul32(_l[1], scale) << NSEC_SHIFT;	\
140 	(hrt) += mul32(_l[0], scale) >> (32 - NSEC_SHIFT); \
141 }
142 
143 #define	TSC_CONVERT(tsc, hrt, scale) {			\
144 	unsigned int *_l = (unsigned int *)&(tsc);	\
145 	(hrt) = mul32(_l[1], scale) << NSEC_SHIFT;	\
146 	(hrt) += mul32(_l[0], scale) >> (32 - NSEC_SHIFT); \
147 }
148 
149 int tsc_master_slave_sync_needed = 1;
150 
151 typedef struct tsc_sync {
152 	volatile hrtime_t master_tsc, slave_tsc;
153 } tsc_sync_t;
154 static tsc_sync_t *tscp;
155 
156 static hrtime_t	tsc_last_jumped = 0;
157 static int	tsc_jumped = 0;
158 static uint32_t	tsc_wayback = 0;
159 /*
160  * The cap of 1 second was chosen since it is the frequency at which the
161  * tsc_tick() function runs which means that when gethrtime() is called it
162  * should never be more than 1 second since tsc_last was updated.
163  */
164 static hrtime_t tsc_resume_cap_ns = NANOSEC;	 /* 1s */
165 
166 static hrtime_t	shadow_tsc_hrtime_base;
167 static hrtime_t	shadow_tsc_last;
168 static uint_t	shadow_nsec_scale;
169 static uint32_t	shadow_hres_lock;
170 int get_tsc_ready();
171 
172 /*
173  * Allow an operator specify an explicit TSC calibration source
174  * via /etc/system e.g. `set tsc_calibration="pit"`
175  */
176 char *tsc_calibration;
177 
178 /*
179  * The source that was used to calibrate the TSC. This is currently just
180  * for diagnostic purposes.
181  */
182 static tsc_calibrate_t *tsc_calibration_source;
183 
184 /* The TSC frequency after calibration */
185 static uint64_t tsc_freq;
186 
187 static inline hrtime_t
188 tsc_protect(hrtime_t a)
189 {
190 	if (a > tsc_resume_cap) {
191 		atomic_inc_32(&tsc_wayback);
192 		DTRACE_PROBE3(tsc__wayback, htrime_t, a, hrtime_t, tsc_last,
193 		    uint32_t, tsc_wayback);
194 		return (tsc_resume_cap);
195 	}
196 	return (a);
197 }
198 
199 hrtime_t
200 tsc_gethrtime(void)
201 {
202 	uint32_t old_hres_lock;
203 	hrtime_t tsc, hrt;
204 
205 	do {
206 		old_hres_lock = hres_lock;
207 
208 		if ((tsc = tsc_read()) >= tsc_last) {
209 			/*
210 			 * It would seem to be obvious that this is true
211 			 * (that is, the past is less than the present),
212 			 * but it isn't true in the presence of suspend/resume
213 			 * cycles.  If we manage to call gethrtime()
214 			 * after a resume, but before the first call to
215 			 * tsc_tick(), we will see the jump.  In this case,
216 			 * we will simply use the value in TSC as the delta.
217 			 */
218 			tsc -= tsc_last;
219 		} else if (tsc >= tsc_last - 2*tsc_max_delta) {
220 			/*
221 			 * There is a chance that tsc_tick() has just run on
222 			 * another CPU, and we have drifted just enough so that
223 			 * we appear behind tsc_last.  In this case, force the
224 			 * delta to be zero.
225 			 */
226 			tsc = 0;
227 		} else {
228 			/*
229 			 * If we reach this else clause we assume that we have
230 			 * gone through a suspend/resume cycle and use the
231 			 * current tsc value as the delta.
232 			 *
233 			 * In rare cases we can reach this else clause due to
234 			 * a lack of monotonicity in the TSC value.  In such
235 			 * cases using the current TSC value as the delta would
236 			 * cause us to return a value ~2x of what it should
237 			 * be.  To protect against these cases we cap the
238 			 * suspend/resume delta at tsc_resume_cap.
239 			 */
240 			tsc = tsc_protect(tsc);
241 		}
242 
243 		hrt = tsc_hrtime_base;
244 
245 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
246 	} while ((old_hres_lock & ~1) != hres_lock);
247 
248 	return (hrt);
249 }
250 
251 hrtime_t
252 tsc_gethrtime_delta(void)
253 {
254 	uint32_t old_hres_lock;
255 	hrtime_t tsc, hrt;
256 	ulong_t flags;
257 
258 	do {
259 		old_hres_lock = hres_lock;
260 
261 		/*
262 		 * We need to disable interrupts here to assure that we
263 		 * don't migrate between the call to tsc_read() and
264 		 * adding the CPU's TSC tick delta. Note that disabling
265 		 * and reenabling preemption is forbidden here because
266 		 * we may be in the middle of a fast trap. In the amd64
267 		 * kernel we cannot tolerate preemption during a fast
268 		 * trap. See _update_sregs().
269 		 */
270 
271 		flags = clear_int_flag();
272 		tsc = tsc_read() + tsc_sync_tick_delta[CPU->cpu_id];
273 		restore_int_flag(flags);
274 
275 		/* See comments in tsc_gethrtime() above */
276 
277 		if (tsc >= tsc_last) {
278 			tsc -= tsc_last;
279 		} else if (tsc >= tsc_last - 2 * tsc_max_delta) {
280 			tsc = 0;
281 		} else {
282 			tsc = tsc_protect(tsc);
283 		}
284 
285 		hrt = tsc_hrtime_base;
286 
287 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
288 	} while ((old_hres_lock & ~1) != hres_lock);
289 
290 	return (hrt);
291 }
292 
293 hrtime_t
294 tsc_gethrtime_tick_delta(void)
295 {
296 	hrtime_t hrt;
297 	ulong_t flags;
298 
299 	flags = clear_int_flag();
300 	hrt = tsc_sync_tick_delta[CPU->cpu_id];
301 	restore_int_flag(flags);
302 
303 	return (hrt);
304 }
305 
306 /* Calculate the hrtime while exposing the parameters of that calculation. */
307 hrtime_t
308 tsc_gethrtime_params(uint64_t *tscp, uint32_t *scalep, uint8_t *shiftp)
309 {
310 	uint32_t old_hres_lock, scale;
311 	hrtime_t tsc, last, base;
312 
313 	do {
314 		old_hres_lock = hres_lock;
315 
316 		if (gethrtimef == tsc_gethrtime_delta) {
317 			ulong_t flags;
318 
319 			flags = clear_int_flag();
320 			tsc = tsc_read() + tsc_sync_tick_delta[CPU->cpu_id];
321 			restore_int_flag(flags);
322 		} else {
323 			tsc = tsc_read();
324 		}
325 
326 		last = tsc_last;
327 		base = tsc_hrtime_base;
328 		scale = nsec_scale;
329 
330 	} while ((old_hres_lock & ~1) != hres_lock);
331 
332 	/* See comments in tsc_gethrtime() above */
333 	if (tsc >= last) {
334 		tsc -= last;
335 	} else if (tsc >= last - 2 * tsc_max_delta) {
336 		tsc = 0;
337 	} else {
338 		tsc = tsc_protect(tsc);
339 	}
340 
341 	TSC_CONVERT_AND_ADD(tsc, base, nsec_scale);
342 
343 	if (tscp != NULL) {
344 		/*
345 		 * Do not simply communicate the delta applied to the hrtime
346 		 * base, but rather the effective TSC measurement.
347 		 */
348 		*tscp = tsc + last;
349 	}
350 	if (scalep != NULL) {
351 		*scalep = scale;
352 	}
353 	if (shiftp != NULL) {
354 		*shiftp = NSEC_SHIFT;
355 	}
356 
357 	return (base);
358 }
359 
360 /*
361  * This is similar to tsc_gethrtime_delta, but it cannot actually spin on
362  * hres_lock.  As a result, it caches all of the variables it needs; if the
363  * variables don't change, it's done.
364  */
365 hrtime_t
366 dtrace_gethrtime(void)
367 {
368 	uint32_t old_hres_lock;
369 	hrtime_t tsc, hrt;
370 	ulong_t flags;
371 
372 	do {
373 		old_hres_lock = hres_lock;
374 
375 		/*
376 		 * Interrupts are disabled to ensure that the thread isn't
377 		 * migrated between the tsc_read() and adding the CPU's
378 		 * TSC tick delta.
379 		 */
380 		flags = clear_int_flag();
381 
382 		tsc = tsc_read();
383 
384 		if (gethrtimef == tsc_gethrtime_delta)
385 			tsc += tsc_sync_tick_delta[CPU->cpu_id];
386 
387 		restore_int_flag(flags);
388 
389 		/*
390 		 * See the comments in tsc_gethrtime(), above.
391 		 */
392 		if (tsc >= tsc_last)
393 			tsc -= tsc_last;
394 		else if (tsc >= tsc_last - 2*tsc_max_delta)
395 			tsc = 0;
396 		else
397 			tsc = tsc_protect(tsc);
398 
399 		hrt = tsc_hrtime_base;
400 
401 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
402 
403 		if ((old_hres_lock & ~1) == hres_lock)
404 			break;
405 
406 		/*
407 		 * If we're here, the clock lock is locked -- or it has been
408 		 * unlocked and locked since we looked.  This may be due to
409 		 * tsc_tick() running on another CPU -- or it may be because
410 		 * some code path has ended up in dtrace_probe() with
411 		 * CLOCK_LOCK held.  We'll try to determine that we're in
412 		 * the former case by taking another lap if the lock has
413 		 * changed since when we first looked at it.
414 		 */
415 		if (old_hres_lock != hres_lock)
416 			continue;
417 
418 		/*
419 		 * So the lock was and is locked.  We'll use the old data
420 		 * instead.
421 		 */
422 		old_hres_lock = shadow_hres_lock;
423 
424 		/*
425 		 * Again, disable interrupts to ensure that the thread
426 		 * isn't migrated between the tsc_read() and adding
427 		 * the CPU's TSC tick delta.
428 		 */
429 		flags = clear_int_flag();
430 
431 		tsc = tsc_read();
432 
433 		if (gethrtimef == tsc_gethrtime_delta)
434 			tsc += tsc_sync_tick_delta[CPU->cpu_id];
435 
436 		restore_int_flag(flags);
437 
438 		/*
439 		 * See the comments in tsc_gethrtime(), above.
440 		 */
441 		if (tsc >= shadow_tsc_last)
442 			tsc -= shadow_tsc_last;
443 		else if (tsc >= shadow_tsc_last - 2 * tsc_max_delta)
444 			tsc = 0;
445 		else
446 			tsc = tsc_protect(tsc);
447 
448 		hrt = shadow_tsc_hrtime_base;
449 
450 		TSC_CONVERT_AND_ADD(tsc, hrt, shadow_nsec_scale);
451 	} while ((old_hres_lock & ~1) != shadow_hres_lock);
452 
453 	return (hrt);
454 }
455 
456 hrtime_t
457 tsc_gethrtimeunscaled(void)
458 {
459 	uint32_t old_hres_lock;
460 	hrtime_t tsc;
461 
462 	do {
463 		old_hres_lock = hres_lock;
464 
465 		/* See tsc_tick(). */
466 		tsc = tsc_read() + tsc_last_jumped;
467 	} while ((old_hres_lock & ~1) != hres_lock);
468 
469 	return (tsc);
470 }
471 
472 /*
473  * Convert a nanosecond based timestamp to tsc
474  */
475 uint64_t
476 tsc_unscalehrtime(hrtime_t nsec)
477 {
478 	hrtime_t tsc;
479 
480 	if (tsc_gethrtime_enable) {
481 		TSC_CONVERT(nsec, tsc, nsec_unscale);
482 		return (tsc);
483 	}
484 	return ((uint64_t)nsec);
485 }
486 
487 /* Convert a tsc timestamp to nanoseconds */
488 void
489 tsc_scalehrtime(hrtime_t *tsc)
490 {
491 	hrtime_t hrt;
492 	hrtime_t mytsc;
493 
494 	if (tsc == NULL)
495 		return;
496 	mytsc = *tsc;
497 
498 	TSC_CONVERT(mytsc, hrt, nsec_scale);
499 	*tsc  = hrt;
500 }
501 
502 hrtime_t
503 tsc_gethrtimeunscaled_delta(void)
504 {
505 	hrtime_t hrt;
506 	ulong_t flags;
507 
508 	/*
509 	 * Similarly to tsc_gethrtime_delta, we need to disable preemption
510 	 * to prevent migration between the call to tsc_gethrtimeunscaled
511 	 * and adding the CPU's hrtime delta. Note that disabling and
512 	 * reenabling preemption is forbidden here because we may be in the
513 	 * middle of a fast trap. In the amd64 kernel we cannot tolerate
514 	 * preemption during a fast trap. See _update_sregs().
515 	 */
516 
517 	flags = clear_int_flag();
518 	hrt = tsc_gethrtimeunscaled() + tsc_sync_tick_delta[CPU->cpu_id];
519 	restore_int_flag(flags);
520 
521 	return (hrt);
522 }
523 
524 /*
525  * TSC Sync Master
526  *
527  * Typically called on the boot CPU, this attempts to quantify TSC skew between
528  * different CPUs.  If an appreciable difference is found, gethrtimef will be
529  * changed to point to tsc_gethrtime_delta().
530  *
531  * Calculating skews is precise only when the master and slave TSCs are read
532  * simultaneously; however, there is no algorithm that can read both CPUs in
533  * perfect simultaneity.  The proposed algorithm is an approximate method based
534  * on the behaviour of cache management.  The slave CPU continuously polls the
535  * TSC while reading a global variable updated by the master CPU.  The latest
536  * TSC reading is saved when the master's update (forced via mfence) reaches
537  * visibility on the slave.  The master will also take a TSC reading
538  * immediately following the mfence.
539  *
540  * While the delay between cache line invalidation on the slave and mfence
541  * completion on the master is not repeatable, the error is heuristically
542  * assumed to be 1/4th of the write time recorded by the master.  Multiple
543  * samples are taken to control for the variance caused by external factors
544  * such as bus contention.  Each sample set is independent per-CPU to control
545  * for differing memory latency on NUMA systems.
546  *
547  * TSC sync is disabled in the context of virtualization because the CPUs
548  * assigned to the guest are virtual CPUs which means the real CPUs on which
549  * guest runs keep changing during life time of guest OS. So we would end up
550  * calculating TSC skews for a set of CPUs during boot whereas the guest
551  * might migrate to a different set of physical CPUs at a later point of
552  * time.
553  */
554 void
555 tsc_sync_master(processorid_t slave)
556 {
557 	ulong_t flags, source, min_write_time = ~0UL;
558 	hrtime_t write_time, mtsc_after, last_delta = 0;
559 	tsc_sync_t *tsc = tscp;
560 	int cnt;
561 	int hwtype;
562 
563 	hwtype = get_hwenv();
564 	if (!tsc_master_slave_sync_needed || (hwtype & HW_VIRTUAL) != 0)
565 		return;
566 
567 	flags = clear_int_flag();
568 	source = CPU->cpu_id;
569 
570 	for (cnt = 0; cnt < SYNC_ITERATIONS; cnt++) {
571 		while (tsc_sync_go != TSC_SYNC_GO)
572 			SMT_PAUSE();
573 
574 		tsc->master_tsc = tsc_read();
575 		membar_enter();
576 		mtsc_after = tsc_read();
577 		while (tsc_sync_go != TSC_SYNC_DONE)
578 			SMT_PAUSE();
579 		write_time =  mtsc_after - tsc->master_tsc;
580 		if (write_time <= min_write_time) {
581 			hrtime_t tdelta;
582 
583 			tdelta = tsc->slave_tsc - mtsc_after;
584 			if (tdelta < 0)
585 				tdelta = -tdelta;
586 			/*
587 			 * If the margin exists, subtract 1/4th of the measured
588 			 * write time from the master's TSC value.  This is an
589 			 * estimate of how late the mfence completion came
590 			 * after the slave noticed the cache line change.
591 			 */
592 			if (tdelta > (write_time/4)) {
593 				tdelta = tsc->slave_tsc -
594 				    (mtsc_after - (write_time/4));
595 			} else {
596 				tdelta = tsc->slave_tsc - mtsc_after;
597 			}
598 			last_delta = tsc_sync_tick_delta[source] - tdelta;
599 			tsc_sync_tick_delta[slave] = last_delta;
600 			min_write_time = write_time;
601 		}
602 
603 		tsc->master_tsc = tsc->slave_tsc = write_time = 0;
604 		membar_enter();
605 		tsc_sync_go = TSC_SYNC_STOP;
606 	}
607 
608 	/*
609 	 * Only enable the delta variants of the TSC functions if the measured
610 	 * skew is greater than the fastest write time.
611 	 */
612 	last_delta = (last_delta < 0) ? -last_delta : last_delta;
613 	if (last_delta > min_write_time) {
614 		gethrtimef = tsc_gethrtime_delta;
615 		gethrtimeunscaledf = tsc_gethrtimeunscaled_delta;
616 		tsc_ncpu = NCPU;
617 	}
618 	restore_int_flag(flags);
619 }
620 
621 /*
622  * TSC Sync Slave
623  *
624  * Called by a CPU which has just been onlined.  It is expected that the CPU
625  * performing the online operation will call tsc_sync_master().
626  *
627  * Like tsc_sync_master, this logic is skipped on virtualized platforms.
628  */
629 void
630 tsc_sync_slave(void)
631 {
632 	ulong_t flags;
633 	hrtime_t s1;
634 	tsc_sync_t *tsc = tscp;
635 	int cnt;
636 	int hwtype;
637 
638 	hwtype = get_hwenv();
639 	if (!tsc_master_slave_sync_needed || (hwtype & HW_VIRTUAL) != 0)
640 		return;
641 
642 	flags = clear_int_flag();
643 
644 	for (cnt = 0; cnt < SYNC_ITERATIONS; cnt++) {
645 		/* Re-fill the cache line */
646 		s1 = tsc->master_tsc;
647 		membar_enter();
648 		tsc_sync_go = TSC_SYNC_GO;
649 		do {
650 			/*
651 			 * Do not put an SMT_PAUSE here.  If the master and
652 			 * slave are the same hyper-threaded CPU, we want the
653 			 * master to yield as quickly as possible to the slave.
654 			 */
655 			s1 = tsc_read();
656 		} while (tsc->master_tsc == 0);
657 		tsc->slave_tsc = s1;
658 		membar_enter();
659 		tsc_sync_go = TSC_SYNC_DONE;
660 
661 		while (tsc_sync_go != TSC_SYNC_STOP)
662 			SMT_PAUSE();
663 	}
664 
665 	restore_int_flag(flags);
666 }
667 
668 /*
669  * Called once per second on a CPU from the cyclic subsystem's
670  * CY_HIGH_LEVEL interrupt.  (No longer just cpu0-only)
671  */
672 void
673 tsc_tick(void)
674 {
675 	hrtime_t now, delta;
676 	ushort_t spl;
677 
678 	/*
679 	 * Before we set the new variables, we set the shadow values.  This
680 	 * allows for lock free operation in dtrace_gethrtime().
681 	 */
682 	lock_set_spl((lock_t *)&shadow_hres_lock + HRES_LOCK_OFFSET,
683 	    ipltospl(CBE_HIGH_PIL), &spl);
684 
685 	shadow_tsc_hrtime_base = tsc_hrtime_base;
686 	shadow_tsc_last = tsc_last;
687 	shadow_nsec_scale = nsec_scale;
688 
689 	shadow_hres_lock++;
690 	splx(spl);
691 
692 	CLOCK_LOCK(&spl);
693 
694 	now = tsc_read();
695 
696 	if (gethrtimef == tsc_gethrtime_delta)
697 		now += tsc_sync_tick_delta[CPU->cpu_id];
698 
699 	if (now < tsc_last) {
700 		/*
701 		 * The TSC has just jumped into the past.  We assume that
702 		 * this is due to a suspend/resume cycle, and we're going
703 		 * to use the _current_ value of TSC as the delta.  This
704 		 * will keep tsc_hrtime_base correct.  We're also going to
705 		 * assume that rate of tsc does not change after a suspend
706 		 * resume (i.e nsec_scale remains the same).
707 		 */
708 		delta = now;
709 		delta = tsc_protect(delta);
710 		tsc_last_jumped += tsc_last;
711 		tsc_jumped = 1;
712 	} else {
713 		/*
714 		 * Determine the number of TSC ticks since the last clock
715 		 * tick, and add that to the hrtime base.
716 		 */
717 		delta = now - tsc_last;
718 	}
719 
720 	TSC_CONVERT_AND_ADD(delta, tsc_hrtime_base, nsec_scale);
721 	tsc_last = now;
722 
723 	CLOCK_UNLOCK(spl);
724 }
725 
726 void
727 tsc_hrtimeinit(uint64_t cpu_freq_hz)
728 {
729 	extern int gethrtime_hires;
730 	longlong_t tsc;
731 	ulong_t flags;
732 
733 	/*
734 	 * cpu_freq_hz is the measured cpu frequency in hertz
735 	 */
736 
737 	/*
738 	 * We can't accommodate CPUs slower than 31.25 MHz.
739 	 */
740 	ASSERT(cpu_freq_hz > NANOSEC / (1 << NSEC_SHIFT));
741 	nsec_scale =
742 	    (uint_t)(((uint64_t)NANOSEC << (32 - NSEC_SHIFT)) / cpu_freq_hz);
743 	nsec_unscale =
744 	    (uint_t)(((uint64_t)cpu_freq_hz << (32 - NSEC_SHIFT)) / NANOSEC);
745 
746 	flags = clear_int_flag();
747 	tsc = tsc_read();
748 	(void) tsc_gethrtime();
749 	tsc_max_delta = tsc_read() - tsc;
750 	restore_int_flag(flags);
751 	gethrtimef = tsc_gethrtime;
752 	gethrtimeunscaledf = tsc_gethrtimeunscaled;
753 	scalehrtimef = tsc_scalehrtime;
754 	unscalehrtimef = tsc_unscalehrtime;
755 	hrtime_tick = tsc_tick;
756 	gethrtime_hires = 1;
757 	/*
758 	 * Being part of the comm page, tsc_ncpu communicates the published
759 	 * length of the tsc_sync_tick_delta array.  This is kept zeroed to
760 	 * ignore the absent delta data while the TSCs are synced.
761 	 */
762 	tsc_ncpu = 0;
763 	/*
764 	 * Allocate memory for the structure used in the tsc sync logic.
765 	 * This structure should be aligned on a multiple of cache line size.
766 	 */
767 	tscp = kmem_zalloc(PAGESIZE, KM_SLEEP);
768 
769 	/*
770 	 * Convert the TSC resume cap ns value into its unscaled TSC value.
771 	 * See tsc_gethrtime().
772 	 */
773 	if (tsc_resume_cap == 0)
774 		TSC_CONVERT(tsc_resume_cap_ns, tsc_resume_cap, nsec_unscale);
775 }
776 
777 int
778 get_tsc_ready()
779 {
780 	return (tsc_ready);
781 }
782 
783 /*
784  * Adjust all the deltas by adding the passed value to the array and activate
785  * the "delta" versions of the gethrtime functions.  It is possible that the
786  * adjustment could be negative.  Such may occur if the SunOS instance was
787  * moved by a virtual manager to a machine with a higher value of TSC.
788  */
789 void
790 tsc_adjust_delta(hrtime_t tdelta)
791 {
792 	int		i;
793 
794 	for (i = 0; i < NCPU; i++) {
795 		tsc_sync_tick_delta[i] += tdelta;
796 	}
797 
798 	gethrtimef = tsc_gethrtime_delta;
799 	gethrtimeunscaledf = tsc_gethrtimeunscaled_delta;
800 	tsc_ncpu = NCPU;
801 }
802 
803 /*
804  * Functions to manage TSC and high-res time on suspend and resume.
805  */
806 
807 /* tod_ops from "uts/i86pc/io/todpc_subr.c" */
808 extern tod_ops_t *tod_ops;
809 
810 static uint64_t tsc_saved_tsc = 0; /* 1 in 2^64 chance this'll screw up! */
811 static timestruc_t tsc_saved_ts;
812 static int	tsc_needs_resume = 0;	/* We only want to do this once. */
813 int		tsc_delta_onsuspend = 0;
814 int		tsc_adjust_seconds = 1;
815 int		tsc_suspend_count = 0;
816 int		tsc_resume_in_cyclic = 0;
817 
818 /*
819  * Take snapshots of the current time and do any other pre-suspend work.
820  */
821 void
822 tsc_suspend(void)
823 {
824 	/*
825 	 * We need to collect the time at which we suspended here so we know
826 	 * now much should be added during the resume.  This is called by each
827 	 * CPU, so reentry must be properly handled.
828 	 */
829 	if (tsc_gethrtime_enable) {
830 		/*
831 		 * Perform the tsc_read after acquiring the lock to make it as
832 		 * accurate as possible in the face of contention.
833 		 */
834 		mutex_enter(&tod_lock);
835 		tsc_saved_tsc = tsc_read();
836 		tsc_saved_ts = TODOP_GET(tod_ops);
837 		mutex_exit(&tod_lock);
838 		/* We only want to do this once. */
839 		if (tsc_needs_resume == 0) {
840 			if (tsc_delta_onsuspend) {
841 				tsc_adjust_delta(tsc_saved_tsc);
842 			} else {
843 				tsc_adjust_delta(nsec_scale);
844 			}
845 			tsc_suspend_count++;
846 		}
847 	}
848 
849 	invalidate_cache();
850 	tsc_needs_resume = 1;
851 }
852 
853 /*
854  * Restore all timestamp state based on the snapshots taken at suspend time.
855  */
856 void
857 tsc_resume(void)
858 {
859 	/*
860 	 * We only need to (and want to) do this once.  So let the first
861 	 * caller handle this (we are locked by the cpu lock), as it
862 	 * is preferential that we get the earliest sync.
863 	 */
864 	if (tsc_needs_resume) {
865 		/*
866 		 * If using the TSC, adjust the delta based on how long
867 		 * we were sleeping (or away).  We also adjust for
868 		 * migration and a grown TSC.
869 		 */
870 		if (tsc_saved_tsc != 0) {
871 			timestruc_t	ts;
872 			hrtime_t	now, sleep_tsc = 0;
873 			int		sleep_sec;
874 			extern void	tsc_tick(void);
875 			extern uint64_t cpu_freq_hz;
876 
877 			/* tsc_read() MUST be before TODOP_GET() */
878 			mutex_enter(&tod_lock);
879 			now = tsc_read();
880 			ts = TODOP_GET(tod_ops);
881 			mutex_exit(&tod_lock);
882 
883 			/* Compute seconds of sleep time */
884 			sleep_sec = ts.tv_sec - tsc_saved_ts.tv_sec;
885 
886 			/*
887 			 * If the saved sec is less that or equal to
888 			 * the current ts, then there is likely a
889 			 * problem with the clock.  Assume at least
890 			 * one second has passed, so that time goes forward.
891 			 */
892 			if (sleep_sec <= 0) {
893 				sleep_sec = 1;
894 			}
895 
896 			/* How many TSC's should have occured while sleeping */
897 			if (tsc_adjust_seconds)
898 				sleep_tsc = sleep_sec * cpu_freq_hz;
899 
900 			/*
901 			 * We also want to subtract from the "sleep_tsc"
902 			 * the current value of tsc_read(), so that our
903 			 * adjustment accounts for the amount of time we
904 			 * have been resumed _or_ an adjustment based on
905 			 * the fact that we didn't actually power off the
906 			 * CPU (migration is another issue, but _should_
907 			 * also comply with this calculation).  If the CPU
908 			 * never powered off, then:
909 			 *    'now == sleep_tsc + saved_tsc'
910 			 * and the delta will effectively be "0".
911 			 */
912 			sleep_tsc -= now;
913 			if (tsc_delta_onsuspend) {
914 				tsc_adjust_delta(sleep_tsc);
915 			} else {
916 				tsc_adjust_delta(tsc_saved_tsc + sleep_tsc);
917 			}
918 			tsc_saved_tsc = 0;
919 
920 			tsc_tick();
921 		}
922 		tsc_needs_resume = 0;
923 	}
924 
925 }
926 
927 static int
928 tsc_calibrate_cmp(const void *a, const void *b)
929 {
930 	const tsc_calibrate_t * const *a1 = a;
931 	const tsc_calibrate_t * const *b1 = b;
932 	const tsc_calibrate_t *l = *a1;
933 	const tsc_calibrate_t *r = *b1;
934 
935 	/* Sort from highest preference to lowest preference */
936 	if (l->tscc_preference > r->tscc_preference)
937 		return (-1);
938 	if (l->tscc_preference < r->tscc_preference)
939 		return (1);
940 
941 	/* For equal preference sources, sort alphabetically */
942 	int c = strcmp(l->tscc_source, r->tscc_source);
943 
944 	if (c < 0)
945 		return (-1);
946 	if (c > 0)
947 		return (1);
948 	return (0);
949 }
950 
951 SET_DECLARE(tsc_calibration_set, tsc_calibrate_t);
952 
953 static tsc_calibrate_t *
954 tsc_calibrate_get_force(const char *source)
955 {
956 	tsc_calibrate_t **tsccpp;
957 
958 	VERIFY3P(source, !=, NULL);
959 
960 	SET_FOREACH(tsccpp, tsc_calibration_set) {
961 		tsc_calibrate_t *tsccp = *tsccpp;
962 
963 		if (strcasecmp(source, tsccp->tscc_source) == 0)
964 			return (tsccp);
965 	}
966 
967 	/*
968 	 * If an operator explicitly gave a TSC value and we didn't find it,
969 	 * we should let them know.
970 	 */
971 	cmn_err(CE_NOTE,
972 	    "Explicit TSC calibration source '%s' not found; using default",
973 	    source);
974 
975 	return (NULL);
976 }
977 
978 /*
979  * As described in tscc_pit.c, as an intertim measure as we transition to
980  * alternate calibration sources besides the PIT, we still want to gather
981  * what the values would have been had we used the PIT. Therefore, if we're
982  * using a source other than the PIT, we explicitly run the PIT calibration
983  * which will store the TSC frequency as measured by the PIT for the
984  * benefit of the APIC code (as well as any potential diagnostics).
985  */
986 static void
987 tsc_pit_also(void)
988 {
989 	tsc_calibrate_t *pit = tsc_calibrate_get_force("PIT");
990 	uint64_t dummy;
991 
992 	/* We should always have the PIT as a possible calibration source */
993 	VERIFY3P(pit, !=, NULL);
994 
995 	/* If we used the PIT to calibrate, we don't need to run again */
996 	if (tsc_calibration_source == pit)
997 		return;
998 
999 	/*
1000 	 * Since we're not using the PIT as the actual TSC calibration source,
1001 	 * we don't care about the results or saving the result -- tscc_pit.c
1002 	 * saves the frequency in a global for the benefit of the APIC code.
1003 	 */
1004 	(void) pit->tscc_calibrate(&dummy);
1005 }
1006 
1007 uint64_t
1008 tsc_calibrate(void)
1009 {
1010 	tsc_calibrate_t **tsccpp, *force;
1011 	size_t tsc_set_size;
1012 	int tsc_name_len;
1013 
1014 	/*
1015 	 * Every x86 system since the Pentium has TSC support. Since we
1016 	 * only support 64-bit x86 systems, there should always be a TSC
1017 	 * present, and something's horribly wrong if it's missing.
1018 	 */
1019 	if (!is_x86_feature(x86_featureset, X86FSET_TSC))
1020 		panic("System does not have TSC support");
1021 
1022 	/*
1023 	 * If we already successfully calibrated the TSC, no need to do
1024 	 * it again.
1025 	 */
1026 	if (tsc_freq > 0)
1027 		return (tsc_freq);
1028 
1029 	PRM_POINT("Calibrating the TSC...");
1030 
1031 	/*
1032 	 * Allow an operator to explicitly specify a calibration source via
1033 	 * `set tsc_calibration=foo` in the bootloader or
1034 	 * `set tsc_calibration="foo"` in /etc/system (preferring a bootloader
1035 	 * supplied value over /etc/system).
1036 	 *
1037 	 * If no source is given, or the specified source is not found, we
1038 	 * fallback to trying all of the known sources in order by preference
1039 	 * (high preference value to low preference value) until one succeeds.
1040 	 */
1041 	tsc_name_len = BOP_GETPROPLEN(bootops, "tsc_calibration");
1042 	if (tsc_name_len > 0) {
1043 		/* Overwrite any /etc/system supplied value */
1044 		if (tsc_calibration != NULL) {
1045 			size_t len = strlen(tsc_calibration) + 1;
1046 
1047 			kobj_free_string(tsc_calibration, len);
1048 		}
1049 
1050 		tsc_calibration = kmem_zalloc(tsc_name_len + 1, KM_SLEEP);
1051 		BOP_GETPROP(bootops, "tsc_calibration", tsc_calibration);
1052 	}
1053 
1054 	if (tsc_calibration != NULL &&
1055 	    (force = tsc_calibrate_get_force(tsc_calibration)) != NULL) {
1056 		if (tsc_name_len > 0) {
1057 			PRM_POINT("Forcing bootloader specified TSC calibration"
1058 			    " source");
1059 		} else {
1060 			PRM_POINT("Forcing /etc/system specified TSC "
1061 			    "calibration source");
1062 		}
1063 		PRM_DEBUGS(force->tscc_source);
1064 
1065 		if (!force->tscc_calibrate(&tsc_freq))
1066 			panic("Failed to calibrate the TSC");
1067 
1068 		tsc_calibration_source = force;
1069 
1070 		/*
1071 		 * We've saved the tsc_calibration_t that matched the value
1072 		 * of tsc_calibration at this point, so we can release the
1073 		 * memory for the value now.
1074 		 */
1075 		if (tsc_name_len > 0) {
1076 			kmem_free(tsc_calibration, tsc_name_len + 1);
1077 		} else if (tsc_calibration != NULL) {
1078 			size_t len = strlen(tsc_calibration) + 1;
1079 
1080 			kobj_free_string(tsc_calibration, len);
1081 		}
1082 		tsc_calibration = NULL;
1083 
1084 		tsc_pit_also();
1085 		return (tsc_freq);
1086 	}
1087 
1088 	/*
1089 	 * While we could sort the set contents in place, we'll make a copy
1090 	 * of the set and avoid modifying the original set.
1091 	 */
1092 	tsc_set_size = SET_COUNT(tsc_calibration_set) *
1093 	    sizeof (tsc_calibrate_t **);
1094 	tsccpp = kmem_zalloc(tsc_set_size, KM_SLEEP);
1095 	bcopy(SET_BEGIN(tsc_calibration_set), tsccpp, tsc_set_size);
1096 
1097 	/*
1098 	 * Sort by preference, highest to lowest
1099 	 */
1100 	qsort(tsccpp, SET_COUNT(tsc_calibration_set),
1101 	    sizeof (tsc_calibrate_t **), tsc_calibrate_cmp);
1102 
1103 	for (uint_t i = 0; i < SET_COUNT(tsc_calibration_set); i++) {
1104 		PRM_DEBUGS(tsccpp[i]->tscc_source);
1105 		if (tsccpp[i]->tscc_calibrate(&tsc_freq)) {
1106 			VERIFY3U(tsc_freq, >, 0);
1107 
1108 			cmn_err(CE_CONT,
1109 			    "?TSC calibrated using %s; freq is %lu Hz\n",
1110 			    tsccpp[i]->tscc_source, tsc_freq);
1111 
1112 			/*
1113 			 * Note that tsccpp is just a (sorted) array of
1114 			 * pointers to the tsc_calibration_t's (from the
1115 			 * linker set). The actual tsc_calibration_t's aren't
1116 			 * kmem_alloc()ed (being part of the linker set), so
1117 			 * it's safe to keep a pointer to the one that was
1118 			 * used for calibration (intended for diagnostic
1119 			 * purposes).
1120 			 */
1121 			tsc_calibration_source = tsccpp[i];
1122 
1123 			kmem_free(tsccpp, tsc_set_size);
1124 			tsc_pit_also();
1125 			return (tsc_freq);
1126 		}
1127 	}
1128 
1129 	/*
1130 	 * In case it's useful, we don't free tsccpp -- we're about to panic
1131 	 * anyway.
1132 	 */
1133 	panic("Failed to calibrate TSC");
1134 }
1135 
1136 uint64_t
1137 tsc_get_freq(void)
1138 {
1139 	VERIFY(tsc_freq > 0);
1140 	return (tsc_freq);
1141 }
1142