xref: /titanic_51/usr/src/uts/i86pc/os/timestamp.c (revision fe54a78e1aacf39261ad56e9903bce02e3fb6d21)
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 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/disp.h>
31 #include <sys/var.h>
32 #include <sys/cmn_err.h>
33 #include <sys/debug.h>
34 #include <sys/x86_archext.h>
35 #include <sys/archsystm.h>
36 #include <sys/cpuvar.h>
37 #include <sys/psm_defs.h>
38 #include <sys/clock.h>
39 #include <sys/atomic.h>
40 #include <sys/lockstat.h>
41 #include <sys/smp_impldefs.h>
42 #include <sys/dtrace.h>
43 #include <sys/time.h>
44 #include <sys/panic.h>
45 #include <sys/cpu.h>
46 
47 /*
48  * Using the Pentium's TSC register for gethrtime()
49  * ------------------------------------------------
50  *
51  * The Pentium family, like many chip architectures, has a high-resolution
52  * timestamp counter ("TSC") which increments once per CPU cycle.  The contents
53  * of the timestamp counter are read with the RDTSC instruction.
54  *
55  * As with its UltraSPARC equivalent (the %tick register), TSC's cycle count
56  * must be translated into nanoseconds in order to implement gethrtime().
57  * We avoid inducing floating point operations in this conversion by
58  * implementing the same nsec_scale algorithm as that found in the sun4u
59  * platform code.  The sun4u NATIVE_TIME_TO_NSEC_SCALE block comment contains
60  * a detailed description of the algorithm; the comment is not reproduced
61  * here.  This implementation differs only in its value for NSEC_SHIFT:
62  * we implement an NSEC_SHIFT of 5 (instead of sun4u's 4) to allow for
63  * 60 MHz Pentiums.
64  *
65  * While TSC and %tick are both cycle counting registers, TSC's functionality
66  * falls short in several critical ways:
67  *
68  *  (a)	TSCs on different CPUs are not guaranteed to be in sync.  While in
69  *	practice they often _are_ in sync, this isn't guaranteed by the
70  *	architecture.
71  *
72  *  (b)	The TSC cannot be reliably set to an arbitrary value.  The architecture
73  *	only supports writing the low 32-bits of TSC, making it impractical
74  *	to rewrite.
75  *
76  *  (c)	The architecture doesn't have the capacity to interrupt based on
77  *	arbitrary values of TSC; there is no TICK_CMPR equivalent.
78  *
79  * Together, (a) and (b) imply that software must track the skew between
80  * TSCs and account for it (it is assumed that while there may exist skew,
81  * there does not exist drift).  To determine the skew between CPUs, we
82  * have newly onlined CPUs call tsc_sync_slave(), while the CPU performing
83  * the online operation calls tsc_sync_master().
84  *
85  * In the absence of time-of-day clock adjustments, gethrtime() must stay in
86  * sync with gettimeofday().  This is problematic; given (c), the software
87  * cannot drive its time-of-day source from TSC, and yet they must somehow be
88  * kept in sync.  We implement this by having a routine, tsc_tick(), which
89  * is called once per second from the interrupt which drives time-of-day.
90  *
91  * Note that the hrtime base for gethrtime, tsc_hrtime_base, is modified
92  * atomically with nsec_scale under CLOCK_LOCK.  This assures that time
93  * monotonically increases.
94  */
95 
96 #define	NSEC_SHIFT 5
97 
98 static uint_t nsec_scale;
99 
100 /*
101  * These two variables used to be grouped together inside of a structure that
102  * lived on a single cache line. A regression (bug ID 4623398) caused the
103  * compiler to emit code that "optimized" away the while-loops below. The
104  * result was that no synchronization between the onlining and onlined CPUs
105  * took place.
106  */
107 static volatile int tsc_ready;
108 static volatile int tsc_sync_go;
109 
110 /*
111  * Used as indices into the tsc_sync_snaps[] array.
112  */
113 #define	TSC_MASTER		0
114 #define	TSC_SLAVE		1
115 
116 /*
117  * Used in the tsc_master_sync()/tsc_slave_sync() rendezvous.
118  */
119 #define	TSC_SYNC_STOP		1
120 #define	TSC_SYNC_GO		2
121 #define	TSC_SYNC_DONE		3
122 #define	SYNC_ITERATIONS		10
123 
124 #define	TSC_CONVERT_AND_ADD(tsc, hrt, scale) {	 	\
125 	unsigned int *_l = (unsigned int *)&(tsc); 	\
126 	(hrt) += mul32(_l[1], scale) << NSEC_SHIFT; 	\
127 	(hrt) += mul32(_l[0], scale) >> (32 - NSEC_SHIFT); \
128 }
129 
130 #define	TSC_CONVERT(tsc, hrt, scale) { 			\
131 	unsigned int *_l = (unsigned int *)&(tsc); 	\
132 	(hrt) = mul32(_l[1], scale) << NSEC_SHIFT; 	\
133 	(hrt) += mul32(_l[0], scale) >> (32 - NSEC_SHIFT); \
134 }
135 
136 int tsc_master_slave_sync_needed = 1;
137 
138 static int	tsc_max_delta;
139 static hrtime_t tsc_sync_tick_delta[NCPU];
140 typedef struct tsc_sync {
141 	volatile hrtime_t master_tsc, slave_tsc;
142 } tsc_sync_t;
143 static tsc_sync_t *tscp;
144 static hrtime_t largest_tsc_delta = 0;
145 static ulong_t shortest_write_time = ~0UL;
146 
147 static hrtime_t	tsc_last = 0;
148 static hrtime_t	tsc_last_jumped = 0;
149 static hrtime_t	tsc_hrtime_base = 0;
150 static int	tsc_jumped = 0;
151 
152 static hrtime_t	shadow_tsc_hrtime_base;
153 static hrtime_t	shadow_tsc_last;
154 static uint_t	shadow_nsec_scale;
155 static uint32_t	shadow_hres_lock;
156 int get_tsc_ready();
157 
158 hrtime_t
159 tsc_gethrtime(void)
160 {
161 	uint32_t old_hres_lock;
162 	hrtime_t tsc, hrt;
163 
164 	do {
165 		old_hres_lock = hres_lock;
166 
167 		if ((tsc = tsc_read()) >= tsc_last) {
168 			/*
169 			 * It would seem to be obvious that this is true
170 			 * (that is, the past is less than the present),
171 			 * but it isn't true in the presence of suspend/resume
172 			 * cycles.  If we manage to call gethrtime()
173 			 * after a resume, but before the first call to
174 			 * tsc_tick(), we will see the jump.  In this case,
175 			 * we will simply use the value in TSC as the delta.
176 			 */
177 			tsc -= tsc_last;
178 		} else if (tsc >= tsc_last - 2*tsc_max_delta) {
179 			/*
180 			 * There is a chance that tsc_tick() has just run on
181 			 * another CPU, and we have drifted just enough so that
182 			 * we appear behind tsc_last.  In this case, force the
183 			 * delta to be zero.
184 			 */
185 			tsc = 0;
186 		}
187 
188 		hrt = tsc_hrtime_base;
189 
190 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
191 	} while ((old_hres_lock & ~1) != hres_lock);
192 
193 	return (hrt);
194 }
195 
196 hrtime_t
197 tsc_gethrtime_delta(void)
198 {
199 	uint32_t old_hres_lock;
200 	hrtime_t tsc, hrt;
201 	ulong_t flags;
202 
203 	do {
204 		old_hres_lock = hres_lock;
205 
206 		/*
207 		 * We need to disable interrupts here to assure that we
208 		 * don't migrate between the call to tsc_read() and
209 		 * adding the CPU's TSC tick delta. Note that disabling
210 		 * and reenabling preemption is forbidden here because
211 		 * we may be in the middle of a fast trap. In the amd64
212 		 * kernel we cannot tolerate preemption during a fast
213 		 * trap. See _update_sregs().
214 		 */
215 
216 		flags = clear_int_flag();
217 		tsc = tsc_read() + tsc_sync_tick_delta[CPU->cpu_id];
218 		restore_int_flag(flags);
219 
220 		/* See comments in tsc_gethrtime() above */
221 
222 		if (tsc >= tsc_last) {
223 			tsc -= tsc_last;
224 		} else if (tsc >= tsc_last - 2 * tsc_max_delta) {
225 			tsc = 0;
226 		}
227 
228 		hrt = tsc_hrtime_base;
229 
230 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
231 	} while ((old_hres_lock & ~1) != hres_lock);
232 
233 	return (hrt);
234 }
235 
236 /*
237  * This is similar to the above, but it cannot actually spin on hres_lock.
238  * As a result, it caches all of the variables it needs; if the variables
239  * don't change, it's done.
240  */
241 hrtime_t
242 dtrace_gethrtime(void)
243 {
244 	uint32_t old_hres_lock;
245 	hrtime_t tsc, hrt;
246 	ulong_t flags;
247 
248 	do {
249 		old_hres_lock = hres_lock;
250 
251 		/*
252 		 * Interrupts are disabled to ensure that the thread isn't
253 		 * migrated between the tsc_read() and adding the CPU's
254 		 * TSC tick delta.
255 		 */
256 		flags = clear_int_flag();
257 
258 		tsc = tsc_read();
259 
260 		if (gethrtimef == tsc_gethrtime_delta)
261 			tsc += tsc_sync_tick_delta[CPU->cpu_id];
262 
263 		restore_int_flag(flags);
264 
265 		/*
266 		 * See the comments in tsc_gethrtime(), above.
267 		 */
268 		if (tsc >= tsc_last)
269 			tsc -= tsc_last;
270 		else if (tsc >= tsc_last - 2*tsc_max_delta)
271 			tsc = 0;
272 
273 		hrt = tsc_hrtime_base;
274 
275 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
276 
277 		if ((old_hres_lock & ~1) == hres_lock)
278 			break;
279 
280 		/*
281 		 * If we're here, the clock lock is locked -- or it has been
282 		 * unlocked and locked since we looked.  This may be due to
283 		 * tsc_tick() running on another CPU -- or it may be because
284 		 * some code path has ended up in dtrace_probe() with
285 		 * CLOCK_LOCK held.  We'll try to determine that we're in
286 		 * the former case by taking another lap if the lock has
287 		 * changed since when we first looked at it.
288 		 */
289 		if (old_hres_lock != hres_lock)
290 			continue;
291 
292 		/*
293 		 * So the lock was and is locked.  We'll use the old data
294 		 * instead.
295 		 */
296 		old_hres_lock = shadow_hres_lock;
297 
298 		/*
299 		 * Again, disable interrupts to ensure that the thread
300 		 * isn't migrated between the tsc_read() and adding
301 		 * the CPU's TSC tick delta.
302 		 */
303 		flags = clear_int_flag();
304 
305 		tsc = tsc_read();
306 
307 		if (gethrtimef == tsc_gethrtime_delta)
308 			tsc += tsc_sync_tick_delta[CPU->cpu_id];
309 
310 		restore_int_flag(flags);
311 
312 		/*
313 		 * See the comments in tsc_gethrtime(), above.
314 		 */
315 		if (tsc >= shadow_tsc_last)
316 			tsc -= shadow_tsc_last;
317 		else if (tsc >= shadow_tsc_last - 2 * tsc_max_delta)
318 			tsc = 0;
319 
320 		hrt = shadow_tsc_hrtime_base;
321 
322 		TSC_CONVERT_AND_ADD(tsc, hrt, shadow_nsec_scale);
323 	} while ((old_hres_lock & ~1) != shadow_hres_lock);
324 
325 	return (hrt);
326 }
327 
328 hrtime_t
329 tsc_gethrtimeunscaled(void)
330 {
331 	uint32_t old_hres_lock;
332 	hrtime_t tsc;
333 
334 	do {
335 		old_hres_lock = hres_lock;
336 
337 		/* See tsc_tick(). */
338 		tsc = tsc_read() + tsc_last_jumped;
339 	} while ((old_hres_lock & ~1) != hres_lock);
340 
341 	return (tsc);
342 }
343 
344 
345 /* Convert a tsc timestamp to nanoseconds */
346 void
347 tsc_scalehrtime(hrtime_t *tsc)
348 {
349 	hrtime_t hrt;
350 	hrtime_t mytsc;
351 
352 	if (tsc == NULL)
353 		return;
354 	mytsc = *tsc;
355 
356 	TSC_CONVERT(mytsc, hrt, nsec_scale);
357 	*tsc  = hrt;
358 }
359 
360 hrtime_t
361 tsc_gethrtimeunscaled_delta(void)
362 {
363 	hrtime_t hrt;
364 	ulong_t flags;
365 
366 	/*
367 	 * Similarly to tsc_gethrtime_delta, we need to disable preemption
368 	 * to prevent migration between the call to tsc_gethrtimeunscaled
369 	 * and adding the CPU's hrtime delta. Note that disabling and
370 	 * reenabling preemption is forbidden here because we may be in the
371 	 * middle of a fast trap. In the amd64 kernel we cannot tolerate
372 	 * preemption during a fast trap. See _update_sregs().
373 	 */
374 
375 	flags = clear_int_flag();
376 	hrt = tsc_gethrtimeunscaled() + tsc_sync_tick_delta[CPU->cpu_id];
377 	restore_int_flag(flags);
378 
379 	return (hrt);
380 }
381 
382 /*
383  * Called by the master in the TSC sync operation (usually the boot CPU).
384  * If the slave is discovered to have a skew, gethrtimef will be changed to
385  * point to tsc_gethrtime_delta(). Calculating skews is precise only when
386  * the master and slave TSCs are read simultaneously; however, there is no
387  * algorithm that can read both CPUs in perfect simultaneity. The proposed
388  * algorithm is an approximate method based on the behaviour of cache
389  * management. The slave CPU continuously reads TSC and then reads a global
390  * variable which the master CPU updates. The moment the master's update reaches
391  * the slave's visibility (being forced by an mfence operation) we use the TSC
392  * reading taken on the slave. A corresponding TSC read will be taken on the
393  * master as soon as possible after finishing the mfence operation. But the
394  * delay between causing the slave to notice the invalid cache line and the
395  * competion of mfence is not repeatable. This error is heuristically assumed
396  * to be 1/4th of the total write time as being measured by the two TSC reads
397  * on the master sandwiching the mfence. Furthermore, due to the nature of
398  * bus arbitration, contention on memory bus, etc., the time taken for the write
399  * to reflect globally can vary a lot. So instead of taking a single reading,
400  * a set of readings are taken and the one with least write time is chosen
401  * to calculate the final skew.
402  */
403 void
404 tsc_sync_master(processorid_t slave)
405 {
406 	ulong_t flags, source, min_write_time = ~0UL;
407 	hrtime_t write_time, x, mtsc_after, tdelta;
408 	tsc_sync_t *tsc = tscp;
409 	int cnt;
410 
411 	if (!tsc_master_slave_sync_needed)
412 		return;
413 
414 	flags = clear_int_flag();
415 	source = CPU->cpu_id;
416 
417 	for (cnt = 0; cnt < SYNC_ITERATIONS; cnt++) {
418 		while (tsc_sync_go != TSC_SYNC_GO)
419 			SMT_PAUSE();
420 
421 		tsc->master_tsc = tsc_read();
422 		membar_enter();
423 		mtsc_after = tsc_read();
424 		while (tsc_sync_go != TSC_SYNC_DONE)
425 			SMT_PAUSE();
426 		write_time =  mtsc_after - tsc->master_tsc;
427 		if (write_time <= min_write_time) {
428 			min_write_time = write_time;
429 			/*
430 			 * Apply heuristic adjustment only if the calculated
431 			 * delta is > 1/4th of the write time.
432 			 */
433 			x = tsc->slave_tsc - mtsc_after;
434 			if (x < 0)
435 				x = -x;
436 			if (x > (min_write_time/4))
437 				/*
438 				 * Subtract 1/4th of the measured write time
439 				 * from the master's TSC value, as an estimate
440 				 * of how late the mfence completion came
441 				 * after the slave noticed the cache line
442 				 * change.
443 				 */
444 				tdelta = tsc->slave_tsc -
445 				    (mtsc_after - (min_write_time/4));
446 			else
447 				tdelta = tsc->slave_tsc - mtsc_after;
448 			tsc_sync_tick_delta[slave] =
449 			    tsc_sync_tick_delta[source] - tdelta;
450 		}
451 
452 		tsc->master_tsc = tsc->slave_tsc = write_time = 0;
453 		membar_enter();
454 		tsc_sync_go = TSC_SYNC_STOP;
455 	}
456 	if (tdelta < 0)
457 		tdelta = -tdelta;
458 	if (tdelta > largest_tsc_delta)
459 		largest_tsc_delta = tdelta;
460 	if (min_write_time < shortest_write_time)
461 		shortest_write_time = min_write_time;
462 	/*
463 	 * Enable delta variants of tsc functions if the largest of all chosen
464 	 * deltas is > smallest of the write time.
465 	 */
466 	if (largest_tsc_delta > shortest_write_time) {
467 		gethrtimef = tsc_gethrtime_delta;
468 		gethrtimeunscaledf = tsc_gethrtimeunscaled_delta;
469 	}
470 	restore_int_flag(flags);
471 }
472 
473 void
474 tsc_sync_slave(void)
475 {
476 	ulong_t flags;
477 	hrtime_t s1;
478 	tsc_sync_t *tsc = tscp;
479 	int cnt;
480 
481 	if (!tsc_master_slave_sync_needed)
482 		return;
483 
484 	flags = clear_int_flag();
485 
486 	for (cnt = 0; cnt < SYNC_ITERATIONS; cnt++) {
487 		/* Re-fill the cache line */
488 		s1 = tsc->master_tsc;
489 		membar_enter();
490 		tsc_sync_go = TSC_SYNC_GO;
491 		do {
492 			/*
493 			 * Do not put an SMT_PAUSE here. For instance,
494 			 * if the master and slave are really the same
495 			 * hyper-threaded CPU, then you want the master
496 			 * to yield to the slave as quickly as possible here,
497 			 * but not the other way.
498 			 */
499 			s1 = tsc_read();
500 		} while (tsc->master_tsc == 0);
501 		tsc->slave_tsc = s1;
502 		membar_enter();
503 		tsc_sync_go = TSC_SYNC_DONE;
504 
505 		while (tsc_sync_go != TSC_SYNC_STOP)
506 			SMT_PAUSE();
507 	}
508 
509 	restore_int_flag(flags);
510 }
511 
512 /*
513  * Called once per second on a CPU from the cyclic subsystem's
514  * CY_HIGH_LEVEL interrupt.  (No longer just cpu0-only)
515  */
516 void
517 tsc_tick(void)
518 {
519 	hrtime_t now, delta;
520 	ushort_t spl;
521 
522 	/*
523 	 * Before we set the new variables, we set the shadow values.  This
524 	 * allows for lock free operation in dtrace_gethrtime().
525 	 */
526 	lock_set_spl((lock_t *)&shadow_hres_lock + HRES_LOCK_OFFSET,
527 	    ipltospl(CBE_HIGH_PIL), &spl);
528 
529 	shadow_tsc_hrtime_base = tsc_hrtime_base;
530 	shadow_tsc_last = tsc_last;
531 	shadow_nsec_scale = nsec_scale;
532 
533 	shadow_hres_lock++;
534 	splx(spl);
535 
536 	CLOCK_LOCK(&spl);
537 
538 	now = tsc_read();
539 
540 	if (gethrtimef == tsc_gethrtime_delta)
541 		now += tsc_sync_tick_delta[CPU->cpu_id];
542 
543 	if (now < tsc_last) {
544 		/*
545 		 * The TSC has just jumped into the past.  We assume that
546 		 * this is due to a suspend/resume cycle, and we're going
547 		 * to use the _current_ value of TSC as the delta.  This
548 		 * will keep tsc_hrtime_base correct.  We're also going to
549 		 * assume that rate of tsc does not change after a suspend
550 		 * resume (i.e nsec_scale remains the same).
551 		 */
552 		delta = now;
553 		tsc_last_jumped += tsc_last;
554 		tsc_jumped = 1;
555 	} else {
556 		/*
557 		 * Determine the number of TSC ticks since the last clock
558 		 * tick, and add that to the hrtime base.
559 		 */
560 		delta = now - tsc_last;
561 	}
562 
563 	TSC_CONVERT_AND_ADD(delta, tsc_hrtime_base, nsec_scale);
564 	tsc_last = now;
565 
566 	CLOCK_UNLOCK(spl);
567 }
568 
569 void
570 tsc_hrtimeinit(uint64_t cpu_freq_hz)
571 {
572 	extern int gethrtime_hires;
573 	longlong_t tsc;
574 	ulong_t flags;
575 
576 	/*
577 	 * cpu_freq_hz is the measured cpu frequency in hertz
578 	 */
579 
580 	/*
581 	 * We can't accommodate CPUs slower than 31.25 MHz.
582 	 */
583 	ASSERT(cpu_freq_hz > NANOSEC / (1 << NSEC_SHIFT));
584 	nsec_scale =
585 	    (uint_t)(((uint64_t)NANOSEC << (32 - NSEC_SHIFT)) / cpu_freq_hz);
586 
587 	flags = clear_int_flag();
588 	tsc = tsc_read();
589 	(void) tsc_gethrtime();
590 	tsc_max_delta = tsc_read() - tsc;
591 	restore_int_flag(flags);
592 	gethrtimef = tsc_gethrtime;
593 	gethrtimeunscaledf = tsc_gethrtimeunscaled;
594 	scalehrtimef = tsc_scalehrtime;
595 	hrtime_tick = tsc_tick;
596 	gethrtime_hires = 1;
597 	/*
598 	 * Allocate memory for the structure used in the tsc sync logic.
599 	 * This structure should be aligned on a multiple of cache line size.
600 	 */
601 	tscp = kmem_zalloc(PAGESIZE, KM_SLEEP);
602 }
603 
604 int
605 get_tsc_ready()
606 {
607 	return (tsc_ready);
608 }
609 
610 /*
611  * Adjust all the deltas by adding the passed value to the array.
612  * Then use the "delt" versions of the the gethrtime functions.
613  * Note that 'tdelta' _could_ be a negative number, which should
614  * reduce the values in the array (used, for example, if the Solaris
615  * instance was moved by a virtual manager to a machine with a higher
616  * value of tsc).
617  */
618 void
619 tsc_adjust_delta(hrtime_t tdelta)
620 {
621 	int		i;
622 
623 	for (i = 0; i < NCPU; i++) {
624 		tsc_sync_tick_delta[i] += tdelta;
625 	}
626 
627 	gethrtimef = tsc_gethrtime_delta;
628 	gethrtimeunscaledf = tsc_gethrtimeunscaled_delta;
629 }
630 
631 /*
632  * Functions to manage TSC and high-res time on suspend and resume.
633  */
634 
635 /*
636  * declarations needed for time adjustment
637  */
638 extern void	rtcsync(void);
639 extern tod_ops_t *tod_ops;
640 /* There must be a better way than exposing nsec_scale! */
641 extern uint_t	nsec_scale;
642 static uint64_t tsc_saved_tsc = 0; /* 1 in 2^64 chance this'll screw up! */
643 static timestruc_t tsc_saved_ts;
644 static int	tsc_needs_resume = 0;	/* We only want to do this once. */
645 int		tsc_delta_onsuspend = 0;
646 int		tsc_adjust_seconds = 1;
647 int		tsc_suspend_count = 0;
648 int		tsc_resume_in_cyclic = 0;
649 
650 /*
651  * Let timestamp.c know that we are suspending.  It needs to take
652  * snapshots of the current time, and do any pre-suspend work.
653  */
654 void
655 tsc_suspend(void)
656 {
657 /*
658  * What we need to do here, is to get the time we suspended, so that we
659  * know how much we should add to the resume.
660  * This routine is called by each CPU, so we need to handle reentry.
661  */
662 	if (tsc_gethrtime_enable) {
663 		/*
664 		 * We put the tsc_read() inside the lock as it
665 		 * as no locking constraints, and it puts the
666 		 * aquired value closer to the time stamp (in
667 		 * case we delay getting the lock).
668 		 */
669 		mutex_enter(&tod_lock);
670 		tsc_saved_tsc = tsc_read();
671 		tsc_saved_ts = TODOP_GET(tod_ops);
672 		mutex_exit(&tod_lock);
673 		/* We only want to do this once. */
674 		if (tsc_needs_resume == 0) {
675 			if (tsc_delta_onsuspend) {
676 				tsc_adjust_delta(tsc_saved_tsc);
677 			} else {
678 				tsc_adjust_delta(nsec_scale);
679 			}
680 			tsc_suspend_count++;
681 		}
682 	}
683 
684 	invalidate_cache();
685 	tsc_needs_resume = 1;
686 }
687 
688 /*
689  * Restore all timestamp state based on the snapshots taken at
690  * suspend time.
691  */
692 void
693 tsc_resume(void)
694 {
695 	/*
696 	 * We only need to (and want to) do this once.  So let the first
697 	 * caller handle this (we are locked by the cpu lock), as it
698 	 * is preferential that we get the earliest sync.
699 	 */
700 	if (tsc_needs_resume) {
701 		/*
702 		 * If using the TSC, adjust the delta based on how long
703 		 * we were sleeping (or away).  We also adjust for
704 		 * migration and a grown TSC.
705 		 */
706 		if (tsc_saved_tsc != 0) {
707 			timestruc_t	ts;
708 			hrtime_t	now, sleep_tsc = 0;
709 			int		sleep_sec;
710 			extern void	tsc_tick(void);
711 			extern uint64_t cpu_freq_hz;
712 
713 			/* tsc_read() MUST be before TODOP_GET() */
714 			mutex_enter(&tod_lock);
715 			now = tsc_read();
716 			ts = TODOP_GET(tod_ops);
717 			mutex_exit(&tod_lock);
718 
719 			/* Compute seconds of sleep time */
720 			sleep_sec = ts.tv_sec - tsc_saved_ts.tv_sec;
721 
722 			/*
723 			 * If the saved sec is less that or equal to
724 			 * the current ts, then there is likely a
725 			 * problem with the clock.  Assume at least
726 			 * one second has passed, so that time goes forward.
727 			 */
728 			if (sleep_sec <= 0) {
729 				sleep_sec = 1;
730 			}
731 
732 			/* How many TSC's should have occured while sleeping */
733 			if (tsc_adjust_seconds)
734 				sleep_tsc = sleep_sec * cpu_freq_hz;
735 
736 			/*
737 			 * We also want to subtract from the "sleep_tsc"
738 			 * the current value of tsc_read(), so that our
739 			 * adjustment accounts for the amount of time we
740 			 * have been resumed _or_ an adjustment based on
741 			 * the fact that we didn't actually power off the
742 			 * CPU (migration is another issue, but _should_
743 			 * also comply with this calculation).  If the CPU
744 			 * never powered off, then:
745 			 *    'now == sleep_tsc + saved_tsc'
746 			 * and the delta will effectively be "0".
747 			 */
748 			sleep_tsc -= now;
749 			if (tsc_delta_onsuspend) {
750 				tsc_adjust_delta(sleep_tsc);
751 			} else {
752 				tsc_adjust_delta(tsc_saved_tsc + sleep_tsc);
753 			}
754 			tsc_saved_tsc = 0;
755 
756 			tsc_tick();
757 		}
758 		tsc_needs_resume = 0;
759 	}
760 
761 }
762