xref: /illumos-gate/usr/src/uts/i86pc/os/timestamp.c (revision 7997e108b559ec4bb8a4c39fbfb6ca5606995a08)
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 
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 extern int platform_is_virt;
138 
139 static int	tsc_max_delta;
140 static hrtime_t tsc_sync_tick_delta[NCPU];
141 typedef struct tsc_sync {
142 	volatile hrtime_t master_tsc, slave_tsc;
143 } tsc_sync_t;
144 static tsc_sync_t *tscp;
145 static hrtime_t largest_tsc_delta = 0;
146 static ulong_t shortest_write_time = ~0UL;
147 
148 static hrtime_t	tsc_last = 0;
149 static hrtime_t	tsc_last_jumped = 0;
150 static hrtime_t	tsc_hrtime_base = 0;
151 static int	tsc_jumped = 0;
152 
153 static hrtime_t	shadow_tsc_hrtime_base;
154 static hrtime_t	shadow_tsc_last;
155 static uint_t	shadow_nsec_scale;
156 static uint32_t	shadow_hres_lock;
157 int get_tsc_ready();
158 
159 hrtime_t
160 tsc_gethrtime(void)
161 {
162 	uint32_t old_hres_lock;
163 	hrtime_t tsc, hrt;
164 
165 	do {
166 		old_hres_lock = hres_lock;
167 
168 		if ((tsc = tsc_read()) >= tsc_last) {
169 			/*
170 			 * It would seem to be obvious that this is true
171 			 * (that is, the past is less than the present),
172 			 * but it isn't true in the presence of suspend/resume
173 			 * cycles.  If we manage to call gethrtime()
174 			 * after a resume, but before the first call to
175 			 * tsc_tick(), we will see the jump.  In this case,
176 			 * we will simply use the value in TSC as the delta.
177 			 */
178 			tsc -= tsc_last;
179 		} else if (tsc >= tsc_last - 2*tsc_max_delta) {
180 			/*
181 			 * There is a chance that tsc_tick() has just run on
182 			 * another CPU, and we have drifted just enough so that
183 			 * we appear behind tsc_last.  In this case, force the
184 			 * delta to be zero.
185 			 */
186 			tsc = 0;
187 		}
188 
189 		hrt = tsc_hrtime_base;
190 
191 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
192 	} while ((old_hres_lock & ~1) != hres_lock);
193 
194 	return (hrt);
195 }
196 
197 hrtime_t
198 tsc_gethrtime_delta(void)
199 {
200 	uint32_t old_hres_lock;
201 	hrtime_t tsc, hrt;
202 	ulong_t flags;
203 
204 	do {
205 		old_hres_lock = hres_lock;
206 
207 		/*
208 		 * We need to disable interrupts here to assure that we
209 		 * don't migrate between the call to tsc_read() and
210 		 * adding the CPU's TSC tick delta. Note that disabling
211 		 * and reenabling preemption is forbidden here because
212 		 * we may be in the middle of a fast trap. In the amd64
213 		 * kernel we cannot tolerate preemption during a fast
214 		 * trap. See _update_sregs().
215 		 */
216 
217 		flags = clear_int_flag();
218 		tsc = tsc_read() + tsc_sync_tick_delta[CPU->cpu_id];
219 		restore_int_flag(flags);
220 
221 		/* See comments in tsc_gethrtime() above */
222 
223 		if (tsc >= tsc_last) {
224 			tsc -= tsc_last;
225 		} else if (tsc >= tsc_last - 2 * tsc_max_delta) {
226 			tsc = 0;
227 		}
228 
229 		hrt = tsc_hrtime_base;
230 
231 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
232 	} while ((old_hres_lock & ~1) != hres_lock);
233 
234 	return (hrt);
235 }
236 
237 /*
238  * This is similar to the above, but it cannot actually spin on hres_lock.
239  * As a result, it caches all of the variables it needs; if the variables
240  * don't change, it's done.
241  */
242 hrtime_t
243 dtrace_gethrtime(void)
244 {
245 	uint32_t old_hres_lock;
246 	hrtime_t tsc, hrt;
247 	ulong_t flags;
248 
249 	do {
250 		old_hres_lock = hres_lock;
251 
252 		/*
253 		 * Interrupts are disabled to ensure that the thread isn't
254 		 * migrated between the tsc_read() and adding the CPU's
255 		 * TSC tick delta.
256 		 */
257 		flags = clear_int_flag();
258 
259 		tsc = tsc_read();
260 
261 		if (gethrtimef == tsc_gethrtime_delta)
262 			tsc += tsc_sync_tick_delta[CPU->cpu_id];
263 
264 		restore_int_flag(flags);
265 
266 		/*
267 		 * See the comments in tsc_gethrtime(), above.
268 		 */
269 		if (tsc >= tsc_last)
270 			tsc -= tsc_last;
271 		else if (tsc >= tsc_last - 2*tsc_max_delta)
272 			tsc = 0;
273 
274 		hrt = tsc_hrtime_base;
275 
276 		TSC_CONVERT_AND_ADD(tsc, hrt, nsec_scale);
277 
278 		if ((old_hres_lock & ~1) == hres_lock)
279 			break;
280 
281 		/*
282 		 * If we're here, the clock lock is locked -- or it has been
283 		 * unlocked and locked since we looked.  This may be due to
284 		 * tsc_tick() running on another CPU -- or it may be because
285 		 * some code path has ended up in dtrace_probe() with
286 		 * CLOCK_LOCK held.  We'll try to determine that we're in
287 		 * the former case by taking another lap if the lock has
288 		 * changed since when we first looked at it.
289 		 */
290 		if (old_hres_lock != hres_lock)
291 			continue;
292 
293 		/*
294 		 * So the lock was and is locked.  We'll use the old data
295 		 * instead.
296 		 */
297 		old_hres_lock = shadow_hres_lock;
298 
299 		/*
300 		 * Again, disable interrupts to ensure that the thread
301 		 * isn't migrated between the tsc_read() and adding
302 		 * the CPU's TSC tick delta.
303 		 */
304 		flags = clear_int_flag();
305 
306 		tsc = tsc_read();
307 
308 		if (gethrtimef == tsc_gethrtime_delta)
309 			tsc += tsc_sync_tick_delta[CPU->cpu_id];
310 
311 		restore_int_flag(flags);
312 
313 		/*
314 		 * See the comments in tsc_gethrtime(), above.
315 		 */
316 		if (tsc >= shadow_tsc_last)
317 			tsc -= shadow_tsc_last;
318 		else if (tsc >= shadow_tsc_last - 2 * tsc_max_delta)
319 			tsc = 0;
320 
321 		hrt = shadow_tsc_hrtime_base;
322 
323 		TSC_CONVERT_AND_ADD(tsc, hrt, shadow_nsec_scale);
324 	} while ((old_hres_lock & ~1) != shadow_hres_lock);
325 
326 	return (hrt);
327 }
328 
329 hrtime_t
330 tsc_gethrtimeunscaled(void)
331 {
332 	uint32_t old_hres_lock;
333 	hrtime_t tsc;
334 
335 	do {
336 		old_hres_lock = hres_lock;
337 
338 		/* See tsc_tick(). */
339 		tsc = tsc_read() + tsc_last_jumped;
340 	} while ((old_hres_lock & ~1) != hres_lock);
341 
342 	return (tsc);
343 }
344 
345 
346 /* Convert a tsc timestamp to nanoseconds */
347 void
348 tsc_scalehrtime(hrtime_t *tsc)
349 {
350 	hrtime_t hrt;
351 	hrtime_t mytsc;
352 
353 	if (tsc == NULL)
354 		return;
355 	mytsc = *tsc;
356 
357 	TSC_CONVERT(mytsc, hrt, nsec_scale);
358 	*tsc  = hrt;
359 }
360 
361 hrtime_t
362 tsc_gethrtimeunscaled_delta(void)
363 {
364 	hrtime_t hrt;
365 	ulong_t flags;
366 
367 	/*
368 	 * Similarly to tsc_gethrtime_delta, we need to disable preemption
369 	 * to prevent migration between the call to tsc_gethrtimeunscaled
370 	 * and adding the CPU's hrtime delta. Note that disabling and
371 	 * reenabling preemption is forbidden here because we may be in the
372 	 * middle of a fast trap. In the amd64 kernel we cannot tolerate
373 	 * preemption during a fast trap. See _update_sregs().
374 	 */
375 
376 	flags = clear_int_flag();
377 	hrt = tsc_gethrtimeunscaled() + tsc_sync_tick_delta[CPU->cpu_id];
378 	restore_int_flag(flags);
379 
380 	return (hrt);
381 }
382 
383 /*
384  * Called by the master in the TSC sync operation (usually the boot CPU).
385  * If the slave is discovered to have a skew, gethrtimef will be changed to
386  * point to tsc_gethrtime_delta(). Calculating skews is precise only when
387  * the master and slave TSCs are read simultaneously; however, there is no
388  * algorithm that can read both CPUs in perfect simultaneity. The proposed
389  * algorithm is an approximate method based on the behaviour of cache
390  * management. The slave CPU continuously reads TSC and then reads a global
391  * variable which the master CPU updates. The moment the master's update reaches
392  * the slave's visibility (being forced by an mfence operation) we use the TSC
393  * reading taken on the slave. A corresponding TSC read will be taken on the
394  * master as soon as possible after finishing the mfence operation. But the
395  * delay between causing the slave to notice the invalid cache line and the
396  * competion of mfence is not repeatable. This error is heuristically assumed
397  * to be 1/4th of the total write time as being measured by the two TSC reads
398  * on the master sandwiching the mfence. Furthermore, due to the nature of
399  * bus arbitration, contention on memory bus, etc., the time taken for the write
400  * to reflect globally can vary a lot. So instead of taking a single reading,
401  * a set of readings are taken and the one with least write time is chosen
402  * to calculate the final skew.
403  *
404  * TSC sync is disabled in the context of virtualization because the CPUs
405  * assigned to the guest are virtual CPUs which means the real CPUs on which
406  * guest runs keep changing during life time of guest OS. So we would end up
407  * calculating TSC skews for a set of CPUs during boot whereas the guest
408  * might migrate to a different set of physical CPUs at a later point of
409  * time.
410  */
411 void
412 tsc_sync_master(processorid_t slave)
413 {
414 	ulong_t flags, source, min_write_time = ~0UL;
415 	hrtime_t write_time, x, mtsc_after, tdelta;
416 	tsc_sync_t *tsc = tscp;
417 	int cnt;
418 
419 	if (!tsc_master_slave_sync_needed || platform_is_virt)
420 		return;
421 
422 	flags = clear_int_flag();
423 	source = CPU->cpu_id;
424 
425 	for (cnt = 0; cnt < SYNC_ITERATIONS; cnt++) {
426 		while (tsc_sync_go != TSC_SYNC_GO)
427 			SMT_PAUSE();
428 
429 		tsc->master_tsc = tsc_read();
430 		membar_enter();
431 		mtsc_after = tsc_read();
432 		while (tsc_sync_go != TSC_SYNC_DONE)
433 			SMT_PAUSE();
434 		write_time =  mtsc_after - tsc->master_tsc;
435 		if (write_time <= min_write_time) {
436 			min_write_time = write_time;
437 			/*
438 			 * Apply heuristic adjustment only if the calculated
439 			 * delta is > 1/4th of the write time.
440 			 */
441 			x = tsc->slave_tsc - mtsc_after;
442 			if (x < 0)
443 				x = -x;
444 			if (x > (min_write_time/4))
445 				/*
446 				 * Subtract 1/4th of the measured write time
447 				 * from the master's TSC value, as an estimate
448 				 * of how late the mfence completion came
449 				 * after the slave noticed the cache line
450 				 * change.
451 				 */
452 				tdelta = tsc->slave_tsc -
453 				    (mtsc_after - (min_write_time/4));
454 			else
455 				tdelta = tsc->slave_tsc - mtsc_after;
456 			tsc_sync_tick_delta[slave] =
457 			    tsc_sync_tick_delta[source] - tdelta;
458 		}
459 
460 		tsc->master_tsc = tsc->slave_tsc = write_time = 0;
461 		membar_enter();
462 		tsc_sync_go = TSC_SYNC_STOP;
463 	}
464 	if (tdelta < 0)
465 		tdelta = -tdelta;
466 	if (tdelta > largest_tsc_delta)
467 		largest_tsc_delta = tdelta;
468 	if (min_write_time < shortest_write_time)
469 		shortest_write_time = min_write_time;
470 	/*
471 	 * Enable delta variants of tsc functions if the largest of all chosen
472 	 * deltas is > smallest of the write time.
473 	 */
474 	if (largest_tsc_delta > shortest_write_time) {
475 		gethrtimef = tsc_gethrtime_delta;
476 		gethrtimeunscaledf = tsc_gethrtimeunscaled_delta;
477 	}
478 	restore_int_flag(flags);
479 }
480 
481 /*
482  * Called by a CPU which has just been onlined.  It is expected that the CPU
483  * performing the online operation will call tsc_sync_master().
484  *
485  * TSC sync is disabled in the context of virtualization. See comments
486  * above tsc_sync_master.
487  */
488 void
489 tsc_sync_slave(void)
490 {
491 	ulong_t flags;
492 	hrtime_t s1;
493 	tsc_sync_t *tsc = tscp;
494 	int cnt;
495 
496 	if (!tsc_master_slave_sync_needed || platform_is_virt)
497 		return;
498 
499 	flags = clear_int_flag();
500 
501 	for (cnt = 0; cnt < SYNC_ITERATIONS; cnt++) {
502 		/* Re-fill the cache line */
503 		s1 = tsc->master_tsc;
504 		membar_enter();
505 		tsc_sync_go = TSC_SYNC_GO;
506 		do {
507 			/*
508 			 * Do not put an SMT_PAUSE here. For instance,
509 			 * if the master and slave are really the same
510 			 * hyper-threaded CPU, then you want the master
511 			 * to yield to the slave as quickly as possible here,
512 			 * but not the other way.
513 			 */
514 			s1 = tsc_read();
515 		} while (tsc->master_tsc == 0);
516 		tsc->slave_tsc = s1;
517 		membar_enter();
518 		tsc_sync_go = TSC_SYNC_DONE;
519 
520 		while (tsc_sync_go != TSC_SYNC_STOP)
521 			SMT_PAUSE();
522 	}
523 
524 	restore_int_flag(flags);
525 }
526 
527 /*
528  * Called once per second on a CPU from the cyclic subsystem's
529  * CY_HIGH_LEVEL interrupt.  (No longer just cpu0-only)
530  */
531 void
532 tsc_tick(void)
533 {
534 	hrtime_t now, delta;
535 	ushort_t spl;
536 
537 	/*
538 	 * Before we set the new variables, we set the shadow values.  This
539 	 * allows for lock free operation in dtrace_gethrtime().
540 	 */
541 	lock_set_spl((lock_t *)&shadow_hres_lock + HRES_LOCK_OFFSET,
542 	    ipltospl(CBE_HIGH_PIL), &spl);
543 
544 	shadow_tsc_hrtime_base = tsc_hrtime_base;
545 	shadow_tsc_last = tsc_last;
546 	shadow_nsec_scale = nsec_scale;
547 
548 	shadow_hres_lock++;
549 	splx(spl);
550 
551 	CLOCK_LOCK(&spl);
552 
553 	now = tsc_read();
554 
555 	if (gethrtimef == tsc_gethrtime_delta)
556 		now += tsc_sync_tick_delta[CPU->cpu_id];
557 
558 	if (now < tsc_last) {
559 		/*
560 		 * The TSC has just jumped into the past.  We assume that
561 		 * this is due to a suspend/resume cycle, and we're going
562 		 * to use the _current_ value of TSC as the delta.  This
563 		 * will keep tsc_hrtime_base correct.  We're also going to
564 		 * assume that rate of tsc does not change after a suspend
565 		 * resume (i.e nsec_scale remains the same).
566 		 */
567 		delta = now;
568 		tsc_last_jumped += tsc_last;
569 		tsc_jumped = 1;
570 	} else {
571 		/*
572 		 * Determine the number of TSC ticks since the last clock
573 		 * tick, and add that to the hrtime base.
574 		 */
575 		delta = now - tsc_last;
576 	}
577 
578 	TSC_CONVERT_AND_ADD(delta, tsc_hrtime_base, nsec_scale);
579 	tsc_last = now;
580 
581 	CLOCK_UNLOCK(spl);
582 }
583 
584 void
585 tsc_hrtimeinit(uint64_t cpu_freq_hz)
586 {
587 	extern int gethrtime_hires;
588 	longlong_t tsc;
589 	ulong_t flags;
590 
591 	/*
592 	 * cpu_freq_hz is the measured cpu frequency in hertz
593 	 */
594 
595 	/*
596 	 * We can't accommodate CPUs slower than 31.25 MHz.
597 	 */
598 	ASSERT(cpu_freq_hz > NANOSEC / (1 << NSEC_SHIFT));
599 	nsec_scale =
600 	    (uint_t)(((uint64_t)NANOSEC << (32 - NSEC_SHIFT)) / cpu_freq_hz);
601 
602 	flags = clear_int_flag();
603 	tsc = tsc_read();
604 	(void) tsc_gethrtime();
605 	tsc_max_delta = tsc_read() - tsc;
606 	restore_int_flag(flags);
607 	gethrtimef = tsc_gethrtime;
608 	gethrtimeunscaledf = tsc_gethrtimeunscaled;
609 	scalehrtimef = tsc_scalehrtime;
610 	hrtime_tick = tsc_tick;
611 	gethrtime_hires = 1;
612 	/*
613 	 * Allocate memory for the structure used in the tsc sync logic.
614 	 * This structure should be aligned on a multiple of cache line size.
615 	 */
616 	tscp = kmem_zalloc(PAGESIZE, KM_SLEEP);
617 }
618 
619 int
620 get_tsc_ready()
621 {
622 	return (tsc_ready);
623 }
624 
625 /*
626  * Adjust all the deltas by adding the passed value to the array.
627  * Then use the "delt" versions of the the gethrtime functions.
628  * Note that 'tdelta' _could_ be a negative number, which should
629  * reduce the values in the array (used, for example, if the Solaris
630  * instance was moved by a virtual manager to a machine with a higher
631  * value of tsc).
632  */
633 void
634 tsc_adjust_delta(hrtime_t tdelta)
635 {
636 	int		i;
637 
638 	for (i = 0; i < NCPU; i++) {
639 		tsc_sync_tick_delta[i] += tdelta;
640 	}
641 
642 	gethrtimef = tsc_gethrtime_delta;
643 	gethrtimeunscaledf = tsc_gethrtimeunscaled_delta;
644 }
645 
646 /*
647  * Functions to manage TSC and high-res time on suspend and resume.
648  */
649 
650 /*
651  * declarations needed for time adjustment
652  */
653 extern void	rtcsync(void);
654 extern tod_ops_t *tod_ops;
655 /* There must be a better way than exposing nsec_scale! */
656 extern uint_t	nsec_scale;
657 static uint64_t tsc_saved_tsc = 0; /* 1 in 2^64 chance this'll screw up! */
658 static timestruc_t tsc_saved_ts;
659 static int	tsc_needs_resume = 0;	/* We only want to do this once. */
660 int		tsc_delta_onsuspend = 0;
661 int		tsc_adjust_seconds = 1;
662 int		tsc_suspend_count = 0;
663 int		tsc_resume_in_cyclic = 0;
664 
665 /*
666  * Let timestamp.c know that we are suspending.  It needs to take
667  * snapshots of the current time, and do any pre-suspend work.
668  */
669 void
670 tsc_suspend(void)
671 {
672 /*
673  * What we need to do here, is to get the time we suspended, so that we
674  * know how much we should add to the resume.
675  * This routine is called by each CPU, so we need to handle reentry.
676  */
677 	if (tsc_gethrtime_enable) {
678 		/*
679 		 * We put the tsc_read() inside the lock as it
680 		 * as no locking constraints, and it puts the
681 		 * aquired value closer to the time stamp (in
682 		 * case we delay getting the lock).
683 		 */
684 		mutex_enter(&tod_lock);
685 		tsc_saved_tsc = tsc_read();
686 		tsc_saved_ts = TODOP_GET(tod_ops);
687 		mutex_exit(&tod_lock);
688 		/* We only want to do this once. */
689 		if (tsc_needs_resume == 0) {
690 			if (tsc_delta_onsuspend) {
691 				tsc_adjust_delta(tsc_saved_tsc);
692 			} else {
693 				tsc_adjust_delta(nsec_scale);
694 			}
695 			tsc_suspend_count++;
696 		}
697 	}
698 
699 	invalidate_cache();
700 	tsc_needs_resume = 1;
701 }
702 
703 /*
704  * Restore all timestamp state based on the snapshots taken at
705  * suspend time.
706  */
707 void
708 tsc_resume(void)
709 {
710 	/*
711 	 * We only need to (and want to) do this once.  So let the first
712 	 * caller handle this (we are locked by the cpu lock), as it
713 	 * is preferential that we get the earliest sync.
714 	 */
715 	if (tsc_needs_resume) {
716 		/*
717 		 * If using the TSC, adjust the delta based on how long
718 		 * we were sleeping (or away).  We also adjust for
719 		 * migration and a grown TSC.
720 		 */
721 		if (tsc_saved_tsc != 0) {
722 			timestruc_t	ts;
723 			hrtime_t	now, sleep_tsc = 0;
724 			int		sleep_sec;
725 			extern void	tsc_tick(void);
726 			extern uint64_t cpu_freq_hz;
727 
728 			/* tsc_read() MUST be before TODOP_GET() */
729 			mutex_enter(&tod_lock);
730 			now = tsc_read();
731 			ts = TODOP_GET(tod_ops);
732 			mutex_exit(&tod_lock);
733 
734 			/* Compute seconds of sleep time */
735 			sleep_sec = ts.tv_sec - tsc_saved_ts.tv_sec;
736 
737 			/*
738 			 * If the saved sec is less that or equal to
739 			 * the current ts, then there is likely a
740 			 * problem with the clock.  Assume at least
741 			 * one second has passed, so that time goes forward.
742 			 */
743 			if (sleep_sec <= 0) {
744 				sleep_sec = 1;
745 			}
746 
747 			/* How many TSC's should have occured while sleeping */
748 			if (tsc_adjust_seconds)
749 				sleep_tsc = sleep_sec * cpu_freq_hz;
750 
751 			/*
752 			 * We also want to subtract from the "sleep_tsc"
753 			 * the current value of tsc_read(), so that our
754 			 * adjustment accounts for the amount of time we
755 			 * have been resumed _or_ an adjustment based on
756 			 * the fact that we didn't actually power off the
757 			 * CPU (migration is another issue, but _should_
758 			 * also comply with this calculation).  If the CPU
759 			 * never powered off, then:
760 			 *    'now == sleep_tsc + saved_tsc'
761 			 * and the delta will effectively be "0".
762 			 */
763 			sleep_tsc -= now;
764 			if (tsc_delta_onsuspend) {
765 				tsc_adjust_delta(sleep_tsc);
766 			} else {
767 				tsc_adjust_delta(tsc_saved_tsc + sleep_tsc);
768 			}
769 			tsc_saved_tsc = 0;
770 
771 			tsc_tick();
772 		}
773 		tsc_needs_resume = 0;
774 	}
775 
776 }
777