VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPDrvGip.cpp@ 64260

Last change on this file since 64260 was 64260, checked in by vboxsync, 9 years ago

supdrvGipDetectGetGipCpuCallback: paranoia, pGipCpu could be NULL.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 180.0 KB
Line 
1/* $Id: SUPDrvGip.cpp 64260 2016-10-13 15:54:01Z vboxsync $ */
2/** @file
3 * VBoxDrv - The VirtualBox Support Driver - Common code for GIP.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP LOG_GROUP_SUP_DRV
32#define SUPDRV_AGNOSTIC
33#include "SUPDrvInternal.h"
34#ifndef PAGE_SHIFT
35# include <iprt/param.h>
36#endif
37#include <iprt/asm.h>
38#include <iprt/asm-amd64-x86.h>
39#include <iprt/asm-math.h>
40#include <iprt/cpuset.h>
41#include <iprt/handletable.h>
42#include <iprt/mem.h>
43#include <iprt/mp.h>
44#include <iprt/power.h>
45#include <iprt/process.h>
46#include <iprt/semaphore.h>
47#include <iprt/spinlock.h>
48#include <iprt/thread.h>
49#include <iprt/uuid.h>
50#include <iprt/net.h>
51#include <iprt/crc.h>
52#include <iprt/string.h>
53#include <iprt/timer.h>
54#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
55# include <iprt/rand.h>
56# include <iprt/path.h>
57#endif
58#include <iprt/uint128.h>
59#include <iprt/x86.h>
60
61#include <VBox/param.h>
62#include <VBox/log.h>
63#include <VBox/err.h>
64
65#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
66# include "dtrace/SUPDrv.h"
67#else
68/* ... */
69#endif
70
71
72/*********************************************************************************************************************************
73* Defined Constants And Macros *
74*********************************************************************************************************************************/
75/** The frequency by which we recalculate the u32UpdateHz and
76 * u32UpdateIntervalNS GIP members. The value must be a power of 2.
77 *
78 * Warning: Bumping this too high might overflow u32UpdateIntervalNS.
79 */
80#define GIP_UPDATEHZ_RECALC_FREQ 0x800
81
82/** A reserved TSC value used for synchronization as well as measurement of
83 * TSC deltas. */
84#define GIP_TSC_DELTA_RSVD UINT64_MAX
85/** The number of TSC delta measurement loops in total (includes primer and
86 * read-time loops). */
87#define GIP_TSC_DELTA_LOOPS 96
88/** The number of cache primer loops. */
89#define GIP_TSC_DELTA_PRIMER_LOOPS 4
90/** The number of loops until we keep computing the minumum read time. */
91#define GIP_TSC_DELTA_READ_TIME_LOOPS 24
92
93/** The TSC frequency refinement period in seconds.
94 * The timer fires after 200ms, then every second, this value just says when
95 * to stop it after that. */
96#define GIP_TSC_REFINE_PERIOD_IN_SECS 12
97/** The TSC-delta threshold for the SUPGIPUSETSCDELTA_PRACTICALLY_ZERO rating */
98#define GIP_TSC_DELTA_THRESHOLD_PRACTICALLY_ZERO 32
99/** The TSC-delta threshold for the SUPGIPUSETSCDELTA_ROUGHLY_ZERO rating */
100#define GIP_TSC_DELTA_THRESHOLD_ROUGHLY_ZERO 448
101/** The TSC delta value for the initial GIP master - 0 in regular builds.
102 * To test the delta code this can be set to a non-zero value. */
103#if 0
104# define GIP_TSC_DELTA_INITIAL_MASTER_VALUE INT64_C(170139095182512) /* 0x00009abd9854acb0 */
105#else
106# define GIP_TSC_DELTA_INITIAL_MASTER_VALUE INT64_C(0)
107#endif
108
109AssertCompile(GIP_TSC_DELTA_PRIMER_LOOPS < GIP_TSC_DELTA_READ_TIME_LOOPS);
110AssertCompile(GIP_TSC_DELTA_PRIMER_LOOPS + GIP_TSC_DELTA_READ_TIME_LOOPS < GIP_TSC_DELTA_LOOPS);
111
112/** @def VBOX_SVN_REV
113 * The makefile should define this if it can. */
114#ifndef VBOX_SVN_REV
115# define VBOX_SVN_REV 0
116#endif
117
118#if 0 /* Don't start the GIP timers. Useful when debugging the IPRT timer code. */
119# define DO_NOT_START_GIP
120#endif
121
122
123/*********************************************************************************************************************************
124* Internal Functions *
125*********************************************************************************************************************************/
126static DECLCALLBACK(void) supdrvGipSyncAndInvariantTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
127static DECLCALLBACK(void) supdrvGipAsyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
128static int supdrvGipSetFlags(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, uint32_t fOrMask, uint32_t fAndMask);
129static void supdrvGipInitCpu(PSUPGLOBALINFOPAGE pGip, PSUPGIPCPU pCpu, uint64_t u64NanoTS, uint64_t uCpuHz);
130static void supdrvTscResetSamples(PSUPDRVDEVEXT pDevExt, bool fClearDeltas);
131#ifdef SUPDRV_USE_TSC_DELTA_THREAD
132static int supdrvTscDeltaThreadInit(PSUPDRVDEVEXT pDevExt);
133static void supdrvTscDeltaTerm(PSUPDRVDEVEXT pDevExt);
134static void supdrvTscDeltaThreadStartMeasurement(PSUPDRVDEVEXT pDevExt, bool fForceAll);
135#else
136static int supdrvTscMeasureInitialDeltas(PSUPDRVDEVEXT pDevExt);
137static int supdrvTscMeasureDeltaOne(PSUPDRVDEVEXT pDevExt, uint32_t idxWorker);
138#endif
139
140
141/*********************************************************************************************************************************
142* Global Variables *
143*********************************************************************************************************************************/
144DECLEXPORT(PSUPGLOBALINFOPAGE) g_pSUPGlobalInfoPage = NULL;
145
146
147
148/*
149 *
150 * Misc Common GIP Code
151 * Misc Common GIP Code
152 * Misc Common GIP Code
153 *
154 *
155 */
156
157
158/**
159 * Finds the GIP CPU index corresponding to @a idCpu.
160 *
161 * @returns GIP CPU array index, UINT32_MAX if not found.
162 * @param pGip The GIP.
163 * @param idCpu The CPU ID.
164 */
165static uint32_t supdrvGipFindCpuIndexForCpuId(PSUPGLOBALINFOPAGE pGip, RTCPUID idCpu)
166{
167 uint32_t i;
168 for (i = 0; i < pGip->cCpus; i++)
169 if (pGip->aCPUs[i].idCpu == idCpu)
170 return i;
171 return UINT32_MAX;
172}
173
174
175
176/*
177 *
178 * GIP Mapping and Unmapping Related Code.
179 * GIP Mapping and Unmapping Related Code.
180 * GIP Mapping and Unmapping Related Code.
181 *
182 *
183 */
184
185
186/**
187 * (Re-)initializes the per-cpu structure prior to starting or resuming the GIP
188 * updating.
189 *
190 * @param pGipCpu The per CPU structure for this CPU.
191 * @param u64NanoTS The current time.
192 */
193static void supdrvGipReInitCpu(PSUPGIPCPU pGipCpu, uint64_t u64NanoTS)
194{
195 /*
196 * Here we don't really care about applying the TSC delta. The re-initialization of this
197 * value is not relevant especially while (re)starting the GIP as the first few ones will
198 * be ignored anyway, see supdrvGipDoUpdateCpu().
199 */
200 pGipCpu->u64TSC = ASMReadTSC() - pGipCpu->u32UpdateIntervalTSC;
201 pGipCpu->u64NanoTS = u64NanoTS;
202}
203
204
205/**
206 * Set the current TSC and NanoTS value for the CPU.
207 *
208 * @param idCpu The CPU ID. Unused - we have to use the APIC ID.
209 * @param pvUser1 Pointer to the ring-0 GIP mapping.
210 * @param pvUser2 Pointer to the variable holding the current time.
211 */
212static DECLCALLBACK(void) supdrvGipReInitCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
213{
214 PSUPGLOBALINFOPAGE pGip = (PSUPGLOBALINFOPAGE)pvUser1;
215 unsigned iCpu = pGip->aiCpuFromApicId[ASMGetApicId()];
216
217 if (RT_LIKELY(iCpu < pGip->cCpus && pGip->aCPUs[iCpu].idCpu == idCpu))
218 supdrvGipReInitCpu(&pGip->aCPUs[iCpu], *(uint64_t *)pvUser2);
219
220 NOREF(pvUser2);
221 NOREF(idCpu);
222}
223
224
225/**
226 * State structure for supdrvGipDetectGetGipCpuCallback.
227 */
228typedef struct SUPDRVGIPDETECTGETCPU
229{
230 /** Bitmap of APIC IDs that has been seen (initialized to zero).
231 * Used to detect duplicate APIC IDs (paranoia). */
232 uint8_t volatile bmApicId[256 / 8];
233 /** Mask of supported GIP CPU getter methods (SUPGIPGETCPU_XXX) (all bits set
234 * initially). The callback clears the methods not detected. */
235 uint32_t volatile fSupported;
236 /** The first callback detecting any kind of range issues (initialized to
237 * NIL_RTCPUID). */
238 RTCPUID volatile idCpuProblem;
239} SUPDRVGIPDETECTGETCPU;
240/** Pointer to state structure for supdrvGipDetectGetGipCpuCallback. */
241typedef SUPDRVGIPDETECTGETCPU *PSUPDRVGIPDETECTGETCPU;
242
243
244/**
245 * Checks for alternative ways of getting the CPU ID.
246 *
247 * This also checks the APIC ID, CPU ID and CPU set index values against the
248 * GIP tables.
249 *
250 * @param idCpu The CPU ID. Unused - we have to use the APIC ID.
251 * @param pvUser1 Pointer to the state structure.
252 * @param pvUser2 Pointer to the GIP.
253 */
254static DECLCALLBACK(void) supdrvGipDetectGetGipCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
255{
256 PSUPDRVGIPDETECTGETCPU pState = (PSUPDRVGIPDETECTGETCPU)pvUser1;
257 PSUPGLOBALINFOPAGE pGip = (PSUPGLOBALINFOPAGE)pvUser2;
258 uint32_t fSupported = 0;
259 uint16_t idApic;
260 int iCpuSet;
261 NOREF(pGip);
262
263 AssertMsg(idCpu == RTMpCpuId(), ("idCpu=%#x RTMpCpuId()=%#x\n", idCpu, RTMpCpuId())); /* paranoia^3 */
264
265 /*
266 * Check that the CPU ID and CPU set index are interchangable.
267 */
268 iCpuSet = RTMpCpuIdToSetIndex(idCpu);
269 if ((RTCPUID)iCpuSet == idCpu)
270 {
271 AssertCompile(RT_IS_POWER_OF_TWO(RTCPUSET_MAX_CPUS));
272 if ( iCpuSet >= 0
273 && iCpuSet < RTCPUSET_MAX_CPUS
274 && RT_IS_POWER_OF_TWO(RTCPUSET_MAX_CPUS))
275 {
276 PSUPGIPCPU pGipCpu = SUPGetGipCpuBySetIndex(pGip, iCpuSet);
277
278 /*
279 * Check whether the IDTR.LIMIT contains a CPU number.
280 */
281#ifdef RT_ARCH_X86
282 uint16_t const cbIdt = sizeof(X86DESC64SYSTEM) * 256;
283#else
284 uint16_t const cbIdt = sizeof(X86DESCGATE) * 256;
285#endif
286 RTIDTR Idtr;
287 ASMGetIDTR(&Idtr);
288 if (Idtr.cbIdt >= cbIdt)
289 {
290 uint32_t uTmp = Idtr.cbIdt - cbIdt;
291 uTmp &= RTCPUSET_MAX_CPUS - 1;
292 if (uTmp == idCpu)
293 {
294 RTIDTR Idtr2;
295 ASMGetIDTR(&Idtr2);
296 if (Idtr2.cbIdt == Idtr.cbIdt)
297 fSupported |= SUPGIPGETCPU_IDTR_LIMIT_MASK_MAX_SET_CPUS;
298 }
299 }
300
301 /*
302 * Check whether RDTSCP is an option.
303 */
304 if (ASMHasCpuId())
305 {
306 if ( ASMIsValidExtRange(ASMCpuId_EAX(UINT32_C(0x80000000)))
307 && (ASMCpuId_EDX(UINT32_C(0x80000001)) & X86_CPUID_EXT_FEATURE_EDX_RDTSCP) )
308 {
309 uint32_t uAux;
310 ASMReadTscWithAux(&uAux);
311 if ((uAux & (RTCPUSET_MAX_CPUS - 1)) == idCpu)
312 {
313 ASMNopPause();
314 ASMReadTscWithAux(&uAux);
315 if ((uAux & (RTCPUSET_MAX_CPUS - 1)) == idCpu)
316 fSupported |= SUPGIPGETCPU_RDTSCP_MASK_MAX_SET_CPUS;
317 }
318
319 if (pGipCpu)
320 {
321 uint32_t const uGroupedAux = (uint8_t)pGipCpu->iCpuGroupMember | ((uint32_t)pGipCpu->iCpuGroup << 8);
322 if ( (uAux & UINT16_MAX) == uGroupedAux
323 && pGipCpu->iCpuGroupMember <= UINT8_MAX)
324 {
325 ASMNopPause();
326 ASMReadTscWithAux(&uAux);
327 if ((uAux & UINT16_MAX) == uGroupedAux)
328 fSupported |= SUPGIPGETCPU_RDTSCP_GROUP_IN_CH_NUMBER_IN_CL;
329 }
330 }
331 }
332 }
333 }
334 }
335
336 /*
337 * Check that the APIC ID is unique.
338 */
339 idApic = ASMGetApicId();
340 if (RT_LIKELY( idApic < RT_ELEMENTS(pGip->aiCpuFromApicId)
341 && !ASMAtomicBitTestAndSet(pState->bmApicId, idApic)))
342 fSupported |= SUPGIPGETCPU_APIC_ID;
343 else
344 {
345 AssertCompile(sizeof(pState->bmApicId) * 8 == RT_ELEMENTS(pGip->aiCpuFromApicId));
346 ASMAtomicCmpXchgU32(&pState->idCpuProblem, idCpu, NIL_RTCPUID);
347 LogRel(("supdrvGipDetectGetGipCpuCallback: idCpu=%#x iCpuSet=%d idApic=%#x - duplicate APIC ID.\n",
348 idCpu, iCpuSet, idApic));
349 }
350
351 /*
352 * Check that the iCpuSet is within the expected range.
353 */
354 if (RT_UNLIKELY( iCpuSet < 0
355 || (unsigned)iCpuSet >= RTCPUSET_MAX_CPUS
356 || (unsigned)iCpuSet >= RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)))
357 {
358 ASMAtomicCmpXchgU32(&pState->idCpuProblem, idCpu, NIL_RTCPUID);
359 LogRel(("supdrvGipDetectGetGipCpuCallback: idCpu=%#x iCpuSet=%d idApic=%#x - CPU set index is out of range.\n",
360 idCpu, iCpuSet, idApic));
361 }
362 else
363 {
364 RTCPUID idCpu2 = RTMpCpuIdFromSetIndex(iCpuSet);
365 if (RT_UNLIKELY(idCpu2 != idCpu))
366 {
367 ASMAtomicCmpXchgU32(&pState->idCpuProblem, idCpu, NIL_RTCPUID);
368 LogRel(("supdrvGipDetectGetGipCpuCallback: idCpu=%#x iCpuSet=%d idApic=%#x - CPU id/index roundtrip problem: %#x\n",
369 idCpu, iCpuSet, idApic, idCpu2));
370 }
371 }
372
373 /*
374 * Update the supported feature mask before we return.
375 */
376 ASMAtomicAndU32(&pState->fSupported, fSupported);
377
378 NOREF(pvUser2);
379}
380
381
382/**
383 * Increase the timer freqency on hosts where this is possible (NT).
384 *
385 * The idea is that more interrupts is better for us... Also, it's better than
386 * we increase the timer frequence, because we might end up getting inaccurate
387 * callbacks if someone else does it.
388 *
389 * @param pDevExt Sets u32SystemTimerGranularityGrant if increased.
390 */
391static void supdrvGipRequestHigherTimerFrequencyFromSystem(PSUPDRVDEVEXT pDevExt)
392{
393 if (pDevExt->u32SystemTimerGranularityGrant == 0)
394 {
395 uint32_t u32SystemResolution;
396 if ( RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 976563 /* 1024 HZ */, &u32SystemResolution))
397 || RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 1000000 /* 1000 HZ */, &u32SystemResolution))
398 || RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 1953125 /* 512 HZ */, &u32SystemResolution))
399 || RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 2000000 /* 500 HZ */, &u32SystemResolution))
400 )
401 {
402#if 0 /* def VBOX_STRICT - this is somehow triggers bogus assertions on windows 10 */
403 uint32_t u32After = RTTimerGetSystemGranularity();
404 AssertMsg(u32After <= u32SystemResolution, ("u32After=%u u32SystemResolution=%u\n", u32After, u32SystemResolution));
405#endif
406 pDevExt->u32SystemTimerGranularityGrant = u32SystemResolution;
407 }
408 }
409}
410
411
412/**
413 * Undoes supdrvGipRequestHigherTimerFrequencyFromSystem.
414 *
415 * @param pDevExt Clears u32SystemTimerGranularityGrant.
416 */
417static void supdrvGipReleaseHigherTimerFrequencyFromSystem(PSUPDRVDEVEXT pDevExt)
418{
419 if (pDevExt->u32SystemTimerGranularityGrant)
420 {
421 int rc2 = RTTimerReleaseSystemGranularity(pDevExt->u32SystemTimerGranularityGrant);
422 AssertRC(rc2);
423 pDevExt->u32SystemTimerGranularityGrant = 0;
424 }
425}
426
427
428/**
429 * Maps the GIP into userspace and/or get the physical address of the GIP.
430 *
431 * @returns IPRT status code.
432 * @param pSession Session to which the GIP mapping should belong.
433 * @param ppGipR3 Where to store the address of the ring-3 mapping. (optional)
434 * @param pHCPhysGip Where to store the physical address. (optional)
435 *
436 * @remark There is no reference counting on the mapping, so one call to this function
437 * count globally as one reference. One call to SUPR0GipUnmap() is will unmap GIP
438 * and remove the session as a GIP user.
439 */
440SUPR0DECL(int) SUPR0GipMap(PSUPDRVSESSION pSession, PRTR3PTR ppGipR3, PRTHCPHYS pHCPhysGip)
441{
442 int rc;
443 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
444 RTR3PTR pGipR3 = NIL_RTR3PTR;
445 RTHCPHYS HCPhys = NIL_RTHCPHYS;
446 LogFlow(("SUPR0GipMap: pSession=%p ppGipR3=%p pHCPhysGip=%p\n", pSession, ppGipR3, pHCPhysGip));
447
448 /*
449 * Validate
450 */
451 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
452 AssertPtrNullReturn(ppGipR3, VERR_INVALID_POINTER);
453 AssertPtrNullReturn(pHCPhysGip, VERR_INVALID_POINTER);
454
455#ifdef SUPDRV_USE_MUTEX_FOR_GIP
456 RTSemMutexRequest(pDevExt->mtxGip, RT_INDEFINITE_WAIT);
457#else
458 RTSemFastMutexRequest(pDevExt->mtxGip);
459#endif
460 if (pDevExt->pGip)
461 {
462 /*
463 * Map it?
464 */
465 rc = VINF_SUCCESS;
466 if (ppGipR3)
467 {
468 if (pSession->GipMapObjR3 == NIL_RTR0MEMOBJ)
469 rc = RTR0MemObjMapUser(&pSession->GipMapObjR3, pDevExt->GipMemObj, (RTR3PTR)-1, 0,
470 RTMEM_PROT_READ, NIL_RTR0PROCESS);
471 if (RT_SUCCESS(rc))
472 pGipR3 = RTR0MemObjAddressR3(pSession->GipMapObjR3);
473 }
474
475 /*
476 * Get physical address.
477 */
478 if (pHCPhysGip && RT_SUCCESS(rc))
479 HCPhys = pDevExt->HCPhysGip;
480
481 /*
482 * Reference globally.
483 */
484 if (!pSession->fGipReferenced && RT_SUCCESS(rc))
485 {
486 pSession->fGipReferenced = 1;
487 pDevExt->cGipUsers++;
488 if (pDevExt->cGipUsers == 1)
489 {
490 PSUPGLOBALINFOPAGE pGipR0 = pDevExt->pGip;
491 uint64_t u64NanoTS;
492
493 /*
494 * GIP starts/resumes updating again. On windows we bump the
495 * host timer frequency to make sure we don't get stuck in guest
496 * mode and to get better timer (and possibly clock) accuracy.
497 */
498 LogFlow(("SUPR0GipMap: Resumes GIP updating\n"));
499
500 supdrvGipRequestHigherTimerFrequencyFromSystem(pDevExt);
501
502 /*
503 * document me
504 */
505 if (pGipR0->aCPUs[0].u32TransactionId != 2 /* not the first time */)
506 {
507 unsigned i;
508 for (i = 0; i < pGipR0->cCpus; i++)
509 ASMAtomicUoWriteU32(&pGipR0->aCPUs[i].u32TransactionId,
510 (pGipR0->aCPUs[i].u32TransactionId + GIP_UPDATEHZ_RECALC_FREQ * 2)
511 & ~(GIP_UPDATEHZ_RECALC_FREQ * 2 - 1));
512 ASMAtomicWriteU64(&pGipR0->u64NanoTSLastUpdateHz, 0);
513 }
514
515 /*
516 * document me
517 */
518 u64NanoTS = RTTimeSystemNanoTS() - pGipR0->u32UpdateIntervalNS;
519 if ( pGipR0->u32Mode == SUPGIPMODE_INVARIANT_TSC
520 || pGipR0->u32Mode == SUPGIPMODE_SYNC_TSC
521 || RTMpGetOnlineCount() == 1)
522 supdrvGipReInitCpu(&pGipR0->aCPUs[0], u64NanoTS);
523 else
524 RTMpOnAll(supdrvGipReInitCpuCallback, pGipR0, &u64NanoTS);
525
526 /*
527 * Detect alternative ways to figure the CPU ID in ring-3 and
528 * raw-mode context. Check the sanity of the APIC IDs, CPU IDs,
529 * and CPU set indexes while we're at it.
530 */
531 if (RT_SUCCESS(rc))
532 {
533 SUPDRVGIPDETECTGETCPU DetectState;
534 RT_BZERO((void *)&DetectState.bmApicId, sizeof(DetectState.bmApicId));
535 DetectState.fSupported = UINT32_MAX;
536 DetectState.idCpuProblem = NIL_RTCPUID;
537 rc = RTMpOnAll(supdrvGipDetectGetGipCpuCallback, &DetectState, pGipR0);
538 if (DetectState.idCpuProblem == NIL_RTCPUID)
539 {
540 if ( DetectState.fSupported != UINT32_MAX
541 && DetectState.fSupported != 0)
542 {
543 if (pGipR0->fGetGipCpu != DetectState.fSupported)
544 {
545 pGipR0->fGetGipCpu = DetectState.fSupported;
546 LogRel(("SUPR0GipMap: fGetGipCpu=%#x\n", DetectState.fSupported));
547 }
548 }
549 else
550 {
551 LogRel(("SUPR0GipMap: No supported ways of getting the APIC ID or CPU number in ring-3! (%#x)\n",
552 DetectState.fSupported));
553 rc = VERR_UNSUPPORTED_CPU;
554 }
555 }
556 else
557 {
558 LogRel(("SUPR0GipMap: APIC ID, CPU ID or CPU set index problem detected on CPU #%u (%#x)!\n",
559 DetectState.idCpuProblem, DetectState.idCpuProblem));
560 rc = VERR_INVALID_CPU_ID;
561 }
562 }
563
564 /*
565 * Start the GIP timer if all is well..
566 */
567 if (RT_SUCCESS(rc))
568 {
569#ifndef DO_NOT_START_GIP
570 rc = RTTimerStart(pDevExt->pGipTimer, 0 /* fire ASAP */); AssertRC(rc);
571#endif
572 rc = VINF_SUCCESS;
573 }
574
575 /*
576 * Bail out on error.
577 */
578 if (RT_FAILURE(rc))
579 {
580 LogRel(("SUPR0GipMap: failed rc=%Rrc\n", rc));
581 pDevExt->cGipUsers = 0;
582 pSession->fGipReferenced = 0;
583 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
584 {
585 int rc2 = RTR0MemObjFree(pSession->GipMapObjR3, false); AssertRC(rc2);
586 if (RT_SUCCESS(rc2))
587 pSession->GipMapObjR3 = NIL_RTR0MEMOBJ;
588 }
589 HCPhys = NIL_RTHCPHYS;
590 pGipR3 = NIL_RTR3PTR;
591 }
592 }
593 }
594 }
595 else
596 {
597 rc = VERR_GENERAL_FAILURE;
598 Log(("SUPR0GipMap: GIP is not available!\n"));
599 }
600#ifdef SUPDRV_USE_MUTEX_FOR_GIP
601 RTSemMutexRelease(pDevExt->mtxGip);
602#else
603 RTSemFastMutexRelease(pDevExt->mtxGip);
604#endif
605
606 /*
607 * Write returns.
608 */
609 if (pHCPhysGip)
610 *pHCPhysGip = HCPhys;
611 if (ppGipR3)
612 *ppGipR3 = pGipR3;
613
614#ifdef DEBUG_DARWIN_GIP
615 OSDBGPRINT(("SUPR0GipMap: returns %d *pHCPhysGip=%lx pGipR3=%p\n", rc, (unsigned long)HCPhys, (void *)pGipR3));
616#else
617 LogFlow(( "SUPR0GipMap: returns %d *pHCPhysGip=%lx pGipR3=%p\n", rc, (unsigned long)HCPhys, (void *)pGipR3));
618#endif
619 return rc;
620}
621
622
623/**
624 * Unmaps any user mapping of the GIP and terminates all GIP access
625 * from this session.
626 *
627 * @returns IPRT status code.
628 * @param pSession Session to which the GIP mapping should belong.
629 */
630SUPR0DECL(int) SUPR0GipUnmap(PSUPDRVSESSION pSession)
631{
632 int rc = VINF_SUCCESS;
633 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
634#ifdef DEBUG_DARWIN_GIP
635 OSDBGPRINT(("SUPR0GipUnmap: pSession=%p pGip=%p GipMapObjR3=%p\n",
636 pSession,
637 pSession->GipMapObjR3 != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pSession->GipMapObjR3) : NULL,
638 pSession->GipMapObjR3));
639#else
640 LogFlow(("SUPR0GipUnmap: pSession=%p\n", pSession));
641#endif
642 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
643
644#ifdef SUPDRV_USE_MUTEX_FOR_GIP
645 RTSemMutexRequest(pDevExt->mtxGip, RT_INDEFINITE_WAIT);
646#else
647 RTSemFastMutexRequest(pDevExt->mtxGip);
648#endif
649
650 /*
651 * GIP test-mode session?
652 */
653 if ( pSession->fGipTestMode
654 && pDevExt->pGip)
655 {
656 supdrvGipSetFlags(pDevExt, pSession, 0, ~SUPGIP_FLAGS_TESTING_ENABLE);
657 Assert(!pSession->fGipTestMode);
658 }
659
660 /*
661 * Unmap anything?
662 */
663 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
664 {
665 rc = RTR0MemObjFree(pSession->GipMapObjR3, false);
666 AssertRC(rc);
667 if (RT_SUCCESS(rc))
668 pSession->GipMapObjR3 = NIL_RTR0MEMOBJ;
669 }
670
671 /*
672 * Dereference global GIP.
673 */
674 if (pSession->fGipReferenced && !rc)
675 {
676 pSession->fGipReferenced = 0;
677 if ( pDevExt->cGipUsers > 0
678 && !--pDevExt->cGipUsers)
679 {
680 LogFlow(("SUPR0GipUnmap: Suspends GIP updating\n"));
681#ifndef DO_NOT_START_GIP
682 rc = RTTimerStop(pDevExt->pGipTimer); AssertRC(rc); rc = VINF_SUCCESS;
683#endif
684 supdrvGipReleaseHigherTimerFrequencyFromSystem(pDevExt);
685 }
686 }
687
688#ifdef SUPDRV_USE_MUTEX_FOR_GIP
689 RTSemMutexRelease(pDevExt->mtxGip);
690#else
691 RTSemFastMutexRelease(pDevExt->mtxGip);
692#endif
693
694 return rc;
695}
696
697
698/**
699 * Gets the GIP pointer.
700 *
701 * @returns Pointer to the GIP or NULL.
702 */
703SUPDECL(PSUPGLOBALINFOPAGE) SUPGetGIP(void)
704{
705 return g_pSUPGlobalInfoPage;
706}
707
708
709
710
711
712/*
713 *
714 *
715 * GIP Initialization, Termination and CPU Offline / Online Related Code.
716 * GIP Initialization, Termination and CPU Offline / Online Related Code.
717 * GIP Initialization, Termination and CPU Offline / Online Related Code.
718 *
719 *
720 */
721
722/**
723 * Used by supdrvGipInitRefineInvariantTscFreqTimer and supdrvGipInitMeasureTscFreq
724 * to update the TSC frequency related GIP variables.
725 *
726 * @param pGip The GIP.
727 * @param nsElapsed The number of nanoseconds elapsed.
728 * @param cElapsedTscTicks The corresponding number of TSC ticks.
729 * @param iTick The tick number for debugging.
730 */
731static void supdrvGipInitSetCpuFreq(PSUPGLOBALINFOPAGE pGip, uint64_t nsElapsed, uint64_t cElapsedTscTicks, uint32_t iTick)
732{
733 /*
734 * Calculate the frequency.
735 */
736 uint64_t uCpuHz;
737 if ( cElapsedTscTicks < UINT64_MAX / RT_NS_1SEC
738 && nsElapsed < UINT32_MAX)
739 uCpuHz = ASMMultU64ByU32DivByU32(cElapsedTscTicks, RT_NS_1SEC, (uint32_t)nsElapsed);
740 else
741 {
742 RTUINT128U CpuHz, Tmp, Divisor;
743 CpuHz.s.Lo = CpuHz.s.Hi = 0;
744 RTUInt128MulU64ByU64(&Tmp, cElapsedTscTicks, RT_NS_1SEC_64);
745 RTUInt128Div(&CpuHz, &Tmp, RTUInt128AssignU64(&Divisor, nsElapsed));
746 uCpuHz = CpuHz.s.Lo;
747 }
748
749 /*
750 * Update the GIP.
751 */
752 ASMAtomicWriteU64(&pGip->u64CpuHz, uCpuHz);
753 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
754 {
755 ASMAtomicWriteU64(&pGip->aCPUs[0].u64CpuHz, uCpuHz);
756
757 /* For inspecting the frequency calcs using tstGIP-2, debugger or similar. */
758 if (iTick + 1 < pGip->cCpus)
759 ASMAtomicWriteU64(&pGip->aCPUs[iTick + 1].u64CpuHz, uCpuHz);
760 }
761}
762
763
764/**
765 * Timer callback function for TSC frequency refinement in invariant GIP mode.
766 *
767 * This is started during driver init and fires once
768 * GIP_TSC_REFINE_PERIOD_IN_SECS seconds later.
769 *
770 * @param pTimer The timer.
771 * @param pvUser Opaque pointer to the device instance data.
772 * @param iTick The timer tick.
773 */
774static DECLCALLBACK(void) supdrvGipInitRefineInvariantTscFreqTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
775{
776 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
777 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
778 RTCPUID idCpu;
779 uint64_t cNsElapsed;
780 uint64_t cTscTicksElapsed;
781 uint64_t nsNow;
782 uint64_t uTsc;
783 RTCCUINTREG fEFlags;
784
785 /* Paranoia. */
786 AssertReturnVoid(pGip);
787 AssertReturnVoid(pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC);
788
789 /*
790 * If we got a power event, stop the refinement process.
791 */
792 if (pDevExt->fInvTscRefinePowerEvent)
793 {
794 int rc = RTTimerStop(pTimer); AssertRC(rc);
795 return;
796 }
797
798 /*
799 * Read the TSC and time, noting which CPU we are on.
800 *
801 * Don't bother spinning until RTTimeSystemNanoTS changes, since on
802 * systems where it matters we're in a context where we cannot waste that
803 * much time (DPC watchdog, called from clock interrupt).
804 */
805 fEFlags = ASMIntDisableFlags();
806 uTsc = ASMReadTSC();
807 nsNow = RTTimeSystemNanoTS();
808 idCpu = RTMpCpuId();
809 ASMSetFlags(fEFlags);
810
811 cNsElapsed = nsNow - pDevExt->nsStartInvarTscRefine;
812 cTscTicksElapsed = uTsc - pDevExt->uTscStartInvarTscRefine;
813
814 /*
815 * If the above measurement was taken on a different CPU than the one we
816 * started the process on, cTscTicksElapsed will need to be adjusted with
817 * the TSC deltas of both the CPUs.
818 *
819 * We ASSUME that the delta calculation process takes less time than the
820 * TSC frequency refinement timer. If it doesn't, we'll complain and
821 * drop the frequency refinement.
822 *
823 * Note! We cannot entirely trust enmUseTscDelta here because it's
824 * downgraded after each delta calculation.
825 */
826 if ( idCpu != pDevExt->idCpuInvarTscRefine
827 && pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
828 {
829 uint32_t iStartCpuSet = RTMpCpuIdToSetIndex(pDevExt->idCpuInvarTscRefine);
830 uint32_t iStopCpuSet = RTMpCpuIdToSetIndex(idCpu);
831 uint16_t iStartGipCpu = iStartCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)
832 ? pGip->aiCpuFromCpuSetIdx[iStartCpuSet] : UINT16_MAX;
833 uint16_t iStopGipCpu = iStopCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)
834 ? pGip->aiCpuFromCpuSetIdx[iStopCpuSet] : UINT16_MAX;
835 int64_t iStartTscDelta = iStartGipCpu < pGip->cCpus ? pGip->aCPUs[iStartGipCpu].i64TSCDelta : INT64_MAX;
836 int64_t iStopTscDelta = iStopGipCpu < pGip->cCpus ? pGip->aCPUs[iStopGipCpu].i64TSCDelta : INT64_MAX;
837 if (RT_LIKELY(iStartTscDelta != INT64_MAX && iStopTscDelta != INT64_MAX))
838 {
839 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_PRACTICALLY_ZERO)
840 {
841 /* cTscTicksElapsed = (uTsc - iStopTscDelta) - (pDevExt->uTscStartInvarTscRefine - iStartTscDelta); */
842 cTscTicksElapsed += iStartTscDelta - iStopTscDelta;
843 }
844 }
845 /*
846 * Allow 5 times the refinement period to elapse before we give up on the TSC delta
847 * calculations.
848 */
849 else if (cNsElapsed > GIP_TSC_REFINE_PERIOD_IN_SECS * 5 * RT_NS_1SEC_64)
850 {
851 SUPR0Printf("vboxdrv: Failed to refine invariant TSC frequency because deltas are unavailable after %u (%u) seconds\n",
852 (uint32_t)(cNsElapsed / RT_NS_1SEC), GIP_TSC_REFINE_PERIOD_IN_SECS);
853 SUPR0Printf("vboxdrv: start: %u, %u, %#llx stop: %u, %u, %#llx\n",
854 iStartCpuSet, iStartGipCpu, iStartTscDelta, iStopCpuSet, iStopGipCpu, iStopTscDelta);
855 int rc = RTTimerStop(pTimer); AssertRC(rc);
856 return;
857 }
858 }
859
860 /*
861 * Calculate and update the CPU frequency variables in GIP.
862 *
863 * If there is a GIP user already and we've already refined the frequency
864 * a couple of times, don't update it as we want a stable frequency value
865 * for all VMs.
866 */
867 if ( pDevExt->cGipUsers == 0
868 || cNsElapsed < RT_NS_1SEC * 2)
869 {
870 supdrvGipInitSetCpuFreq(pGip, cNsElapsed, cTscTicksElapsed, (uint32_t)iTick);
871
872 /*
873 * Stop the timer once we've reached the defined refinement period.
874 */
875 if (cNsElapsed > GIP_TSC_REFINE_PERIOD_IN_SECS * RT_NS_1SEC_64)
876 {
877 int rc = RTTimerStop(pTimer);
878 AssertRC(rc);
879 }
880 }
881 else
882 {
883 int rc = RTTimerStop(pTimer);
884 AssertRC(rc);
885 }
886}
887
888
889/**
890 * @callback_method_impl{FNRTPOWERNOTIFICATION}
891 */
892static DECLCALLBACK(void) supdrvGipPowerNotificationCallback(RTPOWEREVENT enmEvent, void *pvUser)
893{
894 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
895 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
896
897 /*
898 * If the TSC frequency refinement timer is running, we need to cancel it so it
899 * doesn't screw up the frequency after a long suspend.
900 *
901 * Recalculate all TSC-deltas on host resume as it may have changed, seen
902 * on Windows 7 running on the Dell Optiplex Intel Core i5-3570.
903 */
904 if (enmEvent == RTPOWEREVENT_RESUME)
905 {
906 ASMAtomicWriteBool(&pDevExt->fInvTscRefinePowerEvent, true);
907 if ( RT_LIKELY(pGip)
908 && pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED
909 && !supdrvOSAreCpusOfflinedOnSuspend())
910 {
911#ifdef SUPDRV_USE_TSC_DELTA_THREAD
912 supdrvTscDeltaThreadStartMeasurement(pDevExt, true /* fForceAll */);
913#else
914 RTCpuSetCopy(&pDevExt->TscDeltaCpuSet, &pGip->OnlineCpuSet);
915 supdrvTscMeasureInitialDeltas(pDevExt);
916#endif
917 }
918 }
919 else if (enmEvent == RTPOWEREVENT_SUSPEND)
920 ASMAtomicWriteBool(&pDevExt->fInvTscRefinePowerEvent, true);
921}
922
923
924/**
925 * Start the TSC-frequency refinment timer for the invariant TSC GIP mode.
926 *
927 * We cannot use this in the synchronous and asynchronous tsc GIP modes because
928 * the CPU may change the TSC frequence between now and when the timer fires
929 * (supdrvInitAsyncRefineTscTimer).
930 *
931 * @param pDevExt Pointer to the device instance data.
932 */
933static void supdrvGipInitStartTimerForRefiningInvariantTscFreq(PSUPDRVDEVEXT pDevExt)
934{
935 uint64_t u64NanoTS;
936 RTCCUINTREG fEFlags;
937 int rc;
938
939 /*
940 * Register a power management callback.
941 */
942 pDevExt->fInvTscRefinePowerEvent = false;
943 rc = RTPowerNotificationRegister(supdrvGipPowerNotificationCallback, pDevExt);
944 AssertRC(rc); /* ignore */
945
946 /*
947 * Record the TSC and NanoTS as the starting anchor point for refinement
948 * of the TSC. We try get as close to a clock tick as possible on systems
949 * which does not provide high resolution time.
950 */
951 u64NanoTS = RTTimeSystemNanoTS();
952 while (RTTimeSystemNanoTS() == u64NanoTS)
953 ASMNopPause();
954
955 fEFlags = ASMIntDisableFlags();
956 pDevExt->uTscStartInvarTscRefine = ASMReadTSC();
957 pDevExt->nsStartInvarTscRefine = RTTimeSystemNanoTS();
958 pDevExt->idCpuInvarTscRefine = RTMpCpuId();
959 ASMSetFlags(fEFlags);
960
961 /*
962 * Create a timer that runs on the same CPU so we won't have a depencency
963 * on the TSC-delta and can run in parallel to it. On systems that does not
964 * implement CPU specific timers we'll apply deltas in the timer callback,
965 * just like we do for CPUs going offline.
966 *
967 * The longer the refinement interval the better the accuracy, at least in
968 * theory. If it's too long though, ring-3 may already be starting its
969 * first VMs before we're done. On most systems we will be loading the
970 * support driver during boot and VMs won't be started for a while yet,
971 * it is really only a problem during development (especially with
972 * on-demand driver starting on windows).
973 *
974 * To avoid wasting time doing a long supdrvGipInitMeasureTscFreq() call
975 * to calculate the frequency during driver loading, the timer is set
976 * to fire after 200 ms the first time. It will then reschedule itself
977 * to fire every second until GIP_TSC_REFINE_PERIOD_IN_SECS has been
978 * reached or it notices that there is a user land client with GIP
979 * mapped (we want a stable frequency for all VMs).
980 */
981 rc = RTTimerCreateEx(&pDevExt->pInvarTscRefineTimer, RT_NS_1SEC,
982 RTTIMER_FLAGS_CPU(RTMpCpuIdToSetIndex(pDevExt->idCpuInvarTscRefine)),
983 supdrvGipInitRefineInvariantTscFreqTimer, pDevExt);
984 if (RT_SUCCESS(rc))
985 {
986 rc = RTTimerStart(pDevExt->pInvarTscRefineTimer, 2*RT_NS_100MS);
987 if (RT_SUCCESS(rc))
988 return;
989 RTTimerDestroy(pDevExt->pInvarTscRefineTimer);
990 }
991
992 if (rc == VERR_CPU_OFFLINE || rc == VERR_NOT_SUPPORTED)
993 {
994 rc = RTTimerCreateEx(&pDevExt->pInvarTscRefineTimer, RT_NS_1SEC, RTTIMER_FLAGS_CPU_ANY,
995 supdrvGipInitRefineInvariantTscFreqTimer, pDevExt);
996 if (RT_SUCCESS(rc))
997 {
998 rc = RTTimerStart(pDevExt->pInvarTscRefineTimer, 2*RT_NS_100MS);
999 if (RT_SUCCESS(rc))
1000 return;
1001 RTTimerDestroy(pDevExt->pInvarTscRefineTimer);
1002 }
1003 }
1004
1005 pDevExt->pInvarTscRefineTimer = NULL;
1006 OSDBGPRINT(("vboxdrv: Failed to create or start TSC frequency refinement timer: rc=%Rrc\n", rc));
1007}
1008
1009
1010/**
1011 * @callback_method_impl{PFNRTMPWORKER,
1012 * RTMpOnSpecific callback for reading TSC and time on the CPU we started
1013 * the measurements on.}
1014 */
1015DECLCALLBACK(void) supdrvGipInitReadTscAndNanoTsOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1016{
1017 RTCCUINTREG fEFlags = ASMIntDisableFlags();
1018 uint64_t *puTscStop = (uint64_t *)pvUser1;
1019 uint64_t *pnsStop = (uint64_t *)pvUser2;
1020 RT_NOREF1(idCpu);
1021
1022 *puTscStop = ASMReadTSC();
1023 *pnsStop = RTTimeSystemNanoTS();
1024
1025 ASMSetFlags(fEFlags);
1026}
1027
1028
1029/**
1030 * Measures the TSC frequency of the system.
1031 *
1032 * The TSC frequency can vary on systems which are not reported as invariant.
1033 * On such systems the object of this function is to find out what the nominal,
1034 * maximum TSC frequency under 'normal' CPU operation.
1035 *
1036 * @returns VBox status code.
1037 * @param pGip Pointer to the GIP.
1038 * @param fRough Set if we're doing the rough calculation that the
1039 * TSC measuring code needs, where accuracy isn't all
1040 * that important (too high is better than too low).
1041 * When clear we try for best accuracy that we can
1042 * achieve in reasonably short time.
1043 */
1044static int supdrvGipInitMeasureTscFreq(PSUPGLOBALINFOPAGE pGip, bool fRough)
1045{
1046 uint32_t nsTimerIncr = RTTimerGetSystemGranularity();
1047 int cTriesLeft = fRough ? 4 : 2;
1048 while (cTriesLeft-- > 0)
1049 {
1050 RTCCUINTREG fEFlags;
1051 uint64_t nsStart;
1052 uint64_t nsStop;
1053 uint64_t uTscStart;
1054 uint64_t uTscStop;
1055 RTCPUID idCpuStart;
1056 RTCPUID idCpuStop;
1057
1058 /*
1059 * Synchronize with the host OS clock tick on systems without high
1060 * resolution time API (older Windows version for example).
1061 */
1062 nsStart = RTTimeSystemNanoTS();
1063 while (RTTimeSystemNanoTS() == nsStart)
1064 ASMNopPause();
1065
1066 /*
1067 * Read the TSC and current time, noting which CPU we're on.
1068 */
1069 fEFlags = ASMIntDisableFlags();
1070 uTscStart = ASMReadTSC();
1071 nsStart = RTTimeSystemNanoTS();
1072 idCpuStart = RTMpCpuId();
1073 ASMSetFlags(fEFlags);
1074
1075 /*
1076 * Delay for a while.
1077 */
1078 if (pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC)
1079 {
1080 /*
1081 * Sleep-wait since the TSC frequency is constant, it eases host load.
1082 * Shorter interval produces more variance in the frequency (esp. Windows).
1083 */
1084 uint64_t msElapsed = 0;
1085 uint64_t msDelay = ( ((fRough ? 16 : 200) * RT_NS_1MS + nsTimerIncr - 1) / nsTimerIncr * nsTimerIncr - RT_NS_100US )
1086 / RT_NS_1MS;
1087 do
1088 {
1089 RTThreadSleep((RTMSINTERVAL)(msDelay - msElapsed));
1090 nsStop = RTTimeSystemNanoTS();
1091 msElapsed = (nsStop - nsStart) / RT_NS_1MS;
1092 } while (msElapsed < msDelay);
1093
1094 while (RTTimeSystemNanoTS() == nsStop)
1095 ASMNopPause();
1096 }
1097 else
1098 {
1099 /*
1100 * Busy-wait keeping the frequency up.
1101 */
1102 do
1103 {
1104 ASMNopPause();
1105 nsStop = RTTimeSystemNanoTS();
1106 } while (nsStop - nsStart < RT_NS_100MS);
1107 }
1108
1109 /*
1110 * Read the TSC and time again.
1111 */
1112 fEFlags = ASMIntDisableFlags();
1113 uTscStop = ASMReadTSC();
1114 nsStop = RTTimeSystemNanoTS();
1115 idCpuStop = RTMpCpuId();
1116 ASMSetFlags(fEFlags);
1117
1118 /*
1119 * If the CPU changes, things get a bit complicated and what we
1120 * can get away with depends on the GIP mode / TSC reliability.
1121 */
1122 if (idCpuStop != idCpuStart)
1123 {
1124 bool fDoXCall = false;
1125
1126 /*
1127 * Synchronous TSC mode: we're probably fine as it's unlikely
1128 * that we were rescheduled because of TSC throttling or power
1129 * management reasons, so just go ahead.
1130 */
1131 if (pGip->u32Mode == SUPGIPMODE_SYNC_TSC)
1132 {
1133 /* Probably ok, maybe we should retry once?. */
1134 Assert(pGip->enmUseTscDelta == SUPGIPUSETSCDELTA_NOT_APPLICABLE);
1135 }
1136 /*
1137 * If we're just doing the rough measurement, do the cross call and
1138 * get on with things (we don't have deltas!).
1139 */
1140 else if (fRough)
1141 fDoXCall = true;
1142 /*
1143 * Invariant TSC mode: It doesn't matter if we have delta available
1144 * for both CPUs. That is not something we can assume at this point.
1145 *
1146 * Note! We cannot necessarily trust enmUseTscDelta here because it's
1147 * downgraded after each delta calculation and the delta
1148 * calculations may not be complete yet.
1149 */
1150 else if (pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC)
1151 {
1152/** @todo This section of code is never reached atm, consider dropping it later on... */
1153 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
1154 {
1155 uint32_t iStartCpuSet = RTMpCpuIdToSetIndex(idCpuStart);
1156 uint32_t iStopCpuSet = RTMpCpuIdToSetIndex(idCpuStop);
1157 uint16_t iStartGipCpu = iStartCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)
1158 ? pGip->aiCpuFromCpuSetIdx[iStartCpuSet] : UINT16_MAX;
1159 uint16_t iStopGipCpu = iStopCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)
1160 ? pGip->aiCpuFromCpuSetIdx[iStopCpuSet] : UINT16_MAX;
1161 int64_t iStartTscDelta = iStartGipCpu < pGip->cCpus ? pGip->aCPUs[iStartGipCpu].i64TSCDelta : INT64_MAX;
1162 int64_t iStopTscDelta = iStopGipCpu < pGip->cCpus ? pGip->aCPUs[iStopGipCpu].i64TSCDelta : INT64_MAX;
1163 if (RT_LIKELY(iStartTscDelta != INT64_MAX && iStopTscDelta != INT64_MAX))
1164 {
1165 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_PRACTICALLY_ZERO)
1166 {
1167 uTscStart -= iStartTscDelta;
1168 uTscStop -= iStopTscDelta;
1169 }
1170 }
1171 /*
1172 * Invalid CPU indexes are not caused by online/offline races, so
1173 * we have to trigger driver load failure if that happens as GIP
1174 * and IPRT assumptions are busted on this system.
1175 */
1176 else if (iStopGipCpu >= pGip->cCpus || iStartGipCpu >= pGip->cCpus)
1177 {
1178 SUPR0Printf("vboxdrv: Unexpected CPU index in supdrvGipInitMeasureTscFreq.\n");
1179 SUPR0Printf("vboxdrv: start: %u, %u, %#llx stop: %u, %u, %#llx\n",
1180 iStartCpuSet, iStartGipCpu, iStartTscDelta, iStopCpuSet, iStopGipCpu, iStopTscDelta);
1181 return VERR_INVALID_CPU_INDEX;
1182 }
1183 /*
1184 * No valid deltas. We retry, if we're on our last retry
1185 * we do the cross call instead just to get a result. The
1186 * frequency will be refined in a few seconds anyway.
1187 */
1188 else if (cTriesLeft > 0)
1189 continue;
1190 else
1191 fDoXCall = true;
1192 }
1193 }
1194 /*
1195 * Asynchronous TSC mode: This is bad, as the reason we usually
1196 * use this mode is to deal with variable TSC frequencies and
1197 * deltas. So, we need to get the TSC from the same CPU as
1198 * started it, we also need to keep that CPU busy. So, retry
1199 * and fall back to the cross call on the last attempt.
1200 */
1201 else
1202 {
1203 Assert(pGip->u32Mode == SUPGIPMODE_ASYNC_TSC);
1204 if (cTriesLeft > 0)
1205 continue;
1206 fDoXCall = true;
1207 }
1208
1209 if (fDoXCall)
1210 {
1211 /*
1212 * Try read the TSC and timestamp on the start CPU.
1213 */
1214 int rc = RTMpOnSpecific(idCpuStart, supdrvGipInitReadTscAndNanoTsOnCpu, &uTscStop, &nsStop);
1215 if (RT_FAILURE(rc) && (!fRough || cTriesLeft > 0))
1216 continue;
1217 }
1218 }
1219
1220 /*
1221 * Calculate the TSC frequency and update it (shared with the refinement timer).
1222 */
1223 supdrvGipInitSetCpuFreq(pGip, nsStop - nsStart, uTscStop - uTscStart, 0);
1224 return VINF_SUCCESS;
1225 }
1226
1227 Assert(!fRough);
1228 return VERR_SUPDRV_TSC_FREQ_MEASUREMENT_FAILED;
1229}
1230
1231
1232/**
1233 * Finds our (@a idCpu) entry, or allocates a new one if not found.
1234 *
1235 * @returns Index of the CPU in the cache set.
1236 * @param pGip The GIP.
1237 * @param idCpu The CPU ID.
1238 */
1239static uint32_t supdrvGipFindOrAllocCpuIndexForCpuId(PSUPGLOBALINFOPAGE pGip, RTCPUID idCpu)
1240{
1241 uint32_t i, cTries;
1242
1243 /*
1244 * ASSUMES that CPU IDs are constant.
1245 */
1246 for (i = 0; i < pGip->cCpus; i++)
1247 if (pGip->aCPUs[i].idCpu == idCpu)
1248 return i;
1249
1250 cTries = 0;
1251 do
1252 {
1253 for (i = 0; i < pGip->cCpus; i++)
1254 {
1255 bool fRc;
1256 ASMAtomicCmpXchgSize(&pGip->aCPUs[i].idCpu, idCpu, NIL_RTCPUID, fRc);
1257 if (fRc)
1258 return i;
1259 }
1260 } while (cTries++ < 32);
1261 AssertReleaseFailed();
1262 return i - 1;
1263}
1264
1265
1266/**
1267 * The calling CPU should be accounted as online, update GIP accordingly.
1268 *
1269 * This is used by supdrvGipCreate() as well as supdrvGipMpEvent().
1270 *
1271 * @param pDevExt The device extension.
1272 * @param idCpu The CPU ID.
1273 */
1274static void supdrvGipMpEventOnlineOrInitOnCpu(PSUPDRVDEVEXT pDevExt, RTCPUID idCpu)
1275{
1276 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
1277 int iCpuSet = 0;
1278 uint16_t idApic = UINT16_MAX;
1279 uint32_t i = 0;
1280 uint64_t u64NanoTS = 0;
1281
1282 AssertPtrReturnVoid(pGip);
1283 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1284 AssertRelease(idCpu == RTMpCpuId());
1285 Assert(pGip->cPossibleCpus == RTMpGetCount());
1286
1287 /*
1288 * Do this behind a spinlock with interrupts disabled as this can fire
1289 * on all CPUs simultaneously, see @bugref{6110}.
1290 */
1291 RTSpinlockAcquire(pDevExt->hGipSpinlock);
1292
1293 /*
1294 * Update the globals.
1295 */
1296 ASMAtomicWriteU16(&pGip->cPresentCpus, RTMpGetPresentCount());
1297 ASMAtomicWriteU16(&pGip->cOnlineCpus, RTMpGetOnlineCount());
1298 iCpuSet = RTMpCpuIdToSetIndex(idCpu);
1299 if (iCpuSet >= 0)
1300 {
1301 Assert(RTCpuSetIsMemberByIndex(&pGip->PossibleCpuSet, iCpuSet));
1302 RTCpuSetAddByIndex(&pGip->OnlineCpuSet, iCpuSet);
1303 RTCpuSetAddByIndex(&pGip->PresentCpuSet, iCpuSet);
1304 }
1305
1306 /*
1307 * Update the entry.
1308 */
1309 u64NanoTS = RTTimeSystemNanoTS() - pGip->u32UpdateIntervalNS;
1310 i = supdrvGipFindOrAllocCpuIndexForCpuId(pGip, idCpu);
1311
1312 supdrvGipInitCpu(pGip, &pGip->aCPUs[i], u64NanoTS, pGip->u64CpuHz);
1313
1314 idApic = ASMGetApicId();
1315 ASMAtomicWriteU16(&pGip->aCPUs[i].idApic, idApic);
1316 ASMAtomicWriteS16(&pGip->aCPUs[i].iCpuSet, (int16_t)iCpuSet);
1317 ASMAtomicWriteSize(&pGip->aCPUs[i].idCpu, idCpu);
1318
1319 pGip->aCPUs[i].iCpuGroup = 0;
1320 pGip->aCPUs[i].iCpuGroupMember = iCpuSet;
1321#ifdef RT_OS_WINDOWS
1322 pGip->aCPUs[i].iCpuGroup = supdrvOSGipGetGroupFromCpu(pDevExt, idCpu, &pGip->aCPUs[i].iCpuGroupMember);
1323#endif
1324
1325 /*
1326 * Update the APIC ID and CPU set index mappings.
1327 */
1328 ASMAtomicWriteU16(&pGip->aiCpuFromApicId[idApic], i);
1329 ASMAtomicWriteU16(&pGip->aiCpuFromCpuSetIdx[iCpuSet], i);
1330
1331 /* Add this CPU to this set of CPUs we need to calculate the TSC-delta for. */
1332 RTCpuSetAddByIndex(&pDevExt->TscDeltaCpuSet, RTMpCpuIdToSetIndex(idCpu));
1333
1334 /* Update the Mp online/offline counter. */
1335 ASMAtomicIncU32(&pDevExt->cMpOnOffEvents);
1336
1337 /* Commit it. */
1338 ASMAtomicWriteSize(&pGip->aCPUs[i].enmState, SUPGIPCPUSTATE_ONLINE);
1339
1340 RTSpinlockRelease(pDevExt->hGipSpinlock);
1341}
1342
1343
1344/**
1345 * RTMpOnSpecific callback wrapper for supdrvGipMpEventOnlineOrInitOnCpu().
1346 *
1347 * @param idCpu The CPU ID we are running on.
1348 * @param pvUser1 Opaque pointer to the device instance data.
1349 * @param pvUser2 Not used.
1350 */
1351static DECLCALLBACK(void) supdrvGipMpEventOnlineCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1352{
1353 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser1;
1354 NOREF(pvUser2);
1355 supdrvGipMpEventOnlineOrInitOnCpu(pDevExt, idCpu);
1356}
1357
1358
1359/**
1360 * The CPU should be accounted as offline, update the GIP accordingly.
1361 *
1362 * This is used by supdrvGipMpEvent.
1363 *
1364 * @param pDevExt The device extension.
1365 * @param idCpu The CPU ID.
1366 */
1367static void supdrvGipMpEventOffline(PSUPDRVDEVEXT pDevExt, RTCPUID idCpu)
1368{
1369 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
1370 int iCpuSet;
1371 unsigned i;
1372
1373 AssertPtrReturnVoid(pGip);
1374 RTSpinlockAcquire(pDevExt->hGipSpinlock);
1375
1376 iCpuSet = RTMpCpuIdToSetIndex(idCpu);
1377 AssertReturnVoid(iCpuSet >= 0);
1378
1379 i = pGip->aiCpuFromCpuSetIdx[iCpuSet];
1380 AssertReturnVoid(i < pGip->cCpus);
1381 AssertReturnVoid(pGip->aCPUs[i].idCpu == idCpu);
1382
1383 Assert(RTCpuSetIsMemberByIndex(&pGip->PossibleCpuSet, iCpuSet));
1384 RTCpuSetDelByIndex(&pGip->OnlineCpuSet, iCpuSet);
1385
1386 /* Update the Mp online/offline counter. */
1387 ASMAtomicIncU32(&pDevExt->cMpOnOffEvents);
1388
1389 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
1390 {
1391 /* Reset the TSC delta, we will recalculate it lazily. */
1392 ASMAtomicWriteS64(&pGip->aCPUs[i].i64TSCDelta, INT64_MAX);
1393 /* Remove this CPU from the set of CPUs that we have obtained the TSC deltas. */
1394 RTCpuSetDelByIndex(&pDevExt->TscDeltaObtainedCpuSet, iCpuSet);
1395 }
1396
1397 /* Commit it. */
1398 ASMAtomicWriteSize(&pGip->aCPUs[i].enmState, SUPGIPCPUSTATE_OFFLINE);
1399
1400 RTSpinlockRelease(pDevExt->hGipSpinlock);
1401}
1402
1403
1404/**
1405 * Multiprocessor event notification callback.
1406 *
1407 * This is used to make sure that the GIP master gets passed on to
1408 * another CPU. It also updates the associated CPU data.
1409 *
1410 * @param enmEvent The event.
1411 * @param idCpu The cpu it applies to.
1412 * @param pvUser Pointer to the device extension.
1413 */
1414static DECLCALLBACK(void) supdrvGipMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser)
1415{
1416 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
1417 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
1418
1419 if (pGip)
1420 {
1421 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1422 switch (enmEvent)
1423 {
1424 case RTMPEVENT_ONLINE:
1425 {
1426 RTThreadPreemptDisable(&PreemptState);
1427 if (idCpu == RTMpCpuId())
1428 {
1429 supdrvGipMpEventOnlineOrInitOnCpu(pDevExt, idCpu);
1430 RTThreadPreemptRestore(&PreemptState);
1431 }
1432 else
1433 {
1434 RTThreadPreemptRestore(&PreemptState);
1435 RTMpOnSpecific(idCpu, supdrvGipMpEventOnlineCallback, pDevExt, NULL /* pvUser2 */);
1436 }
1437
1438 /*
1439 * Recompute TSC-delta for the newly online'd CPU.
1440 */
1441 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
1442 {
1443#ifdef SUPDRV_USE_TSC_DELTA_THREAD
1444 supdrvTscDeltaThreadStartMeasurement(pDevExt, false /* fForceAll */);
1445#else
1446 uint32_t iCpu = supdrvGipFindOrAllocCpuIndexForCpuId(pGip, idCpu);
1447 supdrvTscMeasureDeltaOne(pDevExt, iCpu);
1448#endif
1449 }
1450 break;
1451 }
1452
1453 case RTMPEVENT_OFFLINE:
1454 supdrvGipMpEventOffline(pDevExt, idCpu);
1455 break;
1456 }
1457 }
1458
1459 /*
1460 * Make sure there is a master GIP.
1461 */
1462 if (enmEvent == RTMPEVENT_OFFLINE)
1463 {
1464 RTCPUID idGipMaster = ASMAtomicReadU32(&pDevExt->idGipMaster);
1465 if (idGipMaster == idCpu)
1466 {
1467 /*
1468 * The GIP master is going offline, find a new one.
1469 */
1470 bool fIgnored;
1471 unsigned i;
1472 RTCPUID idNewGipMaster = NIL_RTCPUID;
1473 RTCPUSET OnlineCpus;
1474 RTMpGetOnlineSet(&OnlineCpus);
1475
1476 for (i = 0; i < RTCPUSET_MAX_CPUS; i++)
1477 if (RTCpuSetIsMemberByIndex(&OnlineCpus, i))
1478 {
1479 RTCPUID idCurCpu = RTMpCpuIdFromSetIndex(i);
1480 if (idCurCpu != idGipMaster)
1481 {
1482 idNewGipMaster = idCurCpu;
1483 break;
1484 }
1485 }
1486
1487 Log(("supdrvGipMpEvent: Gip master %#lx -> %#lx\n", (long)idGipMaster, (long)idNewGipMaster));
1488 ASMAtomicCmpXchgSize(&pDevExt->idGipMaster, idNewGipMaster, idGipMaster, fIgnored);
1489 NOREF(fIgnored);
1490 }
1491 }
1492}
1493
1494
1495/**
1496 * On CPU initialization callback for RTMpOnAll.
1497 *
1498 * @param idCpu The CPU ID.
1499 * @param pvUser1 The device extension.
1500 * @param pvUser2 The GIP.
1501 */
1502static DECLCALLBACK(void) supdrvGipInitOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1503{
1504 /* This is good enough, even though it will update some of the globals a
1505 bit to much. */
1506 supdrvGipMpEventOnlineOrInitOnCpu((PSUPDRVDEVEXT)pvUser1, idCpu);
1507 NOREF(pvUser2);
1508}
1509
1510
1511/**
1512 * Callback used by supdrvDetermineAsyncTSC to read the TSC on a CPU.
1513 *
1514 * @param idCpu Ignored.
1515 * @param pvUser1 Where to put the TSC.
1516 * @param pvUser2 Ignored.
1517 */
1518static DECLCALLBACK(void) supdrvGipInitDetermineAsyncTscWorker(RTCPUID idCpu, void *pvUser1, void *pvUser2)
1519{
1520 Assert(RTMpCpuIdToSetIndex(idCpu) == (intptr_t)pvUser2);
1521 ASMAtomicWriteU64((uint64_t volatile *)pvUser1, ASMReadTSC());
1522 RT_NOREF2(idCpu, pvUser2);
1523}
1524
1525
1526/**
1527 * Determine if Async GIP mode is required because of TSC drift.
1528 *
1529 * When using the default/normal timer code it is essential that the time stamp counter
1530 * (TSC) runs never backwards, that is, a read operation to the counter should return
1531 * a bigger value than any previous read operation. This is guaranteed by the latest
1532 * AMD CPUs and by newer Intel CPUs which never enter the C2 state (P4). In any other
1533 * case we have to choose the asynchronous timer mode.
1534 *
1535 * @param poffMin Pointer to the determined difference between different
1536 * cores (optional, can be NULL).
1537 * @return false if the time stamp counters appear to be synchronized, true otherwise.
1538 */
1539static bool supdrvGipInitDetermineAsyncTsc(uint64_t *poffMin)
1540{
1541 /*
1542 * Just iterate all the cpus 8 times and make sure that the TSC is
1543 * ever increasing. We don't bother taking TSC rollover into account.
1544 */
1545 int iEndCpu = RTMpGetArraySize();
1546 int iCpu;
1547 int cLoops = 8;
1548 bool fAsync = false;
1549 int rc = VINF_SUCCESS;
1550 uint64_t offMax = 0;
1551 uint64_t offMin = ~(uint64_t)0;
1552 uint64_t PrevTsc = ASMReadTSC();
1553
1554 while (cLoops-- > 0)
1555 {
1556 for (iCpu = 0; iCpu < iEndCpu; iCpu++)
1557 {
1558 uint64_t CurTsc;
1559 rc = RTMpOnSpecific(RTMpCpuIdFromSetIndex(iCpu), supdrvGipInitDetermineAsyncTscWorker,
1560 &CurTsc, (void *)(uintptr_t)iCpu);
1561 if (RT_SUCCESS(rc))
1562 {
1563 if (CurTsc <= PrevTsc)
1564 {
1565 fAsync = true;
1566 offMin = offMax = PrevTsc - CurTsc;
1567 Log(("supdrvGipInitDetermineAsyncTsc: iCpu=%d cLoops=%d CurTsc=%llx PrevTsc=%llx\n",
1568 iCpu, cLoops, CurTsc, PrevTsc));
1569 break;
1570 }
1571
1572 /* Gather statistics (except the first time). */
1573 if (iCpu != 0 || cLoops != 7)
1574 {
1575 uint64_t off = CurTsc - PrevTsc;
1576 if (off < offMin)
1577 offMin = off;
1578 if (off > offMax)
1579 offMax = off;
1580 Log2(("%d/%d: off=%llx\n", cLoops, iCpu, off));
1581 }
1582
1583 /* Next */
1584 PrevTsc = CurTsc;
1585 }
1586 else if (rc == VERR_NOT_SUPPORTED)
1587 break;
1588 else
1589 AssertMsg(rc == VERR_CPU_NOT_FOUND || rc == VERR_CPU_OFFLINE, ("%d\n", rc));
1590 }
1591
1592 /* broke out of the loop. */
1593 if (iCpu < iEndCpu)
1594 break;
1595 }
1596
1597 if (poffMin)
1598 *poffMin = offMin; /* Almost RTMpOnSpecific profiling. */
1599 Log(("supdrvGipInitDetermineAsyncTsc: returns %d; iEndCpu=%d rc=%d offMin=%llx offMax=%llx\n",
1600 fAsync, iEndCpu, rc, offMin, offMax));
1601#if !defined(RT_OS_SOLARIS) && !defined(RT_OS_OS2) && !defined(RT_OS_WINDOWS)
1602 OSDBGPRINT(("vboxdrv: fAsync=%d offMin=%#lx offMax=%#lx\n", fAsync, (long)offMin, (long)offMax));
1603#endif
1604 return fAsync;
1605}
1606
1607
1608/**
1609 * supdrvGipInit() worker that determines the GIP TSC mode.
1610 *
1611 * @returns The most suitable TSC mode.
1612 * @param pDevExt Pointer to the device instance data.
1613 */
1614static SUPGIPMODE supdrvGipInitDetermineTscMode(PSUPDRVDEVEXT pDevExt)
1615{
1616 uint64_t u64DiffCoresIgnored;
1617 uint32_t uEAX, uEBX, uECX, uEDX;
1618
1619 /*
1620 * Establish whether the CPU advertises TSC as invariant, we need that in
1621 * a couple of places below.
1622 */
1623 bool fInvariantTsc = false;
1624 if (ASMHasCpuId())
1625 {
1626 uEAX = ASMCpuId_EAX(0x80000000);
1627 if (ASMIsValidExtRange(uEAX) && uEAX >= 0x80000007)
1628 {
1629 uEDX = ASMCpuId_EDX(0x80000007);
1630 if (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR)
1631 fInvariantTsc = true;
1632 }
1633 }
1634
1635 /*
1636 * On single CPU systems, we don't need to consider ASYNC mode.
1637 */
1638 if (RTMpGetCount() <= 1)
1639 return fInvariantTsc ? SUPGIPMODE_INVARIANT_TSC : SUPGIPMODE_SYNC_TSC;
1640
1641 /*
1642 * Allow the user and/or OS specific bits to force async mode.
1643 */
1644 if (supdrvOSGetForcedAsyncTscMode(pDevExt))
1645 return SUPGIPMODE_ASYNC_TSC;
1646
1647 /*
1648 * Use invariant mode if the CPU says TSC is invariant.
1649 */
1650 if (fInvariantTsc)
1651 return SUPGIPMODE_INVARIANT_TSC;
1652
1653 /*
1654 * TSC is not invariant and we're on SMP, this presents two problems:
1655 *
1656 * (1) There might be a skew between the CPU, so that cpu0
1657 * returns a TSC that is slightly different from cpu1.
1658 * This screw may be due to (2), bad TSC initialization
1659 * or slightly different TSC rates.
1660 *
1661 * (2) Power management (and other things) may cause the TSC
1662 * to run at a non-constant speed, and cause the speed
1663 * to be different on the cpus. This will result in (1).
1664 *
1665 * If any of the above is detected, we will have to use ASYNC mode.
1666 */
1667 /* (1). Try check for current differences between the cpus. */
1668 if (supdrvGipInitDetermineAsyncTsc(&u64DiffCoresIgnored))
1669 return SUPGIPMODE_ASYNC_TSC;
1670
1671 /* (2) If it's an AMD CPU with power management, we won't trust its TSC. */
1672 ASMCpuId(0, &uEAX, &uEBX, &uECX, &uEDX);
1673 if ( ASMIsValidStdRange(uEAX)
1674 && ASMIsAmdCpuEx(uEBX, uECX, uEDX))
1675 {
1676 /* Check for APM support. */
1677 uEAX = ASMCpuId_EAX(0x80000000);
1678 if (ASMIsValidExtRange(uEAX) && uEAX >= 0x80000007)
1679 {
1680 uEDX = ASMCpuId_EDX(0x80000007);
1681 if (uEDX & 0x3e) /* STC|TM|THERMTRIP|VID|FID. Ignore TS. */
1682 return SUPGIPMODE_ASYNC_TSC;
1683 }
1684 }
1685
1686 return SUPGIPMODE_SYNC_TSC;
1687}
1688
1689
1690/**
1691 * Initializes per-CPU GIP information.
1692 *
1693 * @param pGip Pointer to the GIP.
1694 * @param pCpu Pointer to which GIP CPU to initialize.
1695 * @param u64NanoTS The current nanosecond timestamp.
1696 * @param uCpuHz The CPU frequency to set, 0 if the caller doesn't know.
1697 */
1698static void supdrvGipInitCpu(PSUPGLOBALINFOPAGE pGip, PSUPGIPCPU pCpu, uint64_t u64NanoTS, uint64_t uCpuHz)
1699{
1700 pCpu->u32TransactionId = 2;
1701 pCpu->u64NanoTS = u64NanoTS;
1702 pCpu->u64TSC = ASMReadTSC();
1703 pCpu->u64TSCSample = GIP_TSC_DELTA_RSVD;
1704 pCpu->i64TSCDelta = pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED ? INT64_MAX : 0;
1705
1706 ASMAtomicWriteSize(&pCpu->enmState, SUPGIPCPUSTATE_INVALID);
1707 ASMAtomicWriteU32(&pCpu->idCpu, NIL_RTCPUID);
1708 ASMAtomicWriteS16(&pCpu->iCpuSet, -1);
1709 ASMAtomicWriteU16(&pCpu->iCpuGroup, 0);
1710 ASMAtomicWriteU16(&pCpu->iCpuGroupMember, UINT16_MAX);
1711 ASMAtomicWriteU16(&pCpu->idApic, UINT16_MAX);
1712 ASMAtomicWriteU32(&pCpu->iReservedForNumaNode, 0);
1713
1714 /*
1715 * The first time we're called, we don't have a CPU frequency handy,
1716 * so pretend it's a 4 GHz CPU. On CPUs that are online, we'll get
1717 * called again and at that point we have a more plausible CPU frequency
1718 * value handy. The frequency history will also be adjusted again on
1719 * the 2nd timer callout (maybe we can skip that now?).
1720 */
1721 if (!uCpuHz)
1722 {
1723 pCpu->u64CpuHz = _4G - 1;
1724 pCpu->u32UpdateIntervalTSC = (uint32_t)((_4G - 1) / pGip->u32UpdateHz);
1725 }
1726 else
1727 {
1728 pCpu->u64CpuHz = uCpuHz;
1729 pCpu->u32UpdateIntervalTSC = (uint32_t)(uCpuHz / pGip->u32UpdateHz);
1730 }
1731 pCpu->au32TSCHistory[0]
1732 = pCpu->au32TSCHistory[1]
1733 = pCpu->au32TSCHistory[2]
1734 = pCpu->au32TSCHistory[3]
1735 = pCpu->au32TSCHistory[4]
1736 = pCpu->au32TSCHistory[5]
1737 = pCpu->au32TSCHistory[6]
1738 = pCpu->au32TSCHistory[7]
1739 = pCpu->u32UpdateIntervalTSC;
1740}
1741
1742
1743/**
1744 * Initializes the GIP data.
1745 *
1746 * @param pDevExt Pointer to the device instance data.
1747 * @param pGip Pointer to the read-write kernel mapping of the GIP.
1748 * @param HCPhys The physical address of the GIP.
1749 * @param u64NanoTS The current nanosecond timestamp.
1750 * @param uUpdateHz The update frequency.
1751 * @param uUpdateIntervalNS The update interval in nanoseconds.
1752 * @param cCpus The CPU count.
1753 */
1754static void supdrvGipInit(PSUPDRVDEVEXT pDevExt, PSUPGLOBALINFOPAGE pGip, RTHCPHYS HCPhys,
1755 uint64_t u64NanoTS, unsigned uUpdateHz, unsigned uUpdateIntervalNS, unsigned cCpus)
1756{
1757 size_t const cbGip = RT_ALIGN_Z(RT_OFFSETOF(SUPGLOBALINFOPAGE, aCPUs[cCpus]), PAGE_SIZE);
1758 unsigned i;
1759#ifdef DEBUG_DARWIN_GIP
1760 OSDBGPRINT(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d cCpus=%u\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz, cCpus));
1761#else
1762 LogFlow(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d cCpus=%u\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz, cCpus));
1763#endif
1764
1765 /*
1766 * Initialize the structure.
1767 */
1768 memset(pGip, 0, cbGip);
1769
1770 pGip->u32Magic = SUPGLOBALINFOPAGE_MAGIC;
1771 pGip->u32Version = SUPGLOBALINFOPAGE_VERSION;
1772 pGip->u32Mode = supdrvGipInitDetermineTscMode(pDevExt);
1773 if ( pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC
1774 /*|| pGip->u32Mode == SUPGIPMODE_SYNC_TSC */)
1775 pGip->enmUseTscDelta = supdrvOSAreTscDeltasInSync() /* Allow OS override (windows). */
1776 ? SUPGIPUSETSCDELTA_ZERO_CLAIMED : SUPGIPUSETSCDELTA_PRACTICALLY_ZERO /* downgrade later */;
1777 else
1778 pGip->enmUseTscDelta = SUPGIPUSETSCDELTA_NOT_APPLICABLE;
1779 pGip->cCpus = (uint16_t)cCpus;
1780 pGip->cPages = (uint16_t)(cbGip / PAGE_SIZE);
1781 pGip->u32UpdateHz = uUpdateHz;
1782 pGip->u32UpdateIntervalNS = uUpdateIntervalNS;
1783 pGip->fGetGipCpu = SUPGIPGETCPU_APIC_ID;
1784 RTCpuSetEmpty(&pGip->OnlineCpuSet);
1785 RTCpuSetEmpty(&pGip->PresentCpuSet);
1786 RTMpGetSet(&pGip->PossibleCpuSet);
1787 pGip->cOnlineCpus = RTMpGetOnlineCount();
1788 pGip->cPresentCpus = RTMpGetPresentCount();
1789 pGip->cPossibleCpus = RTMpGetCount();
1790 pGip->cPossibleCpuGroups = 1;
1791 pGip->idCpuMax = RTMpGetMaxCpuId();
1792 for (i = 0; i < RT_ELEMENTS(pGip->aiCpuFromApicId); i++)
1793 pGip->aiCpuFromApicId[i] = UINT16_MAX;
1794 for (i = 0; i < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx); i++)
1795 pGip->aiCpuFromCpuSetIdx[i] = UINT16_MAX;
1796 pGip->aiFirstCpuSetIdxFromCpuGroup[0] = 0;
1797 for (i = 1; i < RT_ELEMENTS(pGip->aiFirstCpuSetIdxFromCpuGroup); i++)
1798 pGip->aiFirstCpuSetIdxFromCpuGroup[i] = UINT16_MAX;
1799#ifdef RT_OS_WINDOWS
1800 supdrvOSInitGipGroupTable(pDevExt, pGip);
1801#endif
1802 for (i = 0; i < cCpus; i++)
1803 supdrvGipInitCpu(pGip, &pGip->aCPUs[i], u64NanoTS, 0 /*uCpuHz*/);
1804
1805 /*
1806 * Link it to the device extension.
1807 */
1808 pDevExt->pGip = pGip;
1809 pDevExt->HCPhysGip = HCPhys;
1810 pDevExt->cGipUsers = 0;
1811}
1812
1813
1814/**
1815 * Creates the GIP.
1816 *
1817 * @returns VBox status code.
1818 * @param pDevExt Instance data. GIP stuff may be updated.
1819 */
1820int VBOXCALL supdrvGipCreate(PSUPDRVDEVEXT pDevExt)
1821{
1822 PSUPGLOBALINFOPAGE pGip;
1823 RTHCPHYS HCPhysGip;
1824 uint32_t u32SystemResolution;
1825 uint32_t u32Interval;
1826 uint32_t u32MinInterval;
1827 uint32_t uMod;
1828 unsigned cCpus;
1829 int rc;
1830
1831 LogFlow(("supdrvGipCreate:\n"));
1832
1833 /*
1834 * Assert order.
1835 */
1836 Assert(pDevExt->u32SystemTimerGranularityGrant == 0);
1837 Assert(pDevExt->GipMemObj == NIL_RTR0MEMOBJ);
1838 Assert(!pDevExt->pGipTimer);
1839#ifdef SUPDRV_USE_MUTEX_FOR_GIP
1840 Assert(pDevExt->mtxGip != NIL_RTSEMMUTEX);
1841 Assert(pDevExt->mtxTscDelta != NIL_RTSEMMUTEX);
1842#else
1843 Assert(pDevExt->mtxGip != NIL_RTSEMFASTMUTEX);
1844 Assert(pDevExt->mtxTscDelta != NIL_RTSEMFASTMUTEX);
1845#endif
1846
1847 /*
1848 * Check the CPU count.
1849 */
1850 cCpus = RTMpGetArraySize();
1851 if ( cCpus > RTCPUSET_MAX_CPUS
1852#if RTCPUSET_MAX_CPUS != 256
1853 || cCpus > 256 /* ApicId is used for the mappings */
1854#endif
1855 )
1856 {
1857 SUPR0Printf("VBoxDrv: Too many CPUs (%u) for the GIP (max %u)\n", cCpus, RT_MIN(RTCPUSET_MAX_CPUS, 256));
1858 return VERR_TOO_MANY_CPUS;
1859 }
1860
1861 /*
1862 * Allocate a contiguous set of pages with a default kernel mapping.
1863 */
1864 rc = RTR0MemObjAllocCont(&pDevExt->GipMemObj, RT_UOFFSETOF(SUPGLOBALINFOPAGE, aCPUs[cCpus]), false /*fExecutable*/);
1865 if (RT_FAILURE(rc))
1866 {
1867 OSDBGPRINT(("supdrvGipCreate: failed to allocate the GIP page. rc=%d\n", rc));
1868 return rc;
1869 }
1870 pGip = (PSUPGLOBALINFOPAGE)RTR0MemObjAddress(pDevExt->GipMemObj); AssertPtr(pGip);
1871 HCPhysGip = RTR0MemObjGetPagePhysAddr(pDevExt->GipMemObj, 0); Assert(HCPhysGip != NIL_RTHCPHYS);
1872
1873 /*
1874 * Find a reasonable update interval and initialize the structure.
1875 */
1876 supdrvGipRequestHigherTimerFrequencyFromSystem(pDevExt);
1877 /** @todo figure out why using a 100Ms interval upsets timekeeping in VMs.
1878 * See @bugref{6710}. */
1879 u32MinInterval = RT_NS_10MS;
1880 u32SystemResolution = RTTimerGetSystemGranularity();
1881 u32Interval = u32MinInterval;
1882 uMod = u32MinInterval % u32SystemResolution;
1883 if (uMod)
1884 u32Interval += u32SystemResolution - uMod;
1885
1886 supdrvGipInit(pDevExt, pGip, HCPhysGip, RTTimeSystemNanoTS(), RT_NS_1SEC / u32Interval /*=Hz*/, u32Interval, cCpus);
1887
1888 /*
1889 * Important sanity check...
1890 */
1891 if (RT_UNLIKELY( pGip->enmUseTscDelta == SUPGIPUSETSCDELTA_ZERO_CLAIMED
1892 && pGip->u32Mode == SUPGIPMODE_ASYNC_TSC
1893 && !supdrvOSGetForcedAsyncTscMode(pDevExt)))
1894 {
1895 OSDBGPRINT(("supdrvGipCreate: Host-OS/user claims the TSC-deltas are zero but we detected async. TSC! Bad.\n"));
1896 return VERR_INTERNAL_ERROR_2;
1897 }
1898
1899 /* It doesn't make sense to do TSC-delta detection on systems we detect as async. */
1900 AssertReturn( pGip->u32Mode != SUPGIPMODE_ASYNC_TSC
1901 || pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_ZERO_CLAIMED, VERR_INTERNAL_ERROR_3);
1902
1903 /*
1904 * Do the TSC frequency measurements.
1905 *
1906 * If we're in invariant TSC mode, just to a quick preliminary measurement
1907 * that the TSC-delta measurement code can use to yield cross calls.
1908 *
1909 * If we're in any of the other two modes, neither which require MP init,
1910 * notifications or deltas for the job, do the full measurement now so
1911 * that supdrvGipInitOnCpu() can populate the TSC interval and history
1912 * array with more reasonable values.
1913 */
1914 if (pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC)
1915 {
1916 rc = supdrvGipInitMeasureTscFreq(pGip, true /*fRough*/); /* cannot fail */
1917 supdrvGipInitStartTimerForRefiningInvariantTscFreq(pDevExt);
1918 }
1919 else
1920 rc = supdrvGipInitMeasureTscFreq(pGip, false /*fRough*/);
1921 if (RT_SUCCESS(rc))
1922 {
1923 /*
1924 * Start TSC-delta measurement thread before we start getting MP
1925 * events that will try kick it into action (includes the
1926 * RTMpOnAll/supdrvGipInitOnCpu call below).
1927 */
1928 RTCpuSetEmpty(&pDevExt->TscDeltaCpuSet);
1929 RTCpuSetEmpty(&pDevExt->TscDeltaObtainedCpuSet);
1930#ifdef SUPDRV_USE_TSC_DELTA_THREAD
1931 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
1932 rc = supdrvTscDeltaThreadInit(pDevExt);
1933#endif
1934 if (RT_SUCCESS(rc))
1935 {
1936 rc = RTMpNotificationRegister(supdrvGipMpEvent, pDevExt);
1937 if (RT_SUCCESS(rc))
1938 {
1939 /*
1940 * Do GIP initialization on all online CPUs. Wake up the
1941 * TSC-delta thread afterwards.
1942 */
1943 rc = RTMpOnAll(supdrvGipInitOnCpu, pDevExt, pGip);
1944 if (RT_SUCCESS(rc))
1945 {
1946#ifdef SUPDRV_USE_TSC_DELTA_THREAD
1947 supdrvTscDeltaThreadStartMeasurement(pDevExt, true /* fForceAll */);
1948#else
1949 uint16_t iCpu;
1950 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
1951 {
1952 /*
1953 * Measure the TSC deltas now that we have MP notifications.
1954 */
1955 int cTries = 5;
1956 do
1957 {
1958 rc = supdrvTscMeasureInitialDeltas(pDevExt);
1959 if ( rc != VERR_TRY_AGAIN
1960 && rc != VERR_CPU_OFFLINE)
1961 break;
1962 } while (--cTries > 0);
1963 for (iCpu = 0; iCpu < pGip->cCpus; iCpu++)
1964 Log(("supdrvTscDeltaInit: cpu[%u] delta %lld\n", iCpu, pGip->aCPUs[iCpu].i64TSCDelta));
1965 }
1966 else
1967 {
1968 for (iCpu = 0; iCpu < pGip->cCpus; iCpu++)
1969 AssertMsg(!pGip->aCPUs[iCpu].i64TSCDelta, ("iCpu=%u %lld mode=%d\n", iCpu, pGip->aCPUs[iCpu].i64TSCDelta, pGip->u32Mode));
1970 }
1971 if (RT_SUCCESS(rc))
1972#endif
1973 {
1974 /*
1975 * Create the timer.
1976 * If CPU_ALL isn't supported we'll have to fall back to synchronous mode.
1977 */
1978 if (pGip->u32Mode == SUPGIPMODE_ASYNC_TSC)
1979 {
1980 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, RTTIMER_FLAGS_CPU_ALL,
1981 supdrvGipAsyncTimer, pDevExt);
1982 if (rc == VERR_NOT_SUPPORTED)
1983 {
1984 OSDBGPRINT(("supdrvGipCreate: omni timer not supported, falling back to synchronous mode\n"));
1985 pGip->u32Mode = SUPGIPMODE_SYNC_TSC;
1986 }
1987 }
1988 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
1989 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, 0 /* fFlags */,
1990 supdrvGipSyncAndInvariantTimer, pDevExt);
1991 if (RT_SUCCESS(rc))
1992 {
1993 /*
1994 * We're good.
1995 */
1996 Log(("supdrvGipCreate: %u ns interval.\n", u32Interval));
1997 supdrvGipReleaseHigherTimerFrequencyFromSystem(pDevExt);
1998
1999 g_pSUPGlobalInfoPage = pGip;
2000 return VINF_SUCCESS;
2001 }
2002
2003 OSDBGPRINT(("supdrvGipCreate: failed create GIP timer at %u ns interval. rc=%Rrc\n", u32Interval, rc));
2004 Assert(!pDevExt->pGipTimer);
2005 }
2006 }
2007 else
2008 OSDBGPRINT(("supdrvGipCreate: RTMpOnAll failed. rc=%Rrc\n", rc));
2009 }
2010 else
2011 OSDBGPRINT(("supdrvGipCreate: failed to register MP event notfication. rc=%Rrc\n", rc));
2012 }
2013 else
2014 OSDBGPRINT(("supdrvGipCreate: supdrvTscDeltaInit failed. rc=%Rrc\n", rc));
2015 }
2016 else
2017 OSDBGPRINT(("supdrvGipCreate: supdrvTscMeasureInitialDeltas failed. rc=%Rrc\n", rc));
2018
2019 /* Releases timer frequency increase too. */
2020 supdrvGipDestroy(pDevExt);
2021 return rc;
2022}
2023
2024
2025/**
2026 * Invalidates the GIP data upon termination.
2027 *
2028 * @param pGip Pointer to the read-write kernel mapping of the GIP.
2029 */
2030static void supdrvGipTerm(PSUPGLOBALINFOPAGE pGip)
2031{
2032 unsigned i;
2033 pGip->u32Magic = 0;
2034 for (i = 0; i < pGip->cCpus; i++)
2035 {
2036 pGip->aCPUs[i].u64NanoTS = 0;
2037 pGip->aCPUs[i].u64TSC = 0;
2038 pGip->aCPUs[i].iTSCHistoryHead = 0;
2039 pGip->aCPUs[i].u64TSCSample = 0;
2040 pGip->aCPUs[i].i64TSCDelta = INT64_MAX;
2041 }
2042}
2043
2044
2045/**
2046 * Terminates the GIP.
2047 *
2048 * @param pDevExt Instance data. GIP stuff may be updated.
2049 */
2050void VBOXCALL supdrvGipDestroy(PSUPDRVDEVEXT pDevExt)
2051{
2052 int rc;
2053#ifdef DEBUG_DARWIN_GIP
2054 OSDBGPRINT(("supdrvGipDestroy: pDevExt=%p pGip=%p pGipTimer=%p GipMemObj=%p\n", pDevExt,
2055 pDevExt->GipMemObj != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pDevExt->GipMemObj) : NULL,
2056 pDevExt->pGipTimer, pDevExt->GipMemObj));
2057#endif
2058
2059 /*
2060 * Stop receiving MP notifications before tearing anything else down.
2061 */
2062 RTMpNotificationDeregister(supdrvGipMpEvent, pDevExt);
2063
2064#ifdef SUPDRV_USE_TSC_DELTA_THREAD
2065 /*
2066 * Terminate the TSC-delta measurement thread and resources.
2067 */
2068 supdrvTscDeltaTerm(pDevExt);
2069#endif
2070
2071 /*
2072 * Destroy the TSC-refinement timer.
2073 */
2074 if (pDevExt->pInvarTscRefineTimer)
2075 {
2076 RTTimerDestroy(pDevExt->pInvarTscRefineTimer);
2077 pDevExt->pInvarTscRefineTimer = NULL;
2078 }
2079
2080 /*
2081 * Invalid the GIP data.
2082 */
2083 if (pDevExt->pGip)
2084 {
2085 supdrvGipTerm(pDevExt->pGip);
2086 pDevExt->pGip = NULL;
2087 }
2088 g_pSUPGlobalInfoPage = NULL;
2089
2090 /*
2091 * Destroy the timer and free the GIP memory object.
2092 */
2093 if (pDevExt->pGipTimer)
2094 {
2095 rc = RTTimerDestroy(pDevExt->pGipTimer); AssertRC(rc);
2096 pDevExt->pGipTimer = NULL;
2097 }
2098
2099 if (pDevExt->GipMemObj != NIL_RTR0MEMOBJ)
2100 {
2101 rc = RTR0MemObjFree(pDevExt->GipMemObj, true /* free mappings */); AssertRC(rc);
2102 pDevExt->GipMemObj = NIL_RTR0MEMOBJ;
2103 }
2104
2105 /*
2106 * Finally, make sure we've release the system timer resolution request
2107 * if one actually succeeded and is still pending.
2108 */
2109 supdrvGipReleaseHigherTimerFrequencyFromSystem(pDevExt);
2110}
2111
2112
2113
2114
2115/*
2116 *
2117 *
2118 * GIP Update Timer Related Code
2119 * GIP Update Timer Related Code
2120 * GIP Update Timer Related Code
2121 *
2122 *
2123 */
2124
2125
2126/**
2127 * Worker routine for supdrvGipUpdate() and supdrvGipUpdatePerCpu() that
2128 * updates all the per cpu data except the transaction id.
2129 *
2130 * @param pDevExt The device extension.
2131 * @param pGipCpu Pointer to the per cpu data.
2132 * @param u64NanoTS The current time stamp.
2133 * @param u64TSC The current TSC.
2134 * @param iTick The current timer tick.
2135 *
2136 * @remarks Can be called with interrupts disabled!
2137 */
2138static void supdrvGipDoUpdateCpu(PSUPDRVDEVEXT pDevExt, PSUPGIPCPU pGipCpu, uint64_t u64NanoTS, uint64_t u64TSC, uint64_t iTick)
2139{
2140 uint64_t u64TSCDelta;
2141 bool fUpdateCpuHz;
2142 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
2143 AssertPtrReturnVoid(pGip);
2144
2145 /* Delta between this and the previous update. */
2146 ASMAtomicUoWriteU32(&pGipCpu->u32PrevUpdateIntervalNS, (uint32_t)(u64NanoTS - pGipCpu->u64NanoTS));
2147
2148 /*
2149 * Update the NanoTS.
2150 */
2151 ASMAtomicWriteU64(&pGipCpu->u64NanoTS, u64NanoTS);
2152
2153 /*
2154 * Calc TSC delta.
2155 */
2156 u64TSCDelta = u64TSC - pGipCpu->u64TSC;
2157 ASMAtomicWriteU64(&pGipCpu->u64TSC, u64TSC);
2158
2159 /*
2160 * Determine if we need to update the CPU (TSC) frequency calculation.
2161 *
2162 * We don't need to keep recalculating the frequency when it's invariant,
2163 * unless the special tstGIP-2 testing mode is enabled.
2164 */
2165 fUpdateCpuHz = pGip->u32Mode != SUPGIPMODE_INVARIANT_TSC;
2166 if (!(pGip->fFlags & SUPGIP_FLAGS_TESTING))
2167 { /* likely*/ }
2168 else
2169 {
2170 uint32_t fGipFlags = pGip->fFlags;
2171 if (fGipFlags & (SUPGIP_FLAGS_TESTING_ENABLE | SUPGIP_FLAGS_TESTING_START))
2172 {
2173 if (fGipFlags & SUPGIP_FLAGS_TESTING_START)
2174 {
2175 /* Cache the TSC frequency before forcing updates due to test mode. */
2176 if (!fUpdateCpuHz)
2177 pDevExt->uGipTestModeInvariantCpuHz = pGip->aCPUs[0].u64CpuHz;
2178 ASMAtomicAndU32(&pGip->fFlags, ~SUPGIP_FLAGS_TESTING_START);
2179 }
2180 fUpdateCpuHz = true;
2181 }
2182 else if (fGipFlags & SUPGIP_FLAGS_TESTING_STOP)
2183 {
2184 /* Restore the cached TSC frequency if any. */
2185 if (!fUpdateCpuHz)
2186 {
2187 Assert(pDevExt->uGipTestModeInvariantCpuHz);
2188 ASMAtomicWriteU64(&pGip->aCPUs[0].u64CpuHz, pDevExt->uGipTestModeInvariantCpuHz);
2189 }
2190 ASMAtomicAndU32(&pGip->fFlags, ~(SUPGIP_FLAGS_TESTING_STOP | SUPGIP_FLAGS_TESTING));
2191 }
2192 }
2193
2194 /*
2195 * Calculate the CPU (TSC) frequency if necessary.
2196 */
2197 if (fUpdateCpuHz)
2198 {
2199 uint64_t u64CpuHz;
2200 uint32_t u32UpdateIntervalTSC;
2201 uint32_t u32UpdateIntervalTSCSlack;
2202 uint32_t u32TransactionId;
2203 unsigned iTSCHistoryHead;
2204
2205 if (u64TSCDelta >> 32)
2206 {
2207 u64TSCDelta = pGipCpu->u32UpdateIntervalTSC;
2208 pGipCpu->cErrors++;
2209 }
2210
2211 /*
2212 * On the 2nd and 3rd callout, reset the history with the current TSC
2213 * interval since the values entered by supdrvGipInit are totally off.
2214 * The interval on the 1st callout completely unreliable, the 2nd is a bit
2215 * better, while the 3rd should be most reliable.
2216 */
2217 /** @todo Could we drop this now that we initializes the history
2218 * with nominal TSC frequency values? */
2219 u32TransactionId = pGipCpu->u32TransactionId;
2220 if (RT_UNLIKELY( ( u32TransactionId == 5
2221 || u32TransactionId == 7)
2222 && ( iTick == 2
2223 || iTick == 3) ))
2224 {
2225 unsigned i;
2226 for (i = 0; i < RT_ELEMENTS(pGipCpu->au32TSCHistory); i++)
2227 ASMAtomicUoWriteU32(&pGipCpu->au32TSCHistory[i], (uint32_t)u64TSCDelta);
2228 }
2229
2230 /*
2231 * Validate the NanoTS deltas between timer fires with an arbitrary threshold of 0.5%.
2232 * Wait until we have at least one full history since the above history reset. The
2233 * assumption is that the majority of the previous history values will be tolerable.
2234 * See @bugref{6710#c67}.
2235 */
2236 /** @todo Could we drop the fudging there now that we initializes the history
2237 * with nominal TSC frequency values? */
2238 if ( u32TransactionId > 23 /* 7 + (8 * 2) */
2239 && pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
2240 {
2241 uint32_t uNanoTsThreshold = pGip->u32UpdateIntervalNS / 200;
2242 if ( pGipCpu->u32PrevUpdateIntervalNS > pGip->u32UpdateIntervalNS + uNanoTsThreshold
2243 || pGipCpu->u32PrevUpdateIntervalNS < pGip->u32UpdateIntervalNS - uNanoTsThreshold)
2244 {
2245 uint32_t u32;
2246 u32 = pGipCpu->au32TSCHistory[0];
2247 u32 += pGipCpu->au32TSCHistory[1];
2248 u32 += pGipCpu->au32TSCHistory[2];
2249 u32 += pGipCpu->au32TSCHistory[3];
2250 u32 >>= 2;
2251 u64TSCDelta = pGipCpu->au32TSCHistory[4];
2252 u64TSCDelta += pGipCpu->au32TSCHistory[5];
2253 u64TSCDelta += pGipCpu->au32TSCHistory[6];
2254 u64TSCDelta += pGipCpu->au32TSCHistory[7];
2255 u64TSCDelta >>= 2;
2256 u64TSCDelta += u32;
2257 u64TSCDelta >>= 1;
2258 }
2259 }
2260
2261 /*
2262 * TSC History.
2263 */
2264 Assert(RT_ELEMENTS(pGipCpu->au32TSCHistory) == 8);
2265 iTSCHistoryHead = (pGipCpu->iTSCHistoryHead + 1) & 7;
2266 ASMAtomicWriteU32(&pGipCpu->iTSCHistoryHead, iTSCHistoryHead);
2267 ASMAtomicWriteU32(&pGipCpu->au32TSCHistory[iTSCHistoryHead], (uint32_t)u64TSCDelta);
2268
2269 /*
2270 * UpdateIntervalTSC = average of last 8,2,1 intervals depending on update HZ.
2271 *
2272 * On Windows, we have an occasional (but recurring) sour value that messed up
2273 * the history but taking only 1 interval reduces the precision overall.
2274 */
2275 if ( pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC
2276 || pGip->u32UpdateHz >= 1000)
2277 {
2278 uint32_t u32;
2279 u32 = pGipCpu->au32TSCHistory[0];
2280 u32 += pGipCpu->au32TSCHistory[1];
2281 u32 += pGipCpu->au32TSCHistory[2];
2282 u32 += pGipCpu->au32TSCHistory[3];
2283 u32 >>= 2;
2284 u32UpdateIntervalTSC = pGipCpu->au32TSCHistory[4];
2285 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[5];
2286 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[6];
2287 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[7];
2288 u32UpdateIntervalTSC >>= 2;
2289 u32UpdateIntervalTSC += u32;
2290 u32UpdateIntervalTSC >>= 1;
2291
2292 /* Value chosen for a 2GHz Athlon64 running linux 2.6.10/11. */
2293 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 14;
2294 }
2295 else if (pGip->u32UpdateHz >= 90)
2296 {
2297 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
2298 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[(iTSCHistoryHead - 1) & 7];
2299 u32UpdateIntervalTSC >>= 1;
2300
2301 /* value chosen on a 2GHz thinkpad running windows */
2302 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 7;
2303 }
2304 else
2305 {
2306 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
2307
2308 /* This value hasn't be checked yet.. waiting for OS/2 and 33Hz timers.. :-) */
2309 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 6;
2310 }
2311 ASMAtomicWriteU32(&pGipCpu->u32UpdateIntervalTSC, u32UpdateIntervalTSC + u32UpdateIntervalTSCSlack);
2312
2313 /*
2314 * CpuHz.
2315 */
2316 u64CpuHz = ASMMult2xU32RetU64(u32UpdateIntervalTSC, RT_NS_1SEC);
2317 u64CpuHz /= pGip->u32UpdateIntervalNS;
2318 ASMAtomicWriteU64(&pGipCpu->u64CpuHz, u64CpuHz);
2319 }
2320}
2321
2322
2323/**
2324 * Updates the GIP.
2325 *
2326 * @param pDevExt The device extension.
2327 * @param u64NanoTS The current nanosecond timestamp.
2328 * @param u64TSC The current TSC timestamp.
2329 * @param idCpu The CPU ID.
2330 * @param iTick The current timer tick.
2331 *
2332 * @remarks Can be called with interrupts disabled!
2333 */
2334static void supdrvGipUpdate(PSUPDRVDEVEXT pDevExt, uint64_t u64NanoTS, uint64_t u64TSC, RTCPUID idCpu, uint64_t iTick)
2335{
2336 /*
2337 * Determine the relevant CPU data.
2338 */
2339 PSUPGIPCPU pGipCpu;
2340 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
2341 AssertPtrReturnVoid(pGip);
2342
2343 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
2344 pGipCpu = &pGip->aCPUs[0];
2345 else
2346 {
2347 unsigned iCpu = pGip->aiCpuFromApicId[ASMGetApicId()];
2348 if (RT_UNLIKELY(iCpu >= pGip->cCpus))
2349 return;
2350 pGipCpu = &pGip->aCPUs[iCpu];
2351 if (RT_UNLIKELY(pGipCpu->idCpu != idCpu))
2352 return;
2353 }
2354
2355 /*
2356 * Start update transaction.
2357 */
2358 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
2359 {
2360 /* this can happen on win32 if we're taking to long and there are more CPUs around. shouldn't happen though. */
2361 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
2362 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
2363 pGipCpu->cErrors++;
2364 return;
2365 }
2366
2367 /*
2368 * Recalc the update frequency every 0x800th time.
2369 */
2370 if ( pGip->u32Mode != SUPGIPMODE_INVARIANT_TSC /* cuz we're not recalculating the frequency on invariant hosts. */
2371 && !(pGipCpu->u32TransactionId & (GIP_UPDATEHZ_RECALC_FREQ * 2 - 2)))
2372 {
2373 if (pGip->u64NanoTSLastUpdateHz)
2374 {
2375#ifdef RT_ARCH_AMD64 /** @todo fix 64-bit div here to work on x86 linux. */
2376 uint64_t u64Delta = u64NanoTS - pGip->u64NanoTSLastUpdateHz;
2377 uint32_t u32UpdateHz = (uint32_t)((RT_NS_1SEC_64 * GIP_UPDATEHZ_RECALC_FREQ) / u64Delta);
2378 if (u32UpdateHz <= 2000 && u32UpdateHz >= 30)
2379 {
2380 /** @todo r=ramshankar: Changing u32UpdateHz might screw up TSC frequency
2381 * calculation on non-invariant hosts if it changes the history decision
2382 * taken in supdrvGipDoUpdateCpu(). */
2383 uint64_t u64Interval = u64Delta / GIP_UPDATEHZ_RECALC_FREQ;
2384 ASMAtomicWriteU32(&pGip->u32UpdateHz, u32UpdateHz);
2385 ASMAtomicWriteU32(&pGip->u32UpdateIntervalNS, (uint32_t)u64Interval);
2386 }
2387#endif
2388 }
2389 ASMAtomicWriteU64(&pGip->u64NanoTSLastUpdateHz, u64NanoTS | 1);
2390 }
2391
2392 /*
2393 * Update the data.
2394 */
2395 supdrvGipDoUpdateCpu(pDevExt, pGipCpu, u64NanoTS, u64TSC, iTick);
2396
2397 /*
2398 * Complete transaction.
2399 */
2400 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
2401}
2402
2403
2404/**
2405 * Updates the per cpu GIP data for the calling cpu.
2406 *
2407 * @param pDevExt The device extension.
2408 * @param u64NanoTS The current nanosecond timestamp.
2409 * @param u64TSC The current TSC timesaver.
2410 * @param idCpu The CPU ID.
2411 * @param idApic The APIC id for the CPU index.
2412 * @param iTick The current timer tick.
2413 *
2414 * @remarks Can be called with interrupts disabled!
2415 */
2416static void supdrvGipUpdatePerCpu(PSUPDRVDEVEXT pDevExt, uint64_t u64NanoTS, uint64_t u64TSC,
2417 RTCPUID idCpu, uint8_t idApic, uint64_t iTick)
2418{
2419 uint32_t iCpu;
2420 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
2421
2422 /*
2423 * Avoid a potential race when a CPU online notification doesn't fire on
2424 * the onlined CPU but the tick creeps in before the event notification is
2425 * run.
2426 */
2427 if (RT_LIKELY(iTick != 1))
2428 { /* likely*/ }
2429 else
2430 {
2431 iCpu = supdrvGipFindOrAllocCpuIndexForCpuId(pGip, idCpu);
2432 if (pGip->aCPUs[iCpu].enmState == SUPGIPCPUSTATE_OFFLINE)
2433 supdrvGipMpEventOnlineOrInitOnCpu(pDevExt, idCpu);
2434 }
2435
2436 iCpu = pGip->aiCpuFromApicId[idApic];
2437 if (RT_LIKELY(iCpu < pGip->cCpus))
2438 {
2439 PSUPGIPCPU pGipCpu = &pGip->aCPUs[iCpu];
2440 if (pGipCpu->idCpu == idCpu)
2441 {
2442 /*
2443 * Start update transaction.
2444 */
2445 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
2446 {
2447 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
2448 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
2449 pGipCpu->cErrors++;
2450 return;
2451 }
2452
2453 /*
2454 * Update the data.
2455 */
2456 supdrvGipDoUpdateCpu(pDevExt, pGipCpu, u64NanoTS, u64TSC, iTick);
2457
2458 /*
2459 * Complete transaction.
2460 */
2461 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
2462 }
2463 }
2464}
2465
2466
2467/**
2468 * Timer callback function for the sync and invariant GIP modes.
2469 *
2470 * @param pTimer The timer.
2471 * @param pvUser Opaque pointer to the device extension.
2472 * @param iTick The timer tick.
2473 */
2474static DECLCALLBACK(void) supdrvGipSyncAndInvariantTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
2475{
2476 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
2477 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
2478 RTCCUINTREG fEFlags = ASMIntDisableFlags(); /* No interruptions please (real problem on S10). */
2479 uint64_t u64TSC = ASMReadTSC();
2480 uint64_t u64NanoTS = RTTimeSystemNanoTS();
2481 RT_NOREF1(pTimer);
2482
2483 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_PRACTICALLY_ZERO)
2484 {
2485 /*
2486 * The calculations in supdrvGipUpdate() is somewhat timing sensitive,
2487 * missing timer ticks is not an option for GIP because the GIP users
2488 * will end up incrementing the time in 1ns per time getter call until
2489 * there is a complete timer update. So, if the delta has yet to be
2490 * calculated, we just pretend it is zero for now (the GIP users
2491 * probably won't have it for a wee while either and will do the same).
2492 *
2493 * We could maybe on some platforms try cross calling a CPU with a
2494 * working delta here, but it's not worth the hassle since the
2495 * likelihood of this happening is really low. On Windows, Linux, and
2496 * Solaris timers fire on the CPU they were registered/started on.
2497 * Darwin timers doesn't necessarily (they are high priority threads).
2498 */
2499 uint32_t iCpuSet = RTMpCpuIdToSetIndex(RTMpCpuId());
2500 uint16_t iGipCpu = RT_LIKELY(iCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx))
2501 ? pGip->aiCpuFromCpuSetIdx[iCpuSet] : UINT16_MAX;
2502 Assert(!ASMIntAreEnabled());
2503 if (RT_LIKELY(iGipCpu < pGip->cCpus))
2504 {
2505 int64_t iTscDelta = pGip->aCPUs[iGipCpu].i64TSCDelta;
2506 if (iTscDelta != INT64_MAX)
2507 u64TSC -= iTscDelta;
2508 }
2509 }
2510
2511 supdrvGipUpdate(pDevExt, u64NanoTS, u64TSC, NIL_RTCPUID, iTick);
2512
2513 ASMSetFlags(fEFlags);
2514}
2515
2516
2517/**
2518 * Timer callback function for async GIP mode.
2519 * @param pTimer The timer.
2520 * @param pvUser Opaque pointer to the device extension.
2521 * @param iTick The timer tick.
2522 */
2523static DECLCALLBACK(void) supdrvGipAsyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
2524{
2525 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
2526 RTCCUINTREG fEFlags = ASMIntDisableFlags(); /* No interruptions please (real problem on S10). */
2527 RTCPUID idCpu = RTMpCpuId();
2528 uint64_t u64TSC = ASMReadTSC();
2529 uint64_t NanoTS = RTTimeSystemNanoTS();
2530 RT_NOREF1(pTimer);
2531
2532 /** @todo reset the transaction number and whatnot when iTick == 1. */
2533 if (pDevExt->idGipMaster == idCpu)
2534 supdrvGipUpdate(pDevExt, NanoTS, u64TSC, idCpu, iTick);
2535 else
2536 supdrvGipUpdatePerCpu(pDevExt, NanoTS, u64TSC, idCpu, ASMGetApicId(), iTick);
2537
2538 ASMSetFlags(fEFlags);
2539}
2540
2541
2542
2543
2544/*
2545 *
2546 *
2547 * TSC Delta Measurements And Related Code
2548 * TSC Delta Measurements And Related Code
2549 * TSC Delta Measurements And Related Code
2550 *
2551 *
2552 */
2553
2554
2555/*
2556 * Select TSC delta measurement algorithm.
2557 */
2558#if 0
2559# define GIP_TSC_DELTA_METHOD_1
2560#else
2561# define GIP_TSC_DELTA_METHOD_2
2562#endif
2563
2564/** For padding variables to keep them away from other cache lines. Better too
2565 * large than too small!
2566 * @remarks Current AMD64 and x86 CPUs seems to use 64 bytes. There are claims
2567 * that NetBurst had 128 byte cache lines while the 486 thru Pentium
2568 * III had 32 bytes cache lines. */
2569#define GIP_TSC_DELTA_CACHE_LINE_SIZE 128
2570
2571
2572/**
2573 * TSC delta measurement algorithm \#2 result entry.
2574 */
2575typedef struct SUPDRVTSCDELTAMETHOD2ENTRY
2576{
2577 uint32_t iSeqMine;
2578 uint32_t iSeqOther;
2579 uint64_t uTsc;
2580} SUPDRVTSCDELTAMETHOD2ENTRY;
2581
2582/**
2583 * TSC delta measurement algorithm \#2 Data.
2584 */
2585typedef struct SUPDRVTSCDELTAMETHOD2
2586{
2587 /** Padding to make sure the iCurSeqNo is in its own cache line. */
2588 uint64_t au64CacheLinePaddingBefore[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint64_t)];
2589 /** The current sequence number of this worker. */
2590 uint32_t volatile iCurSeqNo;
2591 /** Padding to make sure the iCurSeqNo is in its own cache line. */
2592 uint32_t au64CacheLinePaddingAfter[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint32_t) - 1];
2593 /** Result table. */
2594 SUPDRVTSCDELTAMETHOD2ENTRY aResults[64];
2595} SUPDRVTSCDELTAMETHOD2;
2596/** Pointer to the data for TSC delta measurement algorithm \#2 .*/
2597typedef SUPDRVTSCDELTAMETHOD2 *PSUPDRVTSCDELTAMETHOD2;
2598
2599
2600/**
2601 * The TSC delta synchronization struct, version 2.
2602 *
2603 * The synchronization variable is completely isolated in its own cache line
2604 * (provided our max cache line size estimate is correct).
2605 */
2606typedef struct SUPTSCDELTASYNC2
2607{
2608 /** Padding to make sure the uVar1 is in its own cache line. */
2609 uint64_t au64CacheLinePaddingBefore[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint64_t)];
2610
2611 /** The synchronization variable, holds values GIP_TSC_DELTA_SYNC_*. */
2612 volatile uint32_t uSyncVar;
2613 /** Sequence synchronizing variable used for post 'GO' synchronization. */
2614 volatile uint32_t uSyncSeq;
2615
2616 /** Padding to make sure the uVar1 is in its own cache line. */
2617 uint64_t au64CacheLinePaddingAfter[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint64_t) - 2];
2618
2619 /** Start RDTSC value. Put here mainly to save stack space. */
2620 uint64_t uTscStart;
2621 /** Copy of SUPDRVGIPTSCDELTARGS::cMaxTscTicks. */
2622 uint64_t cMaxTscTicks;
2623} SUPTSCDELTASYNC2;
2624AssertCompileSize(SUPTSCDELTASYNC2, GIP_TSC_DELTA_CACHE_LINE_SIZE * 2 + sizeof(uint64_t));
2625typedef SUPTSCDELTASYNC2 *PSUPTSCDELTASYNC2;
2626
2627/** Prestart wait. */
2628#define GIP_TSC_DELTA_SYNC2_PRESTART_WAIT UINT32_C(0x0ffe)
2629/** Prestart aborted. */
2630#define GIP_TSC_DELTA_SYNC2_PRESTART_ABORT UINT32_C(0x0fff)
2631/** Ready (on your mark). */
2632#define GIP_TSC_DELTA_SYNC2_READY UINT32_C(0x1000)
2633/** Steady (get set). */
2634#define GIP_TSC_DELTA_SYNC2_STEADY UINT32_C(0x1001)
2635/** Go! */
2636#define GIP_TSC_DELTA_SYNC2_GO UINT32_C(0x1002)
2637/** Used by the verification test. */
2638#define GIP_TSC_DELTA_SYNC2_GO_GO UINT32_C(0x1003)
2639
2640/** We reached the time limit. */
2641#define GIP_TSC_DELTA_SYNC2_TIMEOUT UINT32_C(0x1ffe)
2642/** The other party won't touch the sync struct ever again. */
2643#define GIP_TSC_DELTA_SYNC2_FINAL UINT32_C(0x1fff)
2644
2645
2646/**
2647 * Argument package/state passed by supdrvTscMeasureDeltaOne() to the RTMpOn
2648 * callback worker.
2649 * @todo add
2650 */
2651typedef struct SUPDRVGIPTSCDELTARGS
2652{
2653 /** The device extension. */
2654 PSUPDRVDEVEXT pDevExt;
2655 /** Pointer to the GIP CPU array entry for the worker. */
2656 PSUPGIPCPU pWorker;
2657 /** Pointer to the GIP CPU array entry for the master. */
2658 PSUPGIPCPU pMaster;
2659 /** The maximum number of ticks to spend in supdrvTscMeasureDeltaCallback.
2660 * (This is what we need a rough TSC frequency for.) */
2661 uint64_t cMaxTscTicks;
2662 /** Used to abort synchronization setup. */
2663 bool volatile fAbortSetup;
2664
2665 /** Padding to make sure the master variables live in its own cache lines. */
2666 uint64_t au64CacheLinePaddingBefore[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint64_t)];
2667
2668 /** @name Master
2669 * @{ */
2670 /** The time the master spent in the MP worker. */
2671 uint64_t cElapsedMasterTscTicks;
2672 /** The iTry value when stopped at. */
2673 uint32_t iTry;
2674 /** Set if the run timed out. */
2675 bool volatile fTimedOut;
2676 /** Pointer to the master's synchronization struct (on stack). */
2677 PSUPTSCDELTASYNC2 volatile pSyncMaster;
2678 /** Master data union. */
2679 union
2680 {
2681 /** Data (master) for delta verification. */
2682 struct
2683 {
2684 /** Verification test TSC values for the master. */
2685 uint64_t volatile auTscs[32];
2686 } Verify;
2687 /** Data (master) for measurement method \#2. */
2688 struct
2689 {
2690 /** Data and sequence number. */
2691 SUPDRVTSCDELTAMETHOD2 Data;
2692 /** The lag setting for the next run. */
2693 bool fLag;
2694 /** Number of hits. */
2695 uint32_t cHits;
2696 } M2;
2697 } uMaster;
2698 /** The verifier verdict, VINF_SUCCESS if ok, VERR_OUT_OF_RANGE if not,
2699 * VERR_TRY_AGAIN on timeout. */
2700 int32_t rcVerify;
2701#ifdef TSCDELTA_VERIFY_WITH_STATS
2702 /** The maximum difference between TSC read during delta verification. */
2703 int64_t cMaxVerifyTscTicks;
2704 /** The minimum difference between two TSC reads during verification. */
2705 int64_t cMinVerifyTscTicks;
2706 /** The bad TSC diff, worker relative to master (= worker - master).
2707 * Negative value means the worker is behind the master. */
2708 int64_t iVerifyBadTscDiff;
2709#endif
2710 /** @} */
2711
2712 /** Padding to make sure the worker variables live is in its own cache line. */
2713 uint64_t au64CacheLinePaddingBetween[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint64_t)];
2714
2715 /** @name Proletarian
2716 * @{ */
2717 /** Pointer to the worker's synchronization struct (on stack). */
2718 PSUPTSCDELTASYNC2 volatile pSyncWorker;
2719 /** The time the worker spent in the MP worker. */
2720 uint64_t cElapsedWorkerTscTicks;
2721 /** Worker data union. */
2722 union
2723 {
2724 /** Data (worker) for delta verification. */
2725 struct
2726 {
2727 /** Verification test TSC values for the worker. */
2728 uint64_t volatile auTscs[32];
2729 } Verify;
2730 /** Data (worker) for measurement method \#2. */
2731 struct
2732 {
2733 /** Data and sequence number. */
2734 SUPDRVTSCDELTAMETHOD2 Data;
2735 /** The lag setting for the next run (set by master). */
2736 bool fLag;
2737 } M2;
2738 } uWorker;
2739 /** @} */
2740
2741 /** Padding to make sure the above is in its own cache line. */
2742 uint64_t au64CacheLinePaddingAfter[GIP_TSC_DELTA_CACHE_LINE_SIZE / sizeof(uint64_t)];
2743} SUPDRVGIPTSCDELTARGS;
2744typedef SUPDRVGIPTSCDELTARGS *PSUPDRVGIPTSCDELTARGS;
2745
2746
2747/** @name Macros that implements the basic synchronization steps common to
2748 * the algorithms.
2749 *
2750 * Must be used from loop as the timeouts are implemented via 'break' statements
2751 * at the moment.
2752 *
2753 * @{
2754 */
2755#if defined(DEBUG_bird) /* || defined(VBOX_STRICT) */
2756# define TSCDELTA_DBG_VARS() uint32_t iDbgCounter
2757# define TSCDELTA_DBG_START_LOOP() do { iDbgCounter = 0; } while (0)
2758# define TSCDELTA_DBG_CHECK_LOOP() \
2759 do { iDbgCounter++; if ((iDbgCounter & UINT32_C(0x01ffffff)) == 0) RT_BREAKPOINT(); } while (0)
2760#else
2761# define TSCDELTA_DBG_VARS() ((void)0)
2762# define TSCDELTA_DBG_START_LOOP() ((void)0)
2763# define TSCDELTA_DBG_CHECK_LOOP() ((void)0)
2764#endif
2765#if 0
2766# define TSCDELTA_DBG_SYNC_MSG(a_Args) SUPR0Printf a_Args
2767#else
2768# define TSCDELTA_DBG_SYNC_MSG(a_Args) ((void)0)
2769#endif
2770#if 0
2771# define TSCDELTA_DBG_SYNC_MSG2(a_Args) SUPR0Printf a_Args
2772#else
2773# define TSCDELTA_DBG_SYNC_MSG2(a_Args) ((void)0)
2774#endif
2775#if 0
2776# define TSCDELTA_DBG_SYNC_MSG9(a_Args) SUPR0Printf a_Args
2777#else
2778# define TSCDELTA_DBG_SYNC_MSG9(a_Args) ((void)0)
2779#endif
2780
2781
2782static bool supdrvTscDeltaSync2_Before(PSUPTSCDELTASYNC2 pMySync, PSUPTSCDELTASYNC2 pOtherSync,
2783 bool fIsMaster, PRTCCUINTREG pfEFlags, PSUPDRVGIPTSCDELTARGS pArgs)
2784{
2785 uint32_t iMySeq = fIsMaster ? 0 : 256;
2786 uint32_t const iMaxSeq = iMySeq + 16; /* For the last loop, darn linux/freebsd C-ishness. */
2787 uint32_t u32Tmp;
2788 uint32_t iSync2Loops = 0;
2789 RTCCUINTREG fEFlags;
2790 TSCDELTA_DBG_VARS();
2791
2792 *pfEFlags = X86_EFL_IF | X86_EFL_1; /* should shut up most nagging compilers. */
2793
2794 /*
2795 * The master tells the worker to get on it's mark.
2796 */
2797 if (fIsMaster)
2798 {
2799 if (RT_LIKELY(ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_STEADY, GIP_TSC_DELTA_SYNC2_READY)))
2800 { /* likely*/ }
2801 else
2802 {
2803 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: #1 uSyncVar=%#x\n", fIsMaster ? "master" : "worker", pOtherSync->uSyncVar));
2804 return false;
2805 }
2806 }
2807
2808 /*
2809 * Wait for the on your mark signal (ack in the master case). We process timeouts here.
2810 */
2811 ASMAtomicWriteU32(&(pMySync)->uSyncSeq, 0);
2812 for (;;)
2813 {
2814 fEFlags = ASMIntDisableFlags();
2815 u32Tmp = ASMAtomicReadU32(&pMySync->uSyncVar);
2816 if (u32Tmp == GIP_TSC_DELTA_SYNC2_STEADY)
2817 break;
2818 ASMSetFlags(fEFlags);
2819 ASMNopPause();
2820
2821 /* Abort? */
2822 if (u32Tmp != GIP_TSC_DELTA_SYNC2_READY)
2823 {
2824 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: #2 u32Tmp=%#x\n", fIsMaster ? "master" : "worker", u32Tmp));
2825 return false;
2826 }
2827
2828 /* Check for timeouts every so often (not every loop in case RDTSC is
2829 trapping or something). Must check the first time around. */
2830#if 0 /* For debugging the timeout paths. */
2831 static uint32_t volatile xxx;
2832#endif
2833 if ( ( (iSync2Loops & 0x3ff) == 0
2834 && ASMReadTSC() - pMySync->uTscStart > pMySync->cMaxTscTicks)
2835#if 0 /* This is crazy, I know, but enable this code and the results are markedly better when enabled on the 1.4GHz AMD (debug). */
2836 || (!fIsMaster && (++xxx & 0xf) == 0)
2837#endif
2838 )
2839 {
2840 /* Try switch our own state into timeout mode so the master cannot tell us to 'GO',
2841 ignore the timeout if we've got the go ahead already (simpler). */
2842 if (ASMAtomicCmpXchgU32(&pMySync->uSyncVar, GIP_TSC_DELTA_SYNC2_TIMEOUT, GIP_TSC_DELTA_SYNC2_READY))
2843 {
2844 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: timeout\n", fIsMaster ? "master" : "worker"));
2845 ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_TIMEOUT, GIP_TSC_DELTA_SYNC2_STEADY);
2846 ASMAtomicWriteBool(&pArgs->fTimedOut, true);
2847 return false;
2848 }
2849 }
2850 iSync2Loops++;
2851 }
2852
2853 /*
2854 * Interrupts are now disabled and will remain disabled until we do
2855 * TSCDELTA_MASTER_SYNC_AFTER / TSCDELTA_OTHER_SYNC_AFTER.
2856 */
2857 *pfEFlags = fEFlags;
2858
2859 /*
2860 * The worker tells the master that it is on its mark and that the master
2861 * need to get into position as well.
2862 */
2863 if (!fIsMaster)
2864 {
2865 if (RT_LIKELY(ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_STEADY, GIP_TSC_DELTA_SYNC2_READY)))
2866 { /* likely */ }
2867 else
2868 {
2869 ASMSetFlags(fEFlags);
2870 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: #3 uSyncVar=%#x\n", fIsMaster ? "master" : "worker", pOtherSync->uSyncVar));
2871 return false;
2872 }
2873 }
2874
2875 /*
2876 * The master sends the 'go' to the worker and wait for ACK.
2877 */
2878 if (fIsMaster)
2879 {
2880 if (RT_LIKELY(ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_GO, GIP_TSC_DELTA_SYNC2_STEADY)))
2881 { /* likely */ }
2882 else
2883 {
2884 ASMSetFlags(fEFlags);
2885 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: #4 uSyncVar=%#x\n", fIsMaster ? "master" : "worker", pOtherSync->uSyncVar));
2886 return false;
2887 }
2888 }
2889
2890 /*
2891 * Wait for the 'go' signal (ack in the master case).
2892 */
2893 TSCDELTA_DBG_START_LOOP();
2894 for (;;)
2895 {
2896 u32Tmp = ASMAtomicReadU32(&pMySync->uSyncVar);
2897 if (u32Tmp == GIP_TSC_DELTA_SYNC2_GO)
2898 break;
2899 if (RT_LIKELY(u32Tmp == GIP_TSC_DELTA_SYNC2_STEADY))
2900 { /* likely */ }
2901 else
2902 {
2903 ASMSetFlags(fEFlags);
2904 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: #5 u32Tmp=%#x\n", fIsMaster ? "master" : "worker", u32Tmp));
2905 return false;
2906 }
2907
2908 TSCDELTA_DBG_CHECK_LOOP();
2909 ASMNopPause();
2910 }
2911
2912 /*
2913 * The worker acks the 'go' (shouldn't fail).
2914 */
2915 if (!fIsMaster)
2916 {
2917 if (RT_LIKELY(ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_GO, GIP_TSC_DELTA_SYNC2_STEADY)))
2918 { /* likely */ }
2919 else
2920 {
2921 ASMSetFlags(fEFlags);
2922 TSCDELTA_DBG_SYNC_MSG(("sync/before/%s: #6 uSyncVar=%#x\n", fIsMaster ? "master" : "worker", pOtherSync->uSyncVar));
2923 return false;
2924 }
2925 }
2926
2927 /*
2928 * Try enter mostly lockstep execution with it.
2929 */
2930 for (;;)
2931 {
2932 uint32_t iOtherSeq1, iOtherSeq2;
2933 ASMCompilerBarrier();
2934 ASMSerializeInstruction();
2935
2936 ASMAtomicWriteU32(&pMySync->uSyncSeq, iMySeq);
2937 ASMNopPause();
2938 iOtherSeq1 = ASMAtomicXchgU32(&pOtherSync->uSyncSeq, iMySeq);
2939 ASMNopPause();
2940 iOtherSeq2 = ASMAtomicReadU32(&pMySync->uSyncSeq);
2941
2942 ASMCompilerBarrier();
2943 if (iOtherSeq1 == iOtherSeq2)
2944 return true;
2945
2946 /* Did the other guy give up? Should we give up? */
2947 if ( iOtherSeq1 == UINT32_MAX
2948 || iOtherSeq2 == UINT32_MAX)
2949 return true;
2950 if (++iMySeq >= iMaxSeq)
2951 {
2952 ASMAtomicWriteU32(&pMySync->uSyncSeq, UINT32_MAX);
2953 return true;
2954 }
2955 ASMNopPause();
2956 }
2957}
2958
2959#define TSCDELTA_MASTER_SYNC_BEFORE(a_pMySync, a_pOtherSync, a_pfEFlags, a_pArgs) \
2960 if (RT_LIKELY(supdrvTscDeltaSync2_Before(a_pMySync, a_pOtherSync, true /*fIsMaster*/, a_pfEFlags, a_pArgs))) \
2961 { /*likely*/ } \
2962 else if (true) \
2963 { \
2964 TSCDELTA_DBG_SYNC_MSG9(("sync/before/master: #89\n")); \
2965 break; \
2966 } else do {} while (0)
2967#define TSCDELTA_OTHER_SYNC_BEFORE(a_pMySync, a_pOtherSync, a_pfEFlags, a_pArgs) \
2968 if (RT_LIKELY(supdrvTscDeltaSync2_Before(a_pMySync, a_pOtherSync, false /*fIsMaster*/, a_pfEFlags, a_pArgs))) \
2969 { /*likely*/ } \
2970 else if (true) \
2971 { \
2972 TSCDELTA_DBG_SYNC_MSG9(("sync/before/other: #89\n")); \
2973 break; \
2974 } else do {} while (0)
2975
2976
2977static bool supdrvTscDeltaSync2_After(PSUPTSCDELTASYNC2 pMySync, PSUPTSCDELTASYNC2 pOtherSync,
2978 bool fIsMaster, RTCCUINTREG fEFlags)
2979{
2980 TSCDELTA_DBG_VARS();
2981 RT_NOREF1(pOtherSync);
2982
2983 /*
2984 * Wait for the 'ready' signal. In the master's case, this means the
2985 * worker has completed its data collection, while in the worker's case it
2986 * means the master is done processing the data and it's time for the next
2987 * loop iteration (or whatever).
2988 */
2989 ASMSetFlags(fEFlags);
2990 TSCDELTA_DBG_START_LOOP();
2991 for (;;)
2992 {
2993 uint32_t u32Tmp = ASMAtomicReadU32(&pMySync->uSyncVar);
2994 if ( u32Tmp == GIP_TSC_DELTA_SYNC2_READY
2995 || (u32Tmp == GIP_TSC_DELTA_SYNC2_STEADY && !fIsMaster) /* kicked twice => race */ )
2996 return true;
2997 ASMNopPause();
2998 if (RT_LIKELY(u32Tmp == GIP_TSC_DELTA_SYNC2_GO))
2999 { /* likely */}
3000 else
3001 {
3002 TSCDELTA_DBG_SYNC_MSG(("sync/after/other: #1 u32Tmp=%#x\n", u32Tmp));
3003 return false; /* shouldn't ever happen! */
3004 }
3005 TSCDELTA_DBG_CHECK_LOOP();
3006 ASMNopPause();
3007 }
3008}
3009
3010#define TSCDELTA_MASTER_SYNC_AFTER(a_pMySync, a_pOtherSync, a_fEFlags) \
3011 if (RT_LIKELY(supdrvTscDeltaSync2_After(a_pMySync, a_pOtherSync, true /*fIsMaster*/, a_fEFlags))) \
3012 { /* likely */ } \
3013 else if (true) \
3014 { \
3015 TSCDELTA_DBG_SYNC_MSG9(("sync/after/master: #97\n")); \
3016 break; \
3017 } else do {} while (0)
3018
3019#define TSCDELTA_MASTER_KICK_OTHER_OUT_OF_AFTER(a_pMySync, a_pOtherSync) \
3020 /* \
3021 * Tell the worker that we're done processing the data and ready for the next round. \
3022 */ \
3023 if (RT_LIKELY(ASMAtomicCmpXchgU32(&(a_pOtherSync)->uSyncVar, GIP_TSC_DELTA_SYNC2_READY, GIP_TSC_DELTA_SYNC2_GO))) \
3024 { /* likely */ } \
3025 else if (true)\
3026 { \
3027 TSCDELTA_DBG_SYNC_MSG(("sync/after/master: #99 uSyncVar=%#x\n", (a_pOtherSync)->uSyncVar)); \
3028 break; \
3029 } else do {} while (0)
3030
3031#define TSCDELTA_OTHER_SYNC_AFTER(a_pMySync, a_pOtherSync, a_fEFlags) \
3032 if (true) { \
3033 /* \
3034 * Tell the master that we're done collecting data and wait for the next round to start. \
3035 */ \
3036 if (RT_LIKELY(ASMAtomicCmpXchgU32(&(a_pOtherSync)->uSyncVar, GIP_TSC_DELTA_SYNC2_READY, GIP_TSC_DELTA_SYNC2_GO))) \
3037 { /* likely */ } \
3038 else \
3039 { \
3040 ASMSetFlags(a_fEFlags); \
3041 TSCDELTA_DBG_SYNC_MSG(("sync/after/other: #0 uSyncVar=%#x\n", (a_pOtherSync)->uSyncVar)); \
3042 break; \
3043 } \
3044 if (RT_LIKELY(supdrvTscDeltaSync2_After(a_pMySync, a_pOtherSync, false /*fIsMaster*/, a_fEFlags))) \
3045 { /* likely */ } \
3046 else \
3047 { \
3048 TSCDELTA_DBG_SYNC_MSG9(("sync/after/other: #98\n")); \
3049 break; \
3050 } \
3051 } else do {} while (0)
3052/** @} */
3053
3054
3055#ifdef GIP_TSC_DELTA_METHOD_1
3056/**
3057 * TSC delta measurement algorithm \#1 (GIP_TSC_DELTA_METHOD_1).
3058 *
3059 *
3060 * We ignore the first few runs of the loop in order to prime the
3061 * cache. Also, we need to be careful about using 'pause' instruction
3062 * in critical busy-wait loops in this code - it can cause undesired
3063 * behaviour with hyperthreading.
3064 *
3065 * We try to minimize the measurement error by computing the minimum
3066 * read time of the compare statement in the worker by taking TSC
3067 * measurements across it.
3068 *
3069 * It must be noted that the computed minimum read time is mostly to
3070 * eliminate huge deltas when the worker is too early and doesn't by
3071 * itself help produce more accurate deltas. We allow two times the
3072 * computed minimum as an arbitrary acceptable threshold. Therefore,
3073 * it is still possible to get negative deltas where there are none
3074 * when the worker is earlier. As long as these occasional negative
3075 * deltas are lower than the time it takes to exit guest-context and
3076 * the OS to reschedule EMT on a different CPU, we won't expose a TSC
3077 * that jumped backwards. It is due to the existence of the negative
3078 * deltas that we don't recompute the delta with the master and
3079 * worker interchanged to eliminate the remaining measurement error.
3080 *
3081 *
3082 * @param pArgs The argument/state data.
3083 * @param pMySync My synchronization structure.
3084 * @param pOtherSync My partner's synchronization structure.
3085 * @param fIsMaster Set if master, clear if worker.
3086 * @param iTry The attempt number.
3087 */
3088static void supdrvTscDeltaMethod1Loop(PSUPDRVGIPTSCDELTARGS pArgs, PSUPTSCDELTASYNC2 pMySync, PSUPTSCDELTASYNC2 pOtherSync,
3089 bool fIsMaster, uint32_t iTry)
3090{
3091 PSUPGIPCPU pGipCpuWorker = pArgs->pWorker;
3092 PSUPGIPCPU pGipCpuMaster = pArgs->pMaster;
3093 uint64_t uMinCmpReadTime = UINT64_MAX;
3094 unsigned iLoop;
3095 NOREF(iTry);
3096
3097 for (iLoop = 0; iLoop < GIP_TSC_DELTA_LOOPS; iLoop++)
3098 {
3099 RTCCUINTREG fEFlags;
3100 if (fIsMaster)
3101 {
3102 /*
3103 * The master.
3104 */
3105 AssertMsg(pGipCpuMaster->u64TSCSample == GIP_TSC_DELTA_RSVD,
3106 ("%#llx idMaster=%#x idWorker=%#x (idGipMaster=%#x)\n",
3107 pGipCpuMaster->u64TSCSample, pGipCpuMaster->idCpu, pGipCpuWorker->idCpu, pArgs->pDevExt->idGipMaster));
3108 TSCDELTA_MASTER_SYNC_BEFORE(pMySync, pOtherSync, &fEFlags, pArgs);
3109
3110 do
3111 {
3112 ASMSerializeInstruction();
3113 ASMAtomicWriteU64(&pGipCpuMaster->u64TSCSample, ASMReadTSC());
3114 } while (pGipCpuMaster->u64TSCSample == GIP_TSC_DELTA_RSVD);
3115
3116 TSCDELTA_MASTER_SYNC_AFTER(pMySync, pOtherSync, fEFlags);
3117
3118 /* Process the data. */
3119 if (iLoop > GIP_TSC_DELTA_PRIMER_LOOPS + GIP_TSC_DELTA_READ_TIME_LOOPS)
3120 {
3121 if (pGipCpuWorker->u64TSCSample != GIP_TSC_DELTA_RSVD)
3122 {
3123 int64_t iDelta = pGipCpuWorker->u64TSCSample
3124 - (pGipCpuMaster->u64TSCSample - pGipCpuMaster->i64TSCDelta);
3125 if ( iDelta >= GIP_TSC_DELTA_INITIAL_MASTER_VALUE
3126 ? iDelta < pGipCpuWorker->i64TSCDelta
3127 : iDelta > pGipCpuWorker->i64TSCDelta || pGipCpuWorker->i64TSCDelta == INT64_MAX)
3128 pGipCpuWorker->i64TSCDelta = iDelta;
3129 }
3130 }
3131
3132 /* Reset our TSC sample and tell the worker to move on. */
3133 ASMAtomicWriteU64(&pGipCpuMaster->u64TSCSample, GIP_TSC_DELTA_RSVD);
3134 TSCDELTA_MASTER_KICK_OTHER_OUT_OF_AFTER(pMySync, pOtherSync);
3135 }
3136 else
3137 {
3138 /*
3139 * The worker.
3140 */
3141 uint64_t uTscWorker;
3142 uint64_t uTscWorkerFlushed;
3143 uint64_t uCmpReadTime;
3144
3145 ASMAtomicReadU64(&pGipCpuMaster->u64TSCSample); /* Warm the cache line. */
3146 TSCDELTA_OTHER_SYNC_BEFORE(pMySync, pOtherSync, &fEFlags, pArgs);
3147
3148 /*
3149 * Keep reading the TSC until we notice that the master has read his. Reading
3150 * the TSC -after- the master has updated the memory is way too late. We thus
3151 * compensate by trying to measure how long it took for the worker to notice
3152 * the memory flushed from the master.
3153 */
3154 do
3155 {
3156 ASMSerializeInstruction();
3157 uTscWorker = ASMReadTSC();
3158 } while (pGipCpuMaster->u64TSCSample == GIP_TSC_DELTA_RSVD);
3159 ASMSerializeInstruction();
3160 uTscWorkerFlushed = ASMReadTSC();
3161
3162 uCmpReadTime = uTscWorkerFlushed - uTscWorker;
3163 if (iLoop > GIP_TSC_DELTA_PRIMER_LOOPS + GIP_TSC_DELTA_READ_TIME_LOOPS)
3164 {
3165 /* This is totally arbitrary a.k.a I don't like it but I have no better ideas for now. */
3166 if (uCmpReadTime < (uMinCmpReadTime << 1))
3167 {
3168 ASMAtomicWriteU64(&pGipCpuWorker->u64TSCSample, uTscWorker);
3169 if (uCmpReadTime < uMinCmpReadTime)
3170 uMinCmpReadTime = uCmpReadTime;
3171 }
3172 else
3173 ASMAtomicWriteU64(&pGipCpuWorker->u64TSCSample, GIP_TSC_DELTA_RSVD);
3174 }
3175 else if (iLoop > GIP_TSC_DELTA_PRIMER_LOOPS)
3176 {
3177 if (uCmpReadTime < uMinCmpReadTime)
3178 uMinCmpReadTime = uCmpReadTime;
3179 }
3180
3181 TSCDELTA_OTHER_SYNC_AFTER(pMySync, pOtherSync, fEFlags);
3182 }
3183 }
3184
3185 TSCDELTA_DBG_SYNC_MSG9(("sync/method1loop/%s: #92 iLoop=%u MyState=%#x\n", fIsMaster ? "master" : "worker", iLoop,
3186 pMySync->uSyncVar));
3187
3188 /*
3189 * We must reset the worker TSC sample value in case it gets picked as a
3190 * GIP master later on (it's trashed above, naturally).
3191 */
3192 if (!fIsMaster)
3193 ASMAtomicWriteU64(&pGipCpuWorker->u64TSCSample, GIP_TSC_DELTA_RSVD);
3194}
3195#endif /* GIP_TSC_DELTA_METHOD_1 */
3196
3197
3198#ifdef GIP_TSC_DELTA_METHOD_2
3199/*
3200 * TSC delta measurement algorithm \#2 configuration and code - Experimental!!
3201 */
3202
3203# define GIP_TSC_DELTA_M2_LOOPS (7 + GIP_TSC_DELTA_M2_PRIMER_LOOPS)
3204# define GIP_TSC_DELTA_M2_PRIMER_LOOPS 0
3205
3206
3207static void supdrvTscDeltaMethod2ProcessDataOnMaster(PSUPDRVGIPTSCDELTARGS pArgs)
3208{
3209 int64_t iMasterTscDelta = pArgs->pMaster->i64TSCDelta;
3210 int64_t iBestDelta = pArgs->pWorker->i64TSCDelta;
3211 uint32_t idxResult;
3212 uint32_t cHits = 0;
3213
3214 /*
3215 * Look for matching entries in the master and worker tables.
3216 */
3217 for (idxResult = 0; idxResult < RT_ELEMENTS(pArgs->uMaster.M2.Data.aResults); idxResult++)
3218 {
3219 uint32_t idxOther = pArgs->uMaster.M2.Data.aResults[idxResult].iSeqOther;
3220 if (idxOther & 1)
3221 {
3222 idxOther >>= 1;
3223 if (idxOther < RT_ELEMENTS(pArgs->uWorker.M2.Data.aResults))
3224 {
3225 if (pArgs->uWorker.M2.Data.aResults[idxOther].iSeqOther == pArgs->uMaster.M2.Data.aResults[idxResult].iSeqMine)
3226 {
3227 int64_t iDelta;
3228 iDelta = pArgs->uWorker.M2.Data.aResults[idxOther].uTsc
3229 - (pArgs->uMaster.M2.Data.aResults[idxResult].uTsc - iMasterTscDelta);
3230 if ( iDelta >= GIP_TSC_DELTA_INITIAL_MASTER_VALUE
3231 ? iDelta < iBestDelta
3232 : iDelta > iBestDelta || iBestDelta == INT64_MAX)
3233 iBestDelta = iDelta;
3234 cHits++;
3235 }
3236 }
3237 }
3238 }
3239
3240 /*
3241 * Save the results.
3242 */
3243 if (cHits > 2)
3244 pArgs->pWorker->i64TSCDelta = iBestDelta;
3245 pArgs->uMaster.M2.cHits += cHits;
3246}
3247
3248
3249/**
3250 * The core function of the 2nd TSC delta measurement algorithm.
3251 *
3252 * The idea here is that we have the two CPUs execute the exact same code
3253 * collecting a largish set of TSC samples. The code has one data dependency on
3254 * the other CPU which intention it is to synchronize the execution as well as
3255 * help cross references the two sets of TSC samples (the sequence numbers).
3256 *
3257 * The @a fLag parameter is used to modify the execution a tiny bit on one or
3258 * both of the CPUs. When @a fLag differs between the CPUs, it is thought that
3259 * it will help with making the CPUs enter lock step execution occasionally.
3260 *
3261 */
3262static void supdrvTscDeltaMethod2CollectData(PSUPDRVTSCDELTAMETHOD2 pMyData, uint32_t volatile *piOtherSeqNo, bool fLag)
3263{
3264 SUPDRVTSCDELTAMETHOD2ENTRY *pEntry = &pMyData->aResults[0];
3265 uint32_t cLeft = RT_ELEMENTS(pMyData->aResults);
3266
3267 ASMAtomicWriteU32(&pMyData->iCurSeqNo, 0);
3268 ASMSerializeInstruction();
3269 while (cLeft-- > 0)
3270 {
3271 uint64_t uTsc;
3272 uint32_t iSeqMine = ASMAtomicIncU32(&pMyData->iCurSeqNo);
3273 uint32_t iSeqOther = ASMAtomicReadU32(piOtherSeqNo);
3274 ASMCompilerBarrier();
3275 ASMSerializeInstruction(); /* Way better result than with ASMMemoryFenceSSE2() in this position! */
3276 uTsc = ASMReadTSC();
3277 ASMAtomicIncU32(&pMyData->iCurSeqNo);
3278 ASMCompilerBarrier();
3279 ASMSerializeInstruction();
3280 pEntry->iSeqMine = iSeqMine;
3281 pEntry->iSeqOther = iSeqOther;
3282 pEntry->uTsc = uTsc;
3283 pEntry++;
3284 ASMSerializeInstruction();
3285 if (fLag)
3286 ASMNopPause();
3287 }
3288}
3289
3290
3291/**
3292 * TSC delta measurement algorithm \#2 (GIP_TSC_DELTA_METHOD_2).
3293 *
3294 * See supdrvTscDeltaMethod2CollectData for algorithm details.
3295 *
3296 * @param pArgs The argument/state data.
3297 * @param pMySync My synchronization structure.
3298 * @param pOtherSync My partner's synchronization structure.
3299 * @param fIsMaster Set if master, clear if worker.
3300 * @param iTry The attempt number.
3301 */
3302static void supdrvTscDeltaMethod2Loop(PSUPDRVGIPTSCDELTARGS pArgs, PSUPTSCDELTASYNC2 pMySync, PSUPTSCDELTASYNC2 pOtherSync,
3303 bool fIsMaster, uint32_t iTry)
3304{
3305 unsigned iLoop;
3306 RT_NOREF1(iTry);
3307
3308 for (iLoop = 0; iLoop < GIP_TSC_DELTA_M2_LOOPS; iLoop++)
3309 {
3310 RTCCUINTREG fEFlags;
3311 if (fIsMaster)
3312 {
3313 /*
3314 * Adjust the loop lag fudge.
3315 */
3316# if GIP_TSC_DELTA_M2_PRIMER_LOOPS > 0
3317 if (iLoop < GIP_TSC_DELTA_M2_PRIMER_LOOPS)
3318 {
3319 /* Lag during the priming to be nice to everyone.. */
3320 pArgs->uMaster.M2.fLag = true;
3321 pArgs->uWorker.M2.fLag = true;
3322 }
3323 else
3324# endif
3325 if (iLoop < (GIP_TSC_DELTA_M2_LOOPS - GIP_TSC_DELTA_M2_PRIMER_LOOPS) / 4)
3326 {
3327 /* 25 % of the body without lagging. */
3328 pArgs->uMaster.M2.fLag = false;
3329 pArgs->uWorker.M2.fLag = false;
3330 }
3331 else if (iLoop < (GIP_TSC_DELTA_M2_LOOPS - GIP_TSC_DELTA_M2_PRIMER_LOOPS) / 4 * 2)
3332 {
3333 /* 25 % of the body with both lagging. */
3334 pArgs->uMaster.M2.fLag = true;
3335 pArgs->uWorker.M2.fLag = true;
3336 }
3337 else
3338 {
3339 /* 50% of the body with alternating lag. */
3340 pArgs->uMaster.M2.fLag = (iLoop & 1) == 0;
3341 pArgs->uWorker.M2.fLag= (iLoop & 1) == 1;
3342 }
3343
3344 /*
3345 * Sync up with the worker and collect data.
3346 */
3347 TSCDELTA_MASTER_SYNC_BEFORE(pMySync, pOtherSync, &fEFlags, pArgs);
3348 supdrvTscDeltaMethod2CollectData(&pArgs->uMaster.M2.Data, &pArgs->uWorker.M2.Data.iCurSeqNo, pArgs->uMaster.M2.fLag);
3349 TSCDELTA_MASTER_SYNC_AFTER(pMySync, pOtherSync, fEFlags);
3350
3351 /*
3352 * Process the data.
3353 */
3354# if GIP_TSC_DELTA_M2_PRIMER_LOOPS > 0
3355 if (iLoop >= GIP_TSC_DELTA_M2_PRIMER_LOOPS)
3356# endif
3357 supdrvTscDeltaMethod2ProcessDataOnMaster(pArgs);
3358
3359 TSCDELTA_MASTER_KICK_OTHER_OUT_OF_AFTER(pMySync, pOtherSync);
3360 }
3361 else
3362 {
3363 /*
3364 * The worker.
3365 */
3366 TSCDELTA_OTHER_SYNC_BEFORE(pMySync, pOtherSync, &fEFlags, pArgs);
3367 supdrvTscDeltaMethod2CollectData(&pArgs->uWorker.M2.Data, &pArgs->uMaster.M2.Data.iCurSeqNo, pArgs->uWorker.M2.fLag);
3368 TSCDELTA_OTHER_SYNC_AFTER(pMySync, pOtherSync, fEFlags);
3369 }
3370 }
3371}
3372
3373#endif /* GIP_TSC_DELTA_METHOD_2 */
3374
3375
3376
3377static int supdrvTscDeltaVerify(PSUPDRVGIPTSCDELTARGS pArgs, PSUPTSCDELTASYNC2 pMySync,
3378 PSUPTSCDELTASYNC2 pOtherSync, bool fIsMaster, int64_t iWorkerTscDelta)
3379{
3380 /*PSUPGIPCPU pGipCpuWorker = pArgs->pWorker; - unused */
3381 PSUPGIPCPU pGipCpuMaster = pArgs->pMaster;
3382 uint32_t i;
3383 TSCDELTA_DBG_VARS();
3384
3385 for (;;)
3386 {
3387 RTCCUINTREG fEFlags;
3388 AssertCompile((RT_ELEMENTS(pArgs->uMaster.Verify.auTscs) & 1) == 0);
3389 AssertCompile(RT_ELEMENTS(pArgs->uMaster.Verify.auTscs) == RT_ELEMENTS(pArgs->uWorker.Verify.auTscs));
3390
3391 if (fIsMaster)
3392 {
3393 uint64_t uTscWorker;
3394 TSCDELTA_MASTER_SYNC_BEFORE(pMySync, pOtherSync, &fEFlags, pArgs);
3395
3396 /*
3397 * Collect TSC, master goes first.
3398 */
3399 for (i = 0; i < RT_ELEMENTS(pArgs->uMaster.Verify.auTscs); i += 2)
3400 {
3401 /* Read, kick & wait #1. */
3402 uint64_t register uTsc = ASMReadTSC();
3403 ASMAtomicWriteU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_GO_GO);
3404 ASMSerializeInstruction();
3405 pArgs->uMaster.Verify.auTscs[i] = uTsc;
3406 TSCDELTA_DBG_START_LOOP();
3407 while (ASMAtomicReadU32(&pMySync->uSyncVar) == GIP_TSC_DELTA_SYNC2_GO)
3408 {
3409 TSCDELTA_DBG_CHECK_LOOP();
3410 ASMNopPause();
3411 }
3412
3413 /* Read, kick & wait #2. */
3414 uTsc = ASMReadTSC();
3415 ASMAtomicWriteU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_GO);
3416 ASMSerializeInstruction();
3417 pArgs->uMaster.Verify.auTscs[i + 1] = uTsc;
3418 TSCDELTA_DBG_START_LOOP();
3419 while (ASMAtomicReadU32(&pMySync->uSyncVar) == GIP_TSC_DELTA_SYNC2_GO_GO)
3420 {
3421 TSCDELTA_DBG_CHECK_LOOP();
3422 ASMNopPause();
3423 }
3424 }
3425
3426 TSCDELTA_MASTER_SYNC_AFTER(pMySync, pOtherSync, fEFlags);
3427
3428 /*
3429 * Process the data.
3430 */
3431#ifdef TSCDELTA_VERIFY_WITH_STATS
3432 pArgs->cMaxVerifyTscTicks = INT64_MIN;
3433 pArgs->cMinVerifyTscTicks = INT64_MAX;
3434 pArgs->iVerifyBadTscDiff = 0;
3435#endif
3436 ASMAtomicWriteS32(&pArgs->rcVerify, VINF_SUCCESS);
3437 uTscWorker = 0;
3438 for (i = 0; i < RT_ELEMENTS(pArgs->uMaster.Verify.auTscs); i++)
3439 {
3440 /* Master vs previous worker entry. */
3441 uint64_t uTscMaster = pArgs->uMaster.Verify.auTscs[i] - pGipCpuMaster->i64TSCDelta;
3442 int64_t iDiff;
3443 if (i > 0)
3444 {
3445 iDiff = uTscMaster - uTscWorker;
3446#ifdef TSCDELTA_VERIFY_WITH_STATS
3447 if (iDiff > pArgs->cMaxVerifyTscTicks)
3448 pArgs->cMaxVerifyTscTicks = iDiff;
3449 if (iDiff < pArgs->cMinVerifyTscTicks)
3450 pArgs->cMinVerifyTscTicks = iDiff;
3451#endif
3452 if (iDiff < 0)
3453 {
3454#ifdef TSCDELTA_VERIFY_WITH_STATS
3455 pArgs->iVerifyBadTscDiff = -iDiff;
3456#endif
3457 ASMAtomicWriteS32(&pArgs->rcVerify, VERR_OUT_OF_RANGE);
3458 break;
3459 }
3460 }
3461
3462 /* Worker vs master. */
3463 uTscWorker = pArgs->uWorker.Verify.auTscs[i] - iWorkerTscDelta;
3464 iDiff = uTscWorker - uTscMaster;
3465#ifdef TSCDELTA_VERIFY_WITH_STATS
3466 if (iDiff > pArgs->cMaxVerifyTscTicks)
3467 pArgs->cMaxVerifyTscTicks = iDiff;
3468 if (iDiff < pArgs->cMinVerifyTscTicks)
3469 pArgs->cMinVerifyTscTicks = iDiff;
3470#endif
3471 if (iDiff < 0)
3472 {
3473#ifdef TSCDELTA_VERIFY_WITH_STATS
3474 pArgs->iVerifyBadTscDiff = iDiff;
3475#endif
3476 ASMAtomicWriteS32(&pArgs->rcVerify, VERR_OUT_OF_RANGE);
3477 break;
3478 }
3479 }
3480
3481 /* Done. */
3482 TSCDELTA_MASTER_KICK_OTHER_OUT_OF_AFTER(pMySync, pOtherSync);
3483 }
3484 else
3485 {
3486 /*
3487 * The worker, master leads.
3488 */
3489 TSCDELTA_OTHER_SYNC_BEFORE(pMySync, pOtherSync, &fEFlags, pArgs);
3490
3491 for (i = 0; i < RT_ELEMENTS(pArgs->uWorker.Verify.auTscs); i += 2)
3492 {
3493 uint64_t register uTsc;
3494
3495 /* Wait, Read and Kick #1. */
3496 TSCDELTA_DBG_START_LOOP();
3497 while (ASMAtomicReadU32(&pMySync->uSyncVar) == GIP_TSC_DELTA_SYNC2_GO)
3498 {
3499 TSCDELTA_DBG_CHECK_LOOP();
3500 ASMNopPause();
3501 }
3502 uTsc = ASMReadTSC();
3503 ASMAtomicWriteU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_GO_GO);
3504 ASMSerializeInstruction();
3505 pArgs->uWorker.Verify.auTscs[i] = uTsc;
3506
3507 /* Wait, Read and Kick #2. */
3508 TSCDELTA_DBG_START_LOOP();
3509 while (ASMAtomicReadU32(&pMySync->uSyncVar) == GIP_TSC_DELTA_SYNC2_GO_GO)
3510 {
3511 TSCDELTA_DBG_CHECK_LOOP();
3512 ASMNopPause();
3513 }
3514 uTsc = ASMReadTSC();
3515 ASMAtomicWriteU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_GO);
3516 ASMSerializeInstruction();
3517 pArgs->uWorker.Verify.auTscs[i + 1] = uTsc;
3518 }
3519
3520 TSCDELTA_OTHER_SYNC_AFTER(pMySync, pOtherSync, fEFlags);
3521 }
3522 return pArgs->rcVerify;
3523 }
3524
3525 /*
3526 * Timed out, please retry.
3527 */
3528 ASMAtomicWriteS32(&pArgs->rcVerify, VERR_TRY_AGAIN);
3529 return VERR_TIMEOUT;
3530}
3531
3532
3533
3534/**
3535 * Handles the special abort procedure during synchronization setup in
3536 * supdrvTscMeasureDeltaCallbackUnwrapped().
3537 *
3538 * @returns 0 (dummy, ignored)
3539 * @param pArgs Pointer to argument/state data.
3540 * @param pMySync Pointer to my sync structure.
3541 * @param fIsMaster Set if we're the master, clear if worker.
3542 * @param fTimeout Set if it's a timeout.
3543 */
3544DECL_NO_INLINE(static, int)
3545supdrvTscMeasureDeltaCallbackAbortSyncSetup(PSUPDRVGIPTSCDELTARGS pArgs, PSUPTSCDELTASYNC2 pMySync, bool fIsMaster, bool fTimeout)
3546{
3547 PSUPTSCDELTASYNC2 volatile *ppMySync = fIsMaster ? &pArgs->pSyncMaster : &pArgs->pSyncWorker;
3548 PSUPTSCDELTASYNC2 volatile *ppOtherSync = fIsMaster ? &pArgs->pSyncWorker : &pArgs->pSyncMaster;
3549 TSCDELTA_DBG_VARS();
3550 RT_NOREF1(pMySync);
3551
3552 /*
3553 * Clear our sync pointer and make sure the abort flag is set.
3554 */
3555 ASMAtomicWriteNullPtr(ppMySync);
3556 ASMAtomicWriteBool(&pArgs->fAbortSetup, true);
3557 if (fTimeout)
3558 ASMAtomicWriteBool(&pArgs->fTimedOut, true);
3559
3560 /*
3561 * Make sure the other party is out of there and won't be touching our
3562 * sync state again (would cause stack corruption).
3563 */
3564 TSCDELTA_DBG_START_LOOP();
3565 while (ASMAtomicReadPtrT(ppOtherSync, PSUPTSCDELTASYNC2) != NULL)
3566 {
3567 ASMNopPause();
3568 ASMNopPause();
3569 ASMNopPause();
3570 TSCDELTA_DBG_CHECK_LOOP();
3571 }
3572
3573 return 0;
3574}
3575
3576
3577/**
3578 * This is used by supdrvTscMeasureInitialDeltas() to read the TSC on two CPUs
3579 * and compute the delta between them.
3580 *
3581 * To reduce code size a good when timeout handling was added, a dummy return
3582 * value had to be added (saves 1-3 lines per timeout case), thus this
3583 * 'Unwrapped' function and the dummy 0 return value.
3584 *
3585 * @returns 0 (dummy, ignored)
3586 * @param idCpu The CPU we are current scheduled on.
3587 * @param pArgs Pointer to a parameter package.
3588 *
3589 * @remarks Measuring TSC deltas between the CPUs is tricky because we need to
3590 * read the TSC at exactly the same time on both the master and the
3591 * worker CPUs. Due to DMA, bus arbitration, cache locality,
3592 * contention, SMI, pipelining etc. there is no guaranteed way of
3593 * doing this on x86 CPUs.
3594 */
3595static int supdrvTscMeasureDeltaCallbackUnwrapped(RTCPUID idCpu, PSUPDRVGIPTSCDELTARGS pArgs)
3596{
3597 PSUPDRVDEVEXT pDevExt = pArgs->pDevExt;
3598 PSUPGIPCPU pGipCpuWorker = pArgs->pWorker;
3599 PSUPGIPCPU pGipCpuMaster = pArgs->pMaster;
3600 bool const fIsMaster = idCpu == pGipCpuMaster->idCpu;
3601 uint32_t iTry;
3602 PSUPTSCDELTASYNC2 volatile *ppMySync = fIsMaster ? &pArgs->pSyncMaster : &pArgs->pSyncWorker;
3603 PSUPTSCDELTASYNC2 volatile *ppOtherSync = fIsMaster ? &pArgs->pSyncWorker : &pArgs->pSyncMaster;
3604 SUPTSCDELTASYNC2 MySync;
3605 PSUPTSCDELTASYNC2 pOtherSync;
3606 int rc;
3607 TSCDELTA_DBG_VARS();
3608
3609 /* A bit of paranoia first. */
3610 if (!pGipCpuMaster || !pGipCpuWorker)
3611 return 0;
3612
3613 /*
3614 * If the CPU isn't part of the measurement, return immediately.
3615 */
3616 if ( !fIsMaster
3617 && idCpu != pGipCpuWorker->idCpu)
3618 return 0;
3619
3620 /*
3621 * Set up my synchronization stuff and wait for the other party to show up.
3622 *
3623 * We don't wait forever since the other party may be off fishing (offline,
3624 * spinning with ints disables, whatever), we must play nice to the rest of
3625 * the system as this context generally isn't one in which we will get
3626 * preempted and we may hold up a number of lower priority interrupts.
3627 */
3628 ASMAtomicWriteU32(&MySync.uSyncVar, GIP_TSC_DELTA_SYNC2_PRESTART_WAIT);
3629 ASMAtomicWritePtr(ppMySync, &MySync);
3630 MySync.uTscStart = ASMReadTSC();
3631 MySync.cMaxTscTicks = pArgs->cMaxTscTicks;
3632
3633 /* Look for the partner, might not be here yet... Special abort considerations. */
3634 iTry = 0;
3635 TSCDELTA_DBG_START_LOOP();
3636 while ((pOtherSync = ASMAtomicReadPtrT(ppOtherSync, PSUPTSCDELTASYNC2)) == NULL)
3637 {
3638 ASMNopPause();
3639 if ( ASMAtomicReadBool(&pArgs->fAbortSetup)
3640 || !RTMpIsCpuOnline(fIsMaster ? pGipCpuWorker->idCpu : pGipCpuMaster->idCpu) )
3641 return supdrvTscMeasureDeltaCallbackAbortSyncSetup(pArgs, &MySync, fIsMaster, false /*fTimeout*/);
3642 if ( (iTry++ & 0xff) == 0
3643 && ASMReadTSC() - MySync.uTscStart > pArgs->cMaxTscTicks)
3644 return supdrvTscMeasureDeltaCallbackAbortSyncSetup(pArgs, &MySync, fIsMaster, true /*fTimeout*/);
3645 TSCDELTA_DBG_CHECK_LOOP();
3646 ASMNopPause();
3647 }
3648
3649 /* I found my partner, waiting to be found... Special abort considerations. */
3650 if (fIsMaster)
3651 if (!ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_READY, GIP_TSC_DELTA_SYNC2_PRESTART_WAIT)) /* parnaoia */
3652 return supdrvTscMeasureDeltaCallbackAbortSyncSetup(pArgs, &MySync, fIsMaster, false /*fTimeout*/);
3653
3654 iTry = 0;
3655 TSCDELTA_DBG_START_LOOP();
3656 while (ASMAtomicReadU32(&MySync.uSyncVar) == GIP_TSC_DELTA_SYNC2_PRESTART_WAIT)
3657 {
3658 ASMNopPause();
3659 if (ASMAtomicReadBool(&pArgs->fAbortSetup))
3660 return supdrvTscMeasureDeltaCallbackAbortSyncSetup(pArgs, &MySync, fIsMaster, false /*fTimeout*/);
3661 if ( (iTry++ & 0xff) == 0
3662 && ASMReadTSC() - MySync.uTscStart > pArgs->cMaxTscTicks)
3663 {
3664 if ( fIsMaster
3665 && !ASMAtomicCmpXchgU32(&MySync.uSyncVar, GIP_TSC_DELTA_SYNC2_PRESTART_ABORT, GIP_TSC_DELTA_SYNC2_PRESTART_WAIT))
3666 break; /* race #1: slave has moved on, handle timeout in loop instead. */
3667 return supdrvTscMeasureDeltaCallbackAbortSyncSetup(pArgs, &MySync, fIsMaster, true /*fTimeout*/);
3668 }
3669 TSCDELTA_DBG_CHECK_LOOP();
3670 }
3671
3672 if (!fIsMaster)
3673 if (!ASMAtomicCmpXchgU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_READY, GIP_TSC_DELTA_SYNC2_PRESTART_WAIT)) /* race #1 */
3674 return supdrvTscMeasureDeltaCallbackAbortSyncSetup(pArgs, &MySync, fIsMaster, false /*fTimeout*/);
3675
3676/** @todo Add a resumable state to pArgs so we don't waste time if we time
3677 * out or something. Timeouts are legit, any of the two CPUs may get
3678 * interrupted. */
3679
3680 /*
3681 * Start by seeing if we have a zero delta between the two CPUs.
3682 * This should normally be the case.
3683 */
3684 rc = supdrvTscDeltaVerify(pArgs, &MySync, pOtherSync, fIsMaster, GIP_TSC_DELTA_INITIAL_MASTER_VALUE);
3685 if (RT_SUCCESS(rc))
3686 {
3687 if (fIsMaster)
3688 {
3689 ASMAtomicWriteS64(&pGipCpuWorker->i64TSCDelta, GIP_TSC_DELTA_INITIAL_MASTER_VALUE);
3690 RTCpuSetDelByIndex(&pDevExt->TscDeltaCpuSet, pGipCpuWorker->iCpuSet);
3691 RTCpuSetAddByIndex(&pDevExt->TscDeltaObtainedCpuSet, pGipCpuWorker->iCpuSet);
3692 }
3693 }
3694 /*
3695 * If the verification didn't time out, do regular delta measurements.
3696 * We retry this until we get a reasonable value.
3697 */
3698 else if (rc != VERR_TIMEOUT)
3699 {
3700 Assert(pGipCpuWorker->i64TSCDelta == INT64_MAX);
3701 for (iTry = 0; iTry < 12; iTry++)
3702 {
3703 /*
3704 * Check the state before we start.
3705 */
3706 uint32_t u32Tmp = ASMAtomicReadU32(&MySync.uSyncVar);
3707 if ( u32Tmp != GIP_TSC_DELTA_SYNC2_READY
3708 && (fIsMaster || u32Tmp != GIP_TSC_DELTA_SYNC2_STEADY) /* worker may be late prepping for the next round */ )
3709 {
3710 TSCDELTA_DBG_SYNC_MSG(("sync/loop/%s: #0 iTry=%u MyState=%#x\n", fIsMaster ? "master" : "worker", iTry, u32Tmp));
3711 break;
3712 }
3713
3714 /*
3715 * Do the measurements.
3716 */
3717#ifdef GIP_TSC_DELTA_METHOD_1
3718 supdrvTscDeltaMethod1Loop(pArgs, &MySync, pOtherSync, fIsMaster, iTry);
3719#elif defined(GIP_TSC_DELTA_METHOD_2)
3720 supdrvTscDeltaMethod2Loop(pArgs, &MySync, pOtherSync, fIsMaster, iTry);
3721#else
3722# error "huh??"
3723#endif
3724
3725 /*
3726 * Check the state.
3727 */
3728 u32Tmp = ASMAtomicReadU32(&MySync.uSyncVar);
3729 if ( u32Tmp != GIP_TSC_DELTA_SYNC2_READY
3730 && (fIsMaster || u32Tmp != GIP_TSC_DELTA_SYNC2_STEADY) /* worker may be late prepping for the next round */ )
3731 {
3732 if (fIsMaster)
3733 TSCDELTA_DBG_SYNC_MSG(("sync/loop/master: #1 iTry=%u MyState=%#x\n", iTry, u32Tmp));
3734 else
3735 TSCDELTA_DBG_SYNC_MSG2(("sync/loop/worker: #1 iTry=%u MyState=%#x\n", iTry, u32Tmp));
3736 break;
3737 }
3738
3739 /*
3740 * Success? If so, stop trying. Master decides.
3741 */
3742 if (fIsMaster)
3743 {
3744 if (pGipCpuWorker->i64TSCDelta != INT64_MAX)
3745 {
3746 RTCpuSetDelByIndex(&pDevExt->TscDeltaCpuSet, pGipCpuWorker->iCpuSet);
3747 RTCpuSetAddByIndex(&pDevExt->TscDeltaObtainedCpuSet, pGipCpuWorker->iCpuSet);
3748 TSCDELTA_DBG_SYNC_MSG2(("sync/loop/master: #9 iTry=%u MyState=%#x\n", iTry, MySync.uSyncVar));
3749 break;
3750 }
3751 }
3752 }
3753 if (fIsMaster)
3754 pArgs->iTry = iTry;
3755 }
3756
3757 /*
3758 * End the synchronization dance. We tell the other that we're done,
3759 * then wait for the same kind of reply.
3760 */
3761 ASMAtomicWriteU32(&pOtherSync->uSyncVar, GIP_TSC_DELTA_SYNC2_FINAL);
3762 ASMAtomicWriteNullPtr(ppMySync);
3763 iTry = 0;
3764 TSCDELTA_DBG_START_LOOP();
3765 while (ASMAtomicReadU32(&MySync.uSyncVar) != GIP_TSC_DELTA_SYNC2_FINAL)
3766 {
3767 iTry++;
3768 if ( iTry == 0
3769 && !RTMpIsCpuOnline(fIsMaster ? pGipCpuWorker->idCpu : pGipCpuMaster->idCpu))
3770 break; /* this really shouldn't happen. */
3771 TSCDELTA_DBG_CHECK_LOOP();
3772 ASMNopPause();
3773 }
3774
3775 /*
3776 * Collect some runtime stats.
3777 */
3778 if (fIsMaster)
3779 pArgs->cElapsedMasterTscTicks = ASMReadTSC() - MySync.uTscStart;
3780 else
3781 pArgs->cElapsedWorkerTscTicks = ASMReadTSC() - MySync.uTscStart;
3782 return 0;
3783}
3784
3785/**
3786 * Callback used by supdrvTscMeasureInitialDeltas() to read the TSC on two CPUs
3787 * and compute the delta between them.
3788 *
3789 * @param idCpu The CPU we are current scheduled on.
3790 * @param pvUser1 Pointer to a parameter package (SUPDRVGIPTSCDELTARGS).
3791 * @param pvUser2 Unused.
3792 */
3793static DECLCALLBACK(void) supdrvTscMeasureDeltaCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
3794{
3795 supdrvTscMeasureDeltaCallbackUnwrapped(idCpu, (PSUPDRVGIPTSCDELTARGS)pvUser1);
3796 RT_NOREF1(pvUser2);
3797}
3798
3799
3800/**
3801 * Measures the TSC delta between the master GIP CPU and one specified worker
3802 * CPU.
3803 *
3804 * @returns VBox status code.
3805 * @retval VERR_SUPDRV_TSC_DELTA_MEASUREMENT_FAILED on pure measurement
3806 * failure.
3807 * @param pDevExt Pointer to the device instance data.
3808 * @param idxWorker The index of the worker CPU from the GIP's array of
3809 * CPUs.
3810 *
3811 * @remarks This must be called with preemption enabled!
3812 */
3813static int supdrvTscMeasureDeltaOne(PSUPDRVDEVEXT pDevExt, uint32_t idxWorker)
3814{
3815 int rc;
3816 int rc2;
3817 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
3818 RTCPUID idMaster = pDevExt->idGipMaster;
3819 PSUPGIPCPU pGipCpuWorker = &pGip->aCPUs[idxWorker];
3820 PSUPGIPCPU pGipCpuMaster;
3821 uint32_t iGipCpuMaster;
3822 uint32_t u32Tmp;
3823
3824 /* Validate input a bit. */
3825 AssertReturn(pGip, VERR_INVALID_PARAMETER);
3826 Assert(pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED);
3827 Assert(RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3828
3829 /*
3830 * Don't attempt measuring the delta for the GIP master.
3831 */
3832 if (pGipCpuWorker->idCpu == idMaster)
3833 {
3834 if (pGipCpuWorker->i64TSCDelta == INT64_MAX) /* This shouldn't happen, but just in case. */
3835 ASMAtomicWriteS64(&pGipCpuWorker->i64TSCDelta, GIP_TSC_DELTA_INITIAL_MASTER_VALUE);
3836 return VINF_SUCCESS;
3837 }
3838
3839 /*
3840 * One measurement at a time, at least for now. We might be using
3841 * broadcast IPIs so, so be nice to the rest of the system.
3842 */
3843#ifdef SUPDRV_USE_MUTEX_FOR_GIP
3844 rc = RTSemMutexRequest(pDevExt->mtxTscDelta, RT_INDEFINITE_WAIT);
3845#else
3846 rc = RTSemFastMutexRequest(pDevExt->mtxTscDelta);
3847#endif
3848 if (RT_FAILURE(rc))
3849 return rc;
3850
3851 /*
3852 * If the CPU has hyper-threading and the APIC IDs of the master and worker are adjacent,
3853 * try pick a different master. (This fudge only works with multi core systems.)
3854 * ASSUMES related threads have adjacent APIC IDs. ASSUMES two threads per core.
3855 *
3856 * We skip this on AMDs for now as their HTT is different from Intel's and
3857 * it doesn't seem to have any favorable effect on the results.
3858 *
3859 * If the master is offline, we need a new master too, so share the code.
3860 */
3861 iGipCpuMaster = supdrvGipFindCpuIndexForCpuId(pGip, idMaster);
3862 AssertReturn(iGipCpuMaster < pGip->cCpus, VERR_INVALID_CPU_ID);
3863 pGipCpuMaster = &pGip->aCPUs[iGipCpuMaster];
3864 if ( ( (pGipCpuMaster->idApic & ~1) == (pGipCpuWorker->idApic & ~1)
3865 && pGip->cOnlineCpus > 2
3866 && ASMHasCpuId()
3867 && ASMIsValidStdRange(ASMCpuId_EAX(0))
3868 && (ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_HTT)
3869 && ( !ASMIsAmdCpu()
3870 || ASMGetCpuFamily(u32Tmp = ASMCpuId_EAX(1)) > 0x15
3871 || ( ASMGetCpuFamily(u32Tmp) == 0x15 /* Piledriver+, not bulldozer (FX-4150 didn't like it). */
3872 && ASMGetCpuModelAMD(u32Tmp) >= 0x02) ) )
3873 || !RTMpIsCpuOnline(idMaster) )
3874 {
3875 uint32_t i;
3876 for (i = 0; i < pGip->cCpus; i++)
3877 if ( i != iGipCpuMaster
3878 && i != idxWorker
3879 && pGip->aCPUs[i].enmState == SUPGIPCPUSTATE_ONLINE
3880 && pGip->aCPUs[i].i64TSCDelta != INT64_MAX
3881 && pGip->aCPUs[i].idCpu != NIL_RTCPUID
3882 && pGip->aCPUs[i].idCpu != idMaster /* paranoia starts here... */
3883 && pGip->aCPUs[i].idCpu != pGipCpuWorker->idCpu
3884 && pGip->aCPUs[i].idApic != pGipCpuWorker->idApic
3885 && pGip->aCPUs[i].idApic != pGipCpuMaster->idApic
3886 && RTMpIsCpuOnline(pGip->aCPUs[i].idCpu))
3887 {
3888 iGipCpuMaster = i;
3889 pGipCpuMaster = &pGip->aCPUs[i];
3890 idMaster = pGipCpuMaster->idCpu;
3891 break;
3892 }
3893 }
3894
3895 if (RTCpuSetIsMemberByIndex(&pGip->OnlineCpuSet, pGipCpuWorker->iCpuSet))
3896 {
3897 /*
3898 * Initialize data package for the RTMpOnPair callback.
3899 */
3900 PSUPDRVGIPTSCDELTARGS pArgs = (PSUPDRVGIPTSCDELTARGS)RTMemAllocZ(sizeof(*pArgs));
3901 if (pArgs)
3902 {
3903 pArgs->pWorker = pGipCpuWorker;
3904 pArgs->pMaster = pGipCpuMaster;
3905 pArgs->pDevExt = pDevExt;
3906 pArgs->pSyncMaster = NULL;
3907 pArgs->pSyncWorker = NULL;
3908 pArgs->cMaxTscTicks = ASMAtomicReadU64(&pGip->u64CpuHz) / 512; /* 1953 us */
3909
3910 /*
3911 * Do the RTMpOnPair call. We reset i64TSCDelta first so we
3912 * and supdrvTscMeasureDeltaCallback can use it as a success check.
3913 */
3914 /** @todo Store the i64TSCDelta result in pArgs first? Perhaps deals with
3915 * that when doing the restart loop reorg. */
3916 ASMAtomicWriteS64(&pGipCpuWorker->i64TSCDelta, INT64_MAX);
3917 rc = RTMpOnPair(pGipCpuMaster->idCpu, pGipCpuWorker->idCpu, RTMPON_F_CONCURRENT_EXEC,
3918 supdrvTscMeasureDeltaCallback, pArgs, NULL);
3919 if (RT_SUCCESS(rc))
3920 {
3921#if 0
3922 SUPR0Printf("mponpair ticks: %9llu %9llu max: %9llu iTry: %u%s\n", pArgs->cElapsedMasterTscTicks,
3923 pArgs->cElapsedWorkerTscTicks, pArgs->cMaxTscTicks, pArgs->iTry,
3924 pArgs->fTimedOut ? " timed out" :"");
3925#endif
3926#if 0
3927 SUPR0Printf("rcVerify=%d iVerifyBadTscDiff=%lld cMinVerifyTscTicks=%lld cMaxVerifyTscTicks=%lld\n",
3928 pArgs->rcVerify, pArgs->iVerifyBadTscDiff, pArgs->cMinVerifyTscTicks, pArgs->cMaxVerifyTscTicks);
3929#endif
3930 if (RT_LIKELY(pGipCpuWorker->i64TSCDelta != INT64_MAX))
3931 {
3932 /*
3933 * Work the TSC delta applicability rating. It starts
3934 * optimistic in supdrvGipInit, we downgrade it here.
3935 */
3936 SUPGIPUSETSCDELTA enmRating;
3937 if ( pGipCpuWorker->i64TSCDelta > GIP_TSC_DELTA_THRESHOLD_ROUGHLY_ZERO
3938 || pGipCpuWorker->i64TSCDelta < -GIP_TSC_DELTA_THRESHOLD_ROUGHLY_ZERO)
3939 enmRating = SUPGIPUSETSCDELTA_NOT_ZERO;
3940 else if ( pGipCpuWorker->i64TSCDelta > GIP_TSC_DELTA_THRESHOLD_PRACTICALLY_ZERO
3941 || pGipCpuWorker->i64TSCDelta < -GIP_TSC_DELTA_THRESHOLD_PRACTICALLY_ZERO)
3942 enmRating = SUPGIPUSETSCDELTA_ROUGHLY_ZERO;
3943 else
3944 enmRating = SUPGIPUSETSCDELTA_PRACTICALLY_ZERO;
3945 if (pGip->enmUseTscDelta < enmRating)
3946 {
3947 AssertCompile(sizeof(pGip->enmUseTscDelta) == sizeof(uint32_t));
3948 ASMAtomicWriteU32((uint32_t volatile *)&pGip->enmUseTscDelta, enmRating);
3949 }
3950 }
3951 else
3952 rc = VERR_SUPDRV_TSC_DELTA_MEASUREMENT_FAILED;
3953 }
3954 /** @todo return try-again if we get an offline CPU error. */
3955
3956 RTMemFree(pArgs);
3957 }
3958 else
3959 rc = VERR_NO_MEMORY;
3960 }
3961 else
3962 rc = VERR_CPU_OFFLINE;
3963
3964 /*
3965 * We're done now.
3966 */
3967#ifdef SUPDRV_USE_MUTEX_FOR_GIP
3968 rc2 = RTSemMutexRelease(pDevExt->mtxTscDelta); AssertRC(rc2);
3969#else
3970 rc2 = RTSemFastMutexRelease(pDevExt->mtxTscDelta); AssertRC(rc2);
3971#endif
3972 return rc;
3973}
3974
3975
3976/**
3977 * Resets the TSC-delta related TSC samples and optionally the deltas
3978 * themselves.
3979 *
3980 * @param pDevExt Pointer to the device instance data.
3981 * @param fResetTscDeltas Whether the TSC-deltas are also to be reset.
3982 *
3983 * @remarks This might be called while holding a spinlock!
3984 */
3985static void supdrvTscResetSamples(PSUPDRVDEVEXT pDevExt, bool fResetTscDeltas)
3986{
3987 unsigned iCpu;
3988 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
3989 for (iCpu = 0; iCpu < pGip->cCpus; iCpu++)
3990 {
3991 PSUPGIPCPU pGipCpu = &pGip->aCPUs[iCpu];
3992 ASMAtomicWriteU64(&pGipCpu->u64TSCSample, GIP_TSC_DELTA_RSVD);
3993 if (fResetTscDeltas)
3994 {
3995 RTCpuSetDelByIndex(&pDevExt->TscDeltaObtainedCpuSet, pGipCpu->iCpuSet);
3996 ASMAtomicWriteS64(&pGipCpu->i64TSCDelta, INT64_MAX);
3997 }
3998 }
3999}
4000
4001
4002/**
4003 * Picks an online CPU as the master TSC for TSC-delta computations.
4004 *
4005 * @returns VBox status code.
4006 * @param pDevExt Pointer to the device instance data.
4007 * @param pidxMaster Where to store the CPU array index of the chosen
4008 * master. Optional, can be NULL.
4009 */
4010static int supdrvTscPickMaster(PSUPDRVDEVEXT pDevExt, uint32_t *pidxMaster)
4011{
4012 /*
4013 * Pick the first CPU online as the master TSC and make it the new GIP master based
4014 * on the APIC ID.
4015 *
4016 * Technically we can simply use "idGipMaster" but doing this gives us master as CPU 0
4017 * in most cases making it nicer/easier for comparisons. It is safe to update the GIP
4018 * master as this point since the sync/async timer isn't created yet.
4019 */
4020 unsigned iCpu;
4021 uint32_t idxMaster = UINT32_MAX;
4022 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
4023 for (iCpu = 0; iCpu < RT_ELEMENTS(pGip->aiCpuFromApicId); iCpu++)
4024 {
4025 uint16_t idxCpu = pGip->aiCpuFromApicId[iCpu];
4026 if (idxCpu != UINT16_MAX)
4027 {
4028 PSUPGIPCPU pGipCpu = &pGip->aCPUs[idxCpu];
4029 if (RTCpuSetIsMemberByIndex(&pGip->OnlineCpuSet, pGipCpu->iCpuSet))
4030 {
4031 idxMaster = idxCpu;
4032 pGipCpu->i64TSCDelta = GIP_TSC_DELTA_INITIAL_MASTER_VALUE;
4033 ASMAtomicWriteSize(&pDevExt->idGipMaster, pGipCpu->idCpu);
4034 if (pidxMaster)
4035 *pidxMaster = idxMaster;
4036 return VINF_SUCCESS;
4037 }
4038 }
4039 }
4040 return VERR_CPU_OFFLINE;
4041}
4042
4043
4044/**
4045 * Performs the initial measurements of the TSC deltas between CPUs.
4046 *
4047 * This is called by supdrvGipCreate(), supdrvGipPowerNotificationCallback() or
4048 * triggered by it if threaded.
4049 *
4050 * @returns VBox status code.
4051 * @param pDevExt Pointer to the device instance data.
4052 *
4053 * @remarks Must be called only after supdrvGipInitOnCpu() as this function uses
4054 * idCpu, GIP's online CPU set which are populated in
4055 * supdrvGipInitOnCpu().
4056 */
4057static int supdrvTscMeasureInitialDeltas(PSUPDRVDEVEXT pDevExt)
4058{
4059 PSUPGIPCPU pGipCpuMaster;
4060 unsigned iCpu;
4061 unsigned iOddEven;
4062 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
4063 uint32_t idxMaster = UINT32_MAX;
4064 uint32_t cMpOnOffEvents = ASMAtomicReadU32(&pDevExt->cMpOnOffEvents);
4065
4066 Assert(pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED);
4067 supdrvTscResetSamples(pDevExt, true /* fClearDeltas */);
4068 int rc = supdrvTscPickMaster(pDevExt, &idxMaster);
4069 if (RT_FAILURE(rc))
4070 {
4071 SUPR0Printf("Failed to pick a CPU master for TSC-delta measurements rc=%Rrc\n", rc);
4072 return rc;
4073 }
4074 AssertReturn(idxMaster < pGip->cCpus, VERR_INVALID_CPU_INDEX);
4075 pGipCpuMaster = &pGip->aCPUs[idxMaster];
4076 Assert(pDevExt->idGipMaster == pGipCpuMaster->idCpu);
4077
4078 /*
4079 * If there is only a single CPU online we have nothing to do.
4080 */
4081 if (pGip->cOnlineCpus <= 1)
4082 {
4083 AssertReturn(pGip->cOnlineCpus > 0, VERR_INTERNAL_ERROR_5);
4084 return VINF_SUCCESS;
4085 }
4086
4087 /*
4088 * Loop thru the GIP CPU array and get deltas for each CPU (except the
4089 * master). We do the CPUs with the even numbered APIC IDs first so that
4090 * we've got alternative master CPUs to pick from on hyper-threaded systems.
4091 */
4092 for (iOddEven = 0; iOddEven < 2; iOddEven++)
4093 {
4094 for (iCpu = 0; iCpu < pGip->cCpus; iCpu++)
4095 {
4096 PSUPGIPCPU pGipCpuWorker = &pGip->aCPUs[iCpu];
4097 if ( iCpu != idxMaster
4098 && (iOddEven > 0 || (pGipCpuWorker->idApic & 1) == 0)
4099 && RTCpuSetIsMemberByIndex(&pDevExt->TscDeltaCpuSet, pGipCpuWorker->iCpuSet))
4100 {
4101 rc = supdrvTscMeasureDeltaOne(pDevExt, iCpu);
4102 if (RT_FAILURE(rc))
4103 {
4104 SUPR0Printf("supdrvTscMeasureDeltaOne failed. rc=%d CPU[%u].idCpu=%u Master[%u].idCpu=%u\n", rc, iCpu,
4105 pGipCpuWorker->idCpu, idxMaster, pDevExt->idGipMaster, pGipCpuMaster->idCpu);
4106 break;
4107 }
4108
4109 if (ASMAtomicReadU32(&pDevExt->cMpOnOffEvents) != cMpOnOffEvents)
4110 {
4111 SUPR0Printf("One or more CPUs transitioned between online & offline states. I'm confused, retry...\n");
4112 rc = VERR_TRY_AGAIN;
4113 break;
4114 }
4115 }
4116 }
4117 }
4118
4119 return rc;
4120}
4121
4122
4123#ifdef SUPDRV_USE_TSC_DELTA_THREAD
4124
4125/**
4126 * Switches the TSC-delta measurement thread into the butchered state.
4127 *
4128 * @returns VBox status code.
4129 * @param pDevExt Pointer to the device instance data.
4130 * @param fSpinlockHeld Whether the TSC-delta spinlock is held or not.
4131 * @param pszFailed An error message to log.
4132 * @param rcFailed The error code to exit the thread with.
4133 */
4134static int supdrvTscDeltaThreadButchered(PSUPDRVDEVEXT pDevExt, bool fSpinlockHeld, const char *pszFailed, int rcFailed)
4135{
4136 if (!fSpinlockHeld)
4137 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4138
4139 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Butchered;
4140 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4141 OSDBGPRINT(("supdrvTscDeltaThreadButchered: %s. rc=%Rrc\n", pszFailed, rcFailed));
4142 return rcFailed;
4143}
4144
4145
4146/**
4147 * The TSC-delta measurement thread.
4148 *
4149 * @returns VBox status code.
4150 * @param hThread The thread handle.
4151 * @param pvUser Opaque pointer to the device instance data.
4152 */
4153static DECLCALLBACK(int) supdrvTscDeltaThread(RTTHREAD hThread, void *pvUser)
4154{
4155 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
4156 uint32_t cConsecutiveTimeouts = 0;
4157 int rc = VERR_INTERNAL_ERROR_2;
4158 for (;;)
4159 {
4160 /*
4161 * Switch on the current state.
4162 */
4163 SUPDRVTSCDELTATHREADSTATE enmState;
4164 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4165 enmState = pDevExt->enmTscDeltaThreadState;
4166 switch (enmState)
4167 {
4168 case kTscDeltaThreadState_Creating:
4169 {
4170 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Listening;
4171 rc = RTSemEventSignal(pDevExt->hTscDeltaEvent);
4172 if (RT_FAILURE(rc))
4173 return supdrvTscDeltaThreadButchered(pDevExt, true /* fSpinlockHeld */, "RTSemEventSignal", rc);
4174 /* fall thru */
4175 }
4176
4177 case kTscDeltaThreadState_Listening:
4178 {
4179 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4180
4181 /*
4182 * Linux counts uninterruptible sleeps as load, hence we shall do a
4183 * regular, interruptible sleep here and ignore wake ups due to signals.
4184 * See task_contributes_to_load() in include/linux/sched.h in the Linux sources.
4185 */
4186 rc = RTThreadUserWaitNoResume(hThread, pDevExt->cMsTscDeltaTimeout);
4187 if ( RT_FAILURE(rc)
4188 && rc != VERR_TIMEOUT
4189 && rc != VERR_INTERRUPTED)
4190 return supdrvTscDeltaThreadButchered(pDevExt, false /* fSpinlockHeld */, "RTThreadUserWait", rc);
4191 RTThreadUserReset(hThread);
4192 break;
4193 }
4194
4195 case kTscDeltaThreadState_WaitAndMeasure:
4196 {
4197 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Measuring;
4198 rc = RTSemEventSignal(pDevExt->hTscDeltaEvent); /* (Safe on windows as long as spinlock isn't IRQ safe.) */
4199 if (RT_FAILURE(rc))
4200 return supdrvTscDeltaThreadButchered(pDevExt, true /* fSpinlockHeld */, "RTSemEventSignal", rc);
4201 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4202 RTThreadSleep(1);
4203 /* fall thru */
4204 }
4205
4206 case kTscDeltaThreadState_Measuring:
4207 {
4208 cConsecutiveTimeouts = 0;
4209 if (pDevExt->fTscThreadRecomputeAllDeltas)
4210 {
4211 int cTries = 8;
4212 int cMsWaitPerTry = 10;
4213 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
4214 Assert(pGip);
4215 do
4216 {
4217 RTCpuSetCopy(&pDevExt->TscDeltaCpuSet, &pGip->OnlineCpuSet);
4218 rc = supdrvTscMeasureInitialDeltas(pDevExt);
4219 if ( RT_SUCCESS(rc)
4220 || ( RT_FAILURE(rc)
4221 && rc != VERR_TRY_AGAIN
4222 && rc != VERR_CPU_OFFLINE))
4223 {
4224 break;
4225 }
4226 RTThreadSleep(cMsWaitPerTry);
4227 } while (cTries-- > 0);
4228 pDevExt->fTscThreadRecomputeAllDeltas = false;
4229 }
4230 else
4231 {
4232 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
4233 unsigned iCpu;
4234
4235 /* Measure TSC-deltas only for the CPUs that are in the set. */
4236 rc = VINF_SUCCESS;
4237 for (iCpu = 0; iCpu < pGip->cCpus; iCpu++)
4238 {
4239 PSUPGIPCPU pGipCpuWorker = &pGip->aCPUs[iCpu];
4240 if (RTCpuSetIsMemberByIndex(&pDevExt->TscDeltaCpuSet, pGipCpuWorker->iCpuSet))
4241 {
4242 if (pGipCpuWorker->i64TSCDelta == INT64_MAX)
4243 {
4244 int rc2 = supdrvTscMeasureDeltaOne(pDevExt, iCpu);
4245 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4246 rc = rc2;
4247 }
4248 else
4249 {
4250 /*
4251 * The thread/someone must've called SUPR0TscDeltaMeasureBySetIndex(),
4252 * mark the delta as fine to get the timer thread off our back.
4253 */
4254 RTCpuSetDelByIndex(&pDevExt->TscDeltaCpuSet, pGipCpuWorker->iCpuSet);
4255 RTCpuSetAddByIndex(&pDevExt->TscDeltaObtainedCpuSet, pGipCpuWorker->iCpuSet);
4256 }
4257 }
4258 }
4259 }
4260 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4261 if (pDevExt->enmTscDeltaThreadState == kTscDeltaThreadState_Measuring)
4262 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Listening;
4263 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4264 Assert(rc != VERR_NOT_AVAILABLE); /* VERR_NOT_AVAILABLE is used as init value, see supdrvTscDeltaThreadInit(). */
4265 ASMAtomicWriteS32(&pDevExt->rcTscDelta, rc);
4266 break;
4267 }
4268
4269 case kTscDeltaThreadState_Terminating:
4270 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Destroyed;
4271 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4272 return VINF_SUCCESS;
4273
4274 case kTscDeltaThreadState_Butchered:
4275 default:
4276 return supdrvTscDeltaThreadButchered(pDevExt, true /* fSpinlockHeld */, "Invalid state", VERR_INVALID_STATE);
4277 }
4278 }
4279 /* not reached */
4280}
4281
4282
4283/**
4284 * Waits for the TSC-delta measurement thread to respond to a state change.
4285 *
4286 * @returns VINF_SUCCESS on success, VERR_TIMEOUT if it doesn't respond in time,
4287 * other error code on internal error.
4288 *
4289 * @param pDevExt The device instance data.
4290 * @param enmCurState The current state.
4291 * @param enmNewState The new state we're waiting for it to enter.
4292 */
4293static int supdrvTscDeltaThreadWait(PSUPDRVDEVEXT pDevExt, SUPDRVTSCDELTATHREADSTATE enmCurState,
4294 SUPDRVTSCDELTATHREADSTATE enmNewState)
4295{
4296 SUPDRVTSCDELTATHREADSTATE enmActualState;
4297 int rc;
4298
4299 /*
4300 * Wait a short while for the expected state transition.
4301 */
4302 RTSemEventWait(pDevExt->hTscDeltaEvent, RT_MS_1SEC);
4303 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4304 enmActualState = pDevExt->enmTscDeltaThreadState;
4305 if (enmActualState == enmNewState)
4306 {
4307 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4308 rc = VINF_SUCCESS;
4309 }
4310 else if (enmActualState == enmCurState)
4311 {
4312 /*
4313 * Wait longer if the state has not yet transitioned to the one we want.
4314 */
4315 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4316 rc = RTSemEventWait(pDevExt->hTscDeltaEvent, 50 * RT_MS_1SEC);
4317 if ( RT_SUCCESS(rc)
4318 || rc == VERR_TIMEOUT)
4319 {
4320 /*
4321 * Check the state whether we've succeeded.
4322 */
4323 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4324 enmActualState = pDevExt->enmTscDeltaThreadState;
4325 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4326 if (enmActualState == enmNewState)
4327 rc = VINF_SUCCESS;
4328 else if (enmActualState == enmCurState)
4329 {
4330 rc = VERR_TIMEOUT;
4331 OSDBGPRINT(("supdrvTscDeltaThreadWait: timed out state transition. enmActualState=%d enmNewState=%d\n",
4332 enmActualState, enmNewState));
4333 }
4334 else
4335 {
4336 rc = VERR_INTERNAL_ERROR;
4337 OSDBGPRINT(("supdrvTscDeltaThreadWait: invalid state transition from %d to %d, expected %d\n", enmCurState,
4338 enmActualState, enmNewState));
4339 }
4340 }
4341 else
4342 OSDBGPRINT(("supdrvTscDeltaThreadWait: RTSemEventWait failed. rc=%Rrc\n", rc));
4343 }
4344 else
4345 {
4346 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4347 OSDBGPRINT(("supdrvTscDeltaThreadWait: invalid state %d when transitioning from %d to %d\n",
4348 enmActualState, enmCurState, enmNewState));
4349 rc = VERR_INTERNAL_ERROR;
4350 }
4351
4352 return rc;
4353}
4354
4355
4356/**
4357 * Signals the TSC-delta thread to start measuring TSC-deltas.
4358 *
4359 * @param pDevExt Pointer to the device instance data.
4360 * @param fForceAll Force re-calculating TSC-deltas on all CPUs.
4361 */
4362static void supdrvTscDeltaThreadStartMeasurement(PSUPDRVDEVEXT pDevExt, bool fForceAll)
4363{
4364 if (pDevExt->hTscDeltaThread != NIL_RTTHREAD)
4365 {
4366 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4367 if ( pDevExt->enmTscDeltaThreadState == kTscDeltaThreadState_Listening
4368 || pDevExt->enmTscDeltaThreadState == kTscDeltaThreadState_Measuring)
4369 {
4370 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_WaitAndMeasure;
4371 if (fForceAll)
4372 pDevExt->fTscThreadRecomputeAllDeltas = true;
4373 }
4374 else if ( pDevExt->enmTscDeltaThreadState == kTscDeltaThreadState_WaitAndMeasure
4375 && fForceAll)
4376 pDevExt->fTscThreadRecomputeAllDeltas = true;
4377 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4378 RTThreadUserSignal(pDevExt->hTscDeltaThread);
4379 }
4380}
4381
4382
4383/**
4384 * Terminates the actual thread running supdrvTscDeltaThread().
4385 *
4386 * This is an internal worker function for supdrvTscDeltaThreadInit() and
4387 * supdrvTscDeltaTerm().
4388 *
4389 * @param pDevExt Pointer to the device instance data.
4390 */
4391static void supdrvTscDeltaThreadTerminate(PSUPDRVDEVEXT pDevExt)
4392{
4393 int rc;
4394 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4395 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Terminating;
4396 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4397 RTThreadUserSignal(pDevExt->hTscDeltaThread);
4398 rc = RTThreadWait(pDevExt->hTscDeltaThread, 50 * RT_MS_1SEC, NULL /* prc */);
4399 if (RT_FAILURE(rc))
4400 {
4401 /* Signal a few more times before giving up. */
4402 int cTriesLeft = 5;
4403 while (--cTriesLeft > 0)
4404 {
4405 RTThreadUserSignal(pDevExt->hTscDeltaThread);
4406 rc = RTThreadWait(pDevExt->hTscDeltaThread, 2 * RT_MS_1SEC, NULL /* prc */);
4407 if (rc != VERR_TIMEOUT)
4408 break;
4409 }
4410 }
4411}
4412
4413
4414/**
4415 * Initializes and spawns the TSC-delta measurement thread.
4416 *
4417 * A thread is required for servicing re-measurement requests from events like
4418 * CPUs coming online, suspend/resume etc. as it cannot be done synchronously
4419 * under all contexts on all OSs.
4420 *
4421 * @returns VBox status code.
4422 * @param pDevExt Pointer to the device instance data.
4423 *
4424 * @remarks Must only be called -after- initializing GIP and setting up MP
4425 * notifications!
4426 */
4427static int supdrvTscDeltaThreadInit(PSUPDRVDEVEXT pDevExt)
4428{
4429 int rc;
4430 Assert(pDevExt->pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED);
4431 rc = RTSpinlockCreate(&pDevExt->hTscDeltaSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_UNSAFE, "VBoxTscSpnLck");
4432 if (RT_SUCCESS(rc))
4433 {
4434 rc = RTSemEventCreate(&pDevExt->hTscDeltaEvent);
4435 if (RT_SUCCESS(rc))
4436 {
4437 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_Creating;
4438 pDevExt->cMsTscDeltaTimeout = 60000;
4439 rc = RTThreadCreate(&pDevExt->hTscDeltaThread, supdrvTscDeltaThread, pDevExt, 0 /* cbStack */,
4440 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "VBoxTscThread");
4441 if (RT_SUCCESS(rc))
4442 {
4443 rc = supdrvTscDeltaThreadWait(pDevExt, kTscDeltaThreadState_Creating, kTscDeltaThreadState_Listening);
4444 if (RT_SUCCESS(rc))
4445 {
4446 ASMAtomicWriteS32(&pDevExt->rcTscDelta, VERR_NOT_AVAILABLE);
4447 return rc;
4448 }
4449
4450 OSDBGPRINT(("supdrvTscDeltaInit: supdrvTscDeltaThreadWait failed. rc=%Rrc\n", rc));
4451 supdrvTscDeltaThreadTerminate(pDevExt);
4452 }
4453 else
4454 OSDBGPRINT(("supdrvTscDeltaInit: RTThreadCreate failed. rc=%Rrc\n", rc));
4455 RTSemEventDestroy(pDevExt->hTscDeltaEvent);
4456 pDevExt->hTscDeltaEvent = NIL_RTSEMEVENT;
4457 }
4458 else
4459 OSDBGPRINT(("supdrvTscDeltaInit: RTSemEventCreate failed. rc=%Rrc\n", rc));
4460 RTSpinlockDestroy(pDevExt->hTscDeltaSpinlock);
4461 pDevExt->hTscDeltaSpinlock = NIL_RTSPINLOCK;
4462 }
4463 else
4464 OSDBGPRINT(("supdrvTscDeltaInit: RTSpinlockCreate failed. rc=%Rrc\n", rc));
4465
4466 return rc;
4467}
4468
4469
4470/**
4471 * Terminates the TSC-delta measurement thread and cleanup.
4472 *
4473 * @param pDevExt Pointer to the device instance data.
4474 */
4475static void supdrvTscDeltaTerm(PSUPDRVDEVEXT pDevExt)
4476{
4477 if ( pDevExt->hTscDeltaSpinlock != NIL_RTSPINLOCK
4478 && pDevExt->hTscDeltaEvent != NIL_RTSEMEVENT)
4479 {
4480 supdrvTscDeltaThreadTerminate(pDevExt);
4481 }
4482
4483 if (pDevExt->hTscDeltaSpinlock != NIL_RTSPINLOCK)
4484 {
4485 RTSpinlockDestroy(pDevExt->hTscDeltaSpinlock);
4486 pDevExt->hTscDeltaSpinlock = NIL_RTSPINLOCK;
4487 }
4488
4489 if (pDevExt->hTscDeltaEvent != NIL_RTSEMEVENT)
4490 {
4491 RTSemEventDestroy(pDevExt->hTscDeltaEvent);
4492 pDevExt->hTscDeltaEvent = NIL_RTSEMEVENT;
4493 }
4494
4495 ASMAtomicWriteS32(&pDevExt->rcTscDelta, VERR_NOT_AVAILABLE);
4496}
4497
4498#endif /* SUPDRV_USE_TSC_DELTA_THREAD */
4499
4500/**
4501 * Measure the TSC delta for the CPU given by its CPU set index.
4502 *
4503 * @returns VBox status code.
4504 * @retval VERR_INTERRUPTED if interrupted while waiting.
4505 * @retval VERR_SUPDRV_TSC_DELTA_MEASUREMENT_FAILED if we were unable to get a
4506 * measurement.
4507 * @retval VERR_CPU_OFFLINE if the specified CPU is offline.
4508 *
4509 * @param pSession The caller's session. GIP must've been mapped.
4510 * @param iCpuSet The CPU set index of the CPU to measure.
4511 * @param fFlags Flags, SUP_TSCDELTA_MEASURE_F_XXX.
4512 * @param cMsWaitRetry Number of milliseconds to wait between each retry.
4513 * @param cMsWaitThread Number of milliseconds to wait for the thread to get
4514 * ready.
4515 * @param cTries Number of times to try, pass 0 for the default.
4516 */
4517SUPR0DECL(int) SUPR0TscDeltaMeasureBySetIndex(PSUPDRVSESSION pSession, uint32_t iCpuSet, uint32_t fFlags,
4518 RTMSINTERVAL cMsWaitRetry, RTMSINTERVAL cMsWaitThread, uint32_t cTries)
4519{
4520 PSUPDRVDEVEXT pDevExt;
4521 PSUPGLOBALINFOPAGE pGip;
4522 uint16_t iGipCpu;
4523 int rc;
4524#ifdef SUPDRV_USE_TSC_DELTA_THREAD
4525 uint64_t msTsStartWait;
4526 uint32_t iWaitLoop;
4527#endif
4528
4529 /*
4530 * Validate and adjust the input.
4531 */
4532 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4533 if (!pSession->fGipReferenced)
4534 return VERR_WRONG_ORDER;
4535
4536 pDevExt = pSession->pDevExt;
4537 AssertReturn(SUP_IS_DEVEXT_VALID(pDevExt), VERR_INVALID_PARAMETER);
4538
4539 pGip = pDevExt->pGip;
4540 AssertPtrReturn(pGip, VERR_INTERNAL_ERROR_2);
4541
4542 AssertReturn(iCpuSet < RTCPUSET_MAX_CPUS, VERR_INVALID_CPU_INDEX);
4543 AssertReturn(iCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx), VERR_INVALID_CPU_INDEX);
4544 iGipCpu = pGip->aiCpuFromCpuSetIdx[iCpuSet];
4545 AssertReturn(iGipCpu < pGip->cCpus, VERR_INVALID_CPU_INDEX);
4546
4547 if (fFlags & ~SUP_TSCDELTA_MEASURE_F_VALID_MASK)
4548 return VERR_INVALID_FLAGS;
4549
4550 /*
4551 * The request is a noop if the TSC delta isn't being used.
4552 */
4553 if (pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_ZERO_CLAIMED)
4554 return VINF_SUCCESS;
4555
4556 if (cTries == 0)
4557 cTries = 12;
4558 else if (cTries > 256)
4559 cTries = 256;
4560
4561 if (cMsWaitRetry == 0)
4562 cMsWaitRetry = 2;
4563 else if (cMsWaitRetry > 1000)
4564 cMsWaitRetry = 1000;
4565
4566#ifdef SUPDRV_USE_TSC_DELTA_THREAD
4567 /*
4568 * Has the TSC already been measured and we're not forced to redo it?
4569 */
4570 if ( pGip->aCPUs[iGipCpu].i64TSCDelta != INT64_MAX
4571 && !(fFlags & SUP_TSCDELTA_MEASURE_F_FORCE))
4572 return VINF_SUCCESS;
4573
4574 /*
4575 * Asynchronous request? Forward it to the thread, no waiting.
4576 */
4577 if (fFlags & SUP_TSCDELTA_MEASURE_F_ASYNC)
4578 {
4579 /** @todo Async. doesn't implement options like retries, waiting. We'll need
4580 * to pass those options to the thread somehow and implement it in the
4581 * thread. Check if anyone uses/needs fAsync before implementing this. */
4582 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4583 RTCpuSetAddByIndex(&pDevExt->TscDeltaCpuSet, iCpuSet);
4584 if ( pDevExt->enmTscDeltaThreadState == kTscDeltaThreadState_Listening
4585 || pDevExt->enmTscDeltaThreadState == kTscDeltaThreadState_Measuring)
4586 {
4587 pDevExt->enmTscDeltaThreadState = kTscDeltaThreadState_WaitAndMeasure;
4588 rc = VINF_SUCCESS;
4589 }
4590 else if (pDevExt->enmTscDeltaThreadState != kTscDeltaThreadState_WaitAndMeasure)
4591 rc = VERR_THREAD_IS_DEAD;
4592 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4593 RTThreadUserSignal(pDevExt->hTscDeltaThread);
4594 return VINF_SUCCESS;
4595 }
4596
4597 /*
4598 * If a TSC-delta measurement request is already being serviced by the thread,
4599 * wait 'cTries' times if a retry-timeout is provided, otherwise bail as busy.
4600 */
4601 msTsStartWait = RTTimeSystemMilliTS();
4602 for (iWaitLoop = 0;; iWaitLoop++)
4603 {
4604 uint64_t cMsElapsed;
4605 SUPDRVTSCDELTATHREADSTATE enmState;
4606 RTSpinlockAcquire(pDevExt->hTscDeltaSpinlock);
4607 enmState = pDevExt->enmTscDeltaThreadState;
4608 RTSpinlockRelease(pDevExt->hTscDeltaSpinlock);
4609
4610 if (enmState == kTscDeltaThreadState_Measuring)
4611 { /* Must wait, the thread is busy. */ }
4612 else if (enmState == kTscDeltaThreadState_WaitAndMeasure)
4613 { /* Must wait, this state only says what will happen next. */ }
4614 else if (enmState == kTscDeltaThreadState_Terminating)
4615 { /* Must wait, this state only says what should happen next. */ }
4616 else
4617 break; /* All other states, the thread is either idly listening or dead. */
4618
4619 /* Wait or fail. */
4620 if (cMsWaitThread == 0)
4621 return VERR_SUPDRV_TSC_DELTA_MEASUREMENT_BUSY;
4622 cMsElapsed = RTTimeSystemMilliTS() - msTsStartWait;
4623 if (cMsElapsed >= cMsWaitThread)
4624 return VERR_SUPDRV_TSC_DELTA_MEASUREMENT_BUSY;
4625
4626 rc = RTThreadSleep(RT_MIN((RTMSINTERVAL)(cMsWaitThread - cMsElapsed), RT_MIN(iWaitLoop + 1, 10)));
4627 if (rc == VERR_INTERRUPTED)
4628 return rc;
4629 }
4630#endif /* SUPDRV_USE_TSC_DELTA_THREAD */
4631
4632 /*
4633 * Try measure the TSC delta the given number of times.
4634 */
4635 for (;;)
4636 {
4637 /* Unless we're forced to measure the delta, check whether it's done already. */
4638 if ( !(fFlags & SUP_TSCDELTA_MEASURE_F_FORCE)
4639 && pGip->aCPUs[iGipCpu].i64TSCDelta != INT64_MAX)
4640 {
4641 rc = VINF_SUCCESS;
4642 break;
4643 }
4644
4645 /* Measure it. */
4646 rc = supdrvTscMeasureDeltaOne(pDevExt, iGipCpu);
4647 if (rc != VERR_SUPDRV_TSC_DELTA_MEASUREMENT_FAILED)
4648 {
4649 Assert(pGip->aCPUs[iGipCpu].i64TSCDelta != INT64_MAX || RT_FAILURE_NP(rc));
4650 break;
4651 }
4652
4653 /* Retry? */
4654 if (cTries <= 1)
4655 break;
4656 cTries--;
4657
4658 /* Always delay between retries (be nice to the rest of the system
4659 and avoid the BSOD hounds). */
4660 rc = RTThreadSleep(cMsWaitRetry);
4661 if (rc == VERR_INTERRUPTED)
4662 break;
4663 }
4664
4665 return rc;
4666}
4667
4668
4669/**
4670 * Service a TSC-delta measurement request.
4671 *
4672 * @returns VBox status code.
4673 * @param pDevExt Pointer to the device instance data.
4674 * @param pSession The support driver session.
4675 * @param pReq Pointer to the TSC-delta measurement request.
4676 */
4677int VBOXCALL supdrvIOCtl_TscDeltaMeasure(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPTSCDELTAMEASURE pReq)
4678{
4679 uint32_t cTries;
4680 uint32_t iCpuSet;
4681 uint32_t fFlags;
4682 RTMSINTERVAL cMsWaitRetry;
4683 RT_NOREF1(pDevExt);
4684
4685 /*
4686 * Validate and adjust/resolve the input so they can be passed onto SUPR0TscDeltaMeasureBySetIndex.
4687 */
4688 AssertPtr(pDevExt); AssertPtr(pSession); AssertPtr(pReq); /* paranoia^2 */
4689
4690 if (pReq->u.In.idCpu == NIL_RTCPUID)
4691 return VERR_INVALID_CPU_ID;
4692 iCpuSet = RTMpCpuIdToSetIndex(pReq->u.In.idCpu);
4693 if (iCpuSet >= RTCPUSET_MAX_CPUS)
4694 return VERR_INVALID_CPU_ID;
4695
4696 cTries = pReq->u.In.cRetries == 0 ? 0 : (uint32_t)pReq->u.In.cRetries + 1;
4697
4698 cMsWaitRetry = RT_MAX(pReq->u.In.cMsWaitRetry, 5);
4699
4700 fFlags = 0;
4701 if (pReq->u.In.fAsync)
4702 fFlags |= SUP_TSCDELTA_MEASURE_F_ASYNC;
4703 if (pReq->u.In.fForce)
4704 fFlags |= SUP_TSCDELTA_MEASURE_F_FORCE;
4705
4706 return SUPR0TscDeltaMeasureBySetIndex(pSession, iCpuSet, fFlags, cMsWaitRetry,
4707 cTries == 0 ? 5 * RT_MS_1SEC : cMsWaitRetry * cTries /*cMsWaitThread*/,
4708 cTries);
4709}
4710
4711
4712/**
4713 * Reads TSC with delta applied.
4714 *
4715 * Will try to resolve delta value INT64_MAX before applying it. This is the
4716 * main purpose of this function, to handle the case where the delta needs to be
4717 * determined.
4718 *
4719 * @returns VBox status code.
4720 * @param pDevExt Pointer to the device instance data.
4721 * @param pSession The support driver session.
4722 * @param pReq Pointer to the TSC-read request.
4723 */
4724int VBOXCALL supdrvIOCtl_TscRead(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPTSCREAD pReq)
4725{
4726 PSUPGLOBALINFOPAGE pGip;
4727 int rc;
4728
4729 /*
4730 * Validate. We require the client to have mapped GIP (no asserting on
4731 * ring-3 preconditions).
4732 */
4733 AssertPtr(pDevExt); AssertPtr(pReq); AssertPtr(pSession); /* paranoia^2 */
4734 if (pSession->GipMapObjR3 == NIL_RTR0MEMOBJ)
4735 return VERR_WRONG_ORDER;
4736 pGip = pDevExt->pGip;
4737 AssertReturn(pGip, VERR_INTERNAL_ERROR_2);
4738
4739 /*
4740 * We're usually here because we need to apply delta, but we shouldn't be
4741 * upset if the GIP is some different mode.
4742 */
4743 if (pGip->enmUseTscDelta > SUPGIPUSETSCDELTA_ZERO_CLAIMED)
4744 {
4745 uint32_t cTries = 0;
4746 for (;;)
4747 {
4748 /*
4749 * Start by gathering the data, using CLI for disabling preemption
4750 * while we do that.
4751 */
4752 RTCCUINTREG fEFlags = ASMIntDisableFlags();
4753 int iCpuSet = RTMpCpuIdToSetIndex(RTMpCpuId());
4754 int iGipCpu;
4755 if (RT_LIKELY( (unsigned)iCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)
4756 && (iGipCpu = pGip->aiCpuFromCpuSetIdx[iCpuSet]) < pGip->cCpus ))
4757 {
4758 int64_t i64Delta = pGip->aCPUs[iGipCpu].i64TSCDelta;
4759 pReq->u.Out.idApic = pGip->aCPUs[iGipCpu].idApic;
4760 pReq->u.Out.u64AdjustedTsc = ASMReadTSC();
4761 ASMSetFlags(fEFlags);
4762
4763 /*
4764 * If we're lucky we've got a delta, but no predictions here
4765 * as this I/O control is normally only used when the TSC delta
4766 * is set to INT64_MAX.
4767 */
4768 if (i64Delta != INT64_MAX)
4769 {
4770 pReq->u.Out.u64AdjustedTsc -= i64Delta;
4771 rc = VINF_SUCCESS;
4772 break;
4773 }
4774
4775 /* Give up after a few times. */
4776 if (cTries >= 4)
4777 {
4778 rc = VWRN_SUPDRV_TSC_DELTA_MEASUREMENT_FAILED;
4779 break;
4780 }
4781
4782 /* Need to measure the delta an try again. */
4783 rc = supdrvTscMeasureDeltaOne(pDevExt, iGipCpu);
4784 Assert(pGip->aCPUs[iGipCpu].i64TSCDelta != INT64_MAX || RT_FAILURE_NP(rc));
4785 /** @todo should probably delay on failure... dpc watchdogs */
4786 }
4787 else
4788 {
4789 /* This really shouldn't happen. */
4790 AssertMsgFailed(("idCpu=%#x iCpuSet=%#x (%d)\n", RTMpCpuId(), iCpuSet, iCpuSet));
4791 pReq->u.Out.idApic = ASMGetApicId();
4792 pReq->u.Out.u64AdjustedTsc = ASMReadTSC();
4793 ASMSetFlags(fEFlags);
4794 rc = VERR_INTERNAL_ERROR_5; /** @todo change to warning. */
4795 break;
4796 }
4797 }
4798 }
4799 else
4800 {
4801 /*
4802 * No delta to apply. Easy. Deal with preemption the lazy way.
4803 */
4804 RTCCUINTREG fEFlags = ASMIntDisableFlags();
4805 int iCpuSet = RTMpCpuIdToSetIndex(RTMpCpuId());
4806 int iGipCpu;
4807 if (RT_LIKELY( (unsigned)iCpuSet < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx)
4808 && (iGipCpu = pGip->aiCpuFromCpuSetIdx[iCpuSet]) < pGip->cCpus ))
4809 pReq->u.Out.idApic = pGip->aCPUs[iGipCpu].idApic;
4810 else
4811 pReq->u.Out.idApic = ASMGetApicId();
4812 pReq->u.Out.u64AdjustedTsc = ASMReadTSC();
4813 ASMSetFlags(fEFlags);
4814 rc = VINF_SUCCESS;
4815 }
4816
4817 return rc;
4818}
4819
4820
4821/**
4822 * Worker for supdrvIOCtl_GipSetFlags.
4823 *
4824 * @returns VBox status code.
4825 * @retval VERR_WRONG_ORDER if an enable-once-per-session flag is set again for
4826 * a session.
4827 *
4828 * @param pDevExt Pointer to the device instance data.
4829 * @param pSession The support driver session.
4830 * @param fOrMask The OR mask of the GIP flags, see SUPGIP_FLAGS_XXX.
4831 * @param fAndMask The AND mask of the GIP flags, see SUPGIP_FLAGS_XXX.
4832 *
4833 * @remarks Caller must own the GIP mutex.
4834 *
4835 * @remarks This function doesn't validate any of the flags.
4836 */
4837static int supdrvGipSetFlags(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, uint32_t fOrMask, uint32_t fAndMask)
4838{
4839 uint32_t cRefs;
4840 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
4841 AssertMsg((fOrMask & fAndMask) == fOrMask, ("%#x & %#x\n", fOrMask, fAndMask)); /* ASSUMED by code below */
4842
4843 /*
4844 * Compute GIP test-mode flags.
4845 */
4846 if (fOrMask & SUPGIP_FLAGS_TESTING_ENABLE)
4847 {
4848 if (!pSession->fGipTestMode)
4849 {
4850 Assert(pDevExt->cGipTestModeRefs < _64K);
4851 pSession->fGipTestMode = true;
4852 cRefs = ++pDevExt->cGipTestModeRefs;
4853 if (cRefs == 1)
4854 {
4855 fOrMask |= SUPGIP_FLAGS_TESTING | SUPGIP_FLAGS_TESTING_START;
4856 fAndMask &= ~SUPGIP_FLAGS_TESTING_STOP;
4857 }
4858 }
4859 else
4860 {
4861 LogRelMax(10, ("supdrvGipSetFlags: SUPGIP_FLAGS_TESTING_ENABLE already set for this session\n"));
4862 return VERR_WRONG_ORDER;
4863 }
4864 }
4865 else if ( !(fAndMask & SUPGIP_FLAGS_TESTING_ENABLE)
4866 && pSession->fGipTestMode)
4867 {
4868 Assert(pDevExt->cGipTestModeRefs > 0);
4869 Assert(pDevExt->cGipTestModeRefs < _64K);
4870 pSession->fGipTestMode = false;
4871 cRefs = --pDevExt->cGipTestModeRefs;
4872 if (!cRefs)
4873 fOrMask |= SUPGIP_FLAGS_TESTING_STOP;
4874 else
4875 fAndMask |= SUPGIP_FLAGS_TESTING_ENABLE;
4876 }
4877
4878 /*
4879 * Commit the flags. This should be done as atomically as possible
4880 * since the flag consumers won't be holding the GIP mutex.
4881 */
4882 ASMAtomicOrU32(&pGip->fFlags, fOrMask);
4883 ASMAtomicAndU32(&pGip->fFlags, fAndMask);
4884
4885 return VINF_SUCCESS;
4886}
4887
4888
4889/**
4890 * Sets GIP test mode parameters.
4891 *
4892 * @returns VBox status code.
4893 * @param pDevExt Pointer to the device instance data.
4894 * @param pSession The support driver session.
4895 * @param fOrMask The OR mask of the GIP flags, see SUPGIP_FLAGS_XXX.
4896 * @param fAndMask The AND mask of the GIP flags, see SUPGIP_FLAGS_XXX.
4897 */
4898int VBOXCALL supdrvIOCtl_GipSetFlags(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, uint32_t fOrMask, uint32_t fAndMask)
4899{
4900 PSUPGLOBALINFOPAGE pGip;
4901 int rc;
4902
4903 /*
4904 * Validate. We require the client to have mapped GIP (no asserting on
4905 * ring-3 preconditions).
4906 */
4907 AssertPtr(pDevExt); AssertPtr(pSession); /* paranoia^2 */
4908 if (pSession->GipMapObjR3 == NIL_RTR0MEMOBJ)
4909 return VERR_WRONG_ORDER;
4910 pGip = pDevExt->pGip;
4911 AssertReturn(pGip, VERR_INTERNAL_ERROR_3);
4912
4913 if (fOrMask & ~SUPGIP_FLAGS_VALID_MASK)
4914 return VERR_INVALID_PARAMETER;
4915 if ((fAndMask & ~SUPGIP_FLAGS_VALID_MASK) != ~SUPGIP_FLAGS_VALID_MASK)
4916 return VERR_INVALID_PARAMETER;
4917
4918 /*
4919 * Don't confuse supdrvGipSetFlags or anyone else by both setting
4920 * and clearing the same flags. AND takes precedence.
4921 */
4922 fOrMask &= fAndMask;
4923
4924 /*
4925 * Take the loader lock to avoid having to think about races between two
4926 * clients changing the flags at the same time (state is not simple).
4927 */
4928#ifdef SUPDRV_USE_MUTEX_FOR_GIP
4929 RTSemMutexRequest(pDevExt->mtxGip, RT_INDEFINITE_WAIT);
4930#else
4931 RTSemFastMutexRequest(pDevExt->mtxGip);
4932#endif
4933
4934 rc = supdrvGipSetFlags(pDevExt, pSession, fOrMask, fAndMask);
4935
4936#ifdef SUPDRV_USE_MUTEX_FOR_GIP
4937 RTSemMutexRelease(pDevExt->mtxGip);
4938#else
4939 RTSemFastMutexRelease(pDevExt->mtxGip);
4940#endif
4941 return rc;
4942}
4943
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette