summaryrefslogtreecommitdiffstats
path: root/src/VBox/VMM/VMMAll/TMAllVirtual.cpp
blob: 9244bd850b6ea8870b40964b0fcac8723b039d1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
/* $Id: TMAllVirtual.cpp $ */
/** @file
 * TM - Timeout Manager, Virtual Time, All Contexts.
 */

/*
 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_TM
#include <VBox/vmm/tm.h>
#include <VBox/vmm/dbgftrace.h>
#ifdef IN_RING3
# include <iprt/thread.h>
#endif
#include "TMInternal.h"
#include <VBox/vmm/vmcc.h>
#include <VBox/vmm/vmm.h>
#include <VBox/err.h>
#include <VBox/log.h>
#include <VBox/sup.h>

#include <iprt/time.h>
#include <iprt/assert.h>
#include <iprt/asm.h>
#include <iprt/asm-math.h>



/**
 * @interface_method_impl{RTTIMENANOTSDATA,pfnBad}
 */
DECLCALLBACK(DECLEXPORT(void)) tmVirtualNanoTSBad(PRTTIMENANOTSDATA pData, uint64_t u64NanoTS, uint64_t u64DeltaPrev,
                                                  uint64_t u64PrevNanoTS)
{
    PVMCC pVM = RT_FROM_CPP_MEMBER(pData, VMCC, VMCC_CTX(tm).s.VirtualGetRawData);
    pData->cBadPrev++;
    if ((int64_t)u64DeltaPrev < 0)
        LogRel(("TM: u64DeltaPrev=%RI64 u64PrevNanoTS=0x%016RX64 u64NanoTS=0x%016RX64 pVM=%p\n",
                u64DeltaPrev, u64PrevNanoTS, u64NanoTS, pVM));
    else
        Log(("TM: u64DeltaPrev=%RI64 u64PrevNanoTS=0x%016RX64 u64NanoTS=0x%016RX64 pVM=%p (debugging?)\n",
             u64DeltaPrev, u64PrevNanoTS, u64NanoTS, pVM));
}


#ifdef IN_RING3
/**
 * @callback_method_impl{FNTIMENANOTSINTERNAL, For driverless mode.}
 */
static DECLCALLBACK(uint64_t) tmR3VirtualNanoTSDriverless(PRTTIMENANOTSDATA pData, PRTITMENANOTSEXTRA pExtra)
{
    RT_NOREF(pData);
    if (pExtra)
        pExtra->uTSCValue = ASMReadTSC();
    return RTTimeSystemNanoTS();
}
#endif


/**
 * @interface_method_impl{RTTIMENANOTSDATA,pfnRediscover}
 *
 * This is the initial worker, so the first call in each context ends up here.
 * It is also used should the delta rating of the host CPUs change or if the
 * fGetGipCpu feature the current worker relies upon becomes unavailable.  The
 * last two events may occur as CPUs are taken online.
 */
DECLCALLBACK(DECLEXPORT(uint64_t)) tmVirtualNanoTSRediscover(PRTTIMENANOTSDATA pData, PRTITMENANOTSEXTRA pExtra)
{
    PVMCC                 pVM = RT_FROM_CPP_MEMBER(pData, VMCC, VMCC_CTX(tm).s.VirtualGetRawData);
    PFNTIMENANOTSINTERNAL pfnWorker;

    /*
     * We require a valid GIP for the selection below.
     * Invalid GIP is fatal, though we have to allow no GIP in driverless mode (ring-3 only).
     */
    PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
#ifdef IN_RING3
    if (pGip)
#endif
    {
        AssertFatalMsg(RT_VALID_PTR(pGip), ("pVM=%p pGip=%p\n", pVM, pGip));
        AssertFatalMsg(pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC, ("pVM=%p pGip=%p u32Magic=%#x\n", pVM, pGip, pGip->u32Magic));
        AssertFatalMsg(pGip->u32Mode > SUPGIPMODE_INVALID && pGip->u32Mode < SUPGIPMODE_END,
                       ("pVM=%p pGip=%p u32Mode=%#x\n", pVM, pGip, pGip->u32Mode));

        /*
         * Determine the new worker.
         */
#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
        bool const fLFence = RT_BOOL(ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2);
#endif
        switch (pGip->u32Mode)
        {
#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
            case SUPGIPMODE_SYNC_TSC:
            case SUPGIPMODE_INVARIANT_TSC:
# ifdef IN_RING0
                if (pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_ROUGHLY_ZERO)
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceSyncInvarNoDelta    : RTTimeNanoTSLegacySyncInvarNoDelta;
                else
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceSyncInvarWithDelta  : RTTimeNanoTSLegacySyncInvarWithDelta;
# else
                if (pGip->fGetGipCpu & SUPGIPGETCPU_IDTR_LIMIT_MASK_MAX_SET_CPUS)
                    pfnWorker = pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_PRACTICALLY_ZERO
                              ? fLFence ? RTTimeNanoTSLFenceSyncInvarNoDelta             : RTTimeNanoTSLegacySyncInvarNoDelta
                              : fLFence ? RTTimeNanoTSLFenceSyncInvarWithDeltaUseIdtrLim : RTTimeNanoTSLegacySyncInvarWithDeltaUseIdtrLim;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_RDTSCP_MASK_MAX_SET_CPUS)
                    pfnWorker = pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_PRACTICALLY_ZERO
                              ? fLFence ? RTTimeNanoTSLFenceSyncInvarNoDelta            : RTTimeNanoTSLegacySyncInvarNoDelta
                              : fLFence ? RTTimeNanoTSLFenceSyncInvarWithDeltaUseRdtscp : RTTimeNanoTSLegacySyncInvarWithDeltaUseRdtscp;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_APIC_ID_EXT_0B)
                    pfnWorker = pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_ROUGHLY_ZERO
                              ? fLFence ? RTTimeNanoTSLFenceSyncInvarNoDelta                 : RTTimeNanoTSLegacySyncInvarNoDelta
                              : fLFence ? RTTimeNanoTSLFenceSyncInvarWithDeltaUseApicIdExt0B : RTTimeNanoTSLegacySyncInvarWithDeltaUseApicIdExt0B;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_APIC_ID_EXT_8000001E)
                    pfnWorker = pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_ROUGHLY_ZERO
                              ? fLFence ? RTTimeNanoTSLFenceSyncInvarNoDelta                       : RTTimeNanoTSLegacySyncInvarNoDelta
                              : fLFence ? RTTimeNanoTSLFenceSyncInvarWithDeltaUseApicIdExt8000001E : RTTimeNanoTSLegacySyncInvarWithDeltaUseApicIdExt8000001E;
                else
                    pfnWorker = pGip->enmUseTscDelta <= SUPGIPUSETSCDELTA_ROUGHLY_ZERO
                              ? fLFence ? RTTimeNanoTSLFenceSyncInvarNoDelta            : RTTimeNanoTSLegacySyncInvarNoDelta
                              : fLFence ? RTTimeNanoTSLFenceSyncInvarWithDeltaUseApicId : RTTimeNanoTSLegacySyncInvarWithDeltaUseApicId;
# endif
                break;

            case SUPGIPMODE_ASYNC_TSC:
# ifdef IN_RING0
                pfnWorker = fLFence ? RTTimeNanoTSLFenceAsync : RTTimeNanoTSLegacyAsync;
# else
                if (pGip->fGetGipCpu & SUPGIPGETCPU_IDTR_LIMIT_MASK_MAX_SET_CPUS)
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceAsyncUseIdtrLim     : RTTimeNanoTSLegacyAsyncUseIdtrLim;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_RDTSCP_MASK_MAX_SET_CPUS)
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceAsyncUseRdtscp      : RTTimeNanoTSLegacyAsyncUseRdtscp;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_RDTSCP_GROUP_IN_CH_NUMBER_IN_CL)
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceAsyncUseRdtscpGroupChNumCl : RTTimeNanoTSLegacyAsyncUseRdtscpGroupChNumCl;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_APIC_ID_EXT_0B)
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceAsyncUseApicIdExt0B : RTTimeNanoTSLegacyAsyncUseApicIdExt0B;
                else if (pGip->fGetGipCpu & SUPGIPGETCPU_APIC_ID_EXT_8000001E)
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceAsyncUseApicIdExt8000001E  : RTTimeNanoTSLegacyAsyncUseApicIdExt8000001E;
                else
                    pfnWorker = fLFence ? RTTimeNanoTSLFenceAsyncUseApicId      : RTTimeNanoTSLegacyAsyncUseApicId;
# endif
                break;
#endif
            default:
                AssertFatalMsgFailed(("pVM=%p pGip=%p u32Mode=%#x\n", pVM, pGip, pGip->u32Mode));
        }
    }
#ifdef IN_RING3
    else
        pfnWorker = tmR3VirtualNanoTSDriverless;
#endif

    /*
     * Update the pfnVirtualGetRaw pointer and call the worker we selected.
     */
    ASMAtomicWritePtr((void * volatile *)&pVM->VMCC_CTX(tm).s.pfnVirtualGetRaw, (void *)(uintptr_t)pfnWorker);
    return pfnWorker(pData, pExtra);
}


/**
 * @interface_method_impl{RTTIMENANOTSDATA,pfnBadCpuIndex}
 */
DECLCALLBACK(DECLEXPORT(uint64_t)) tmVirtualNanoTSBadCpuIndex(PRTTIMENANOTSDATA pData, PRTITMENANOTSEXTRA pExtra,
                                                              uint16_t idApic, uint16_t iCpuSet, uint16_t iGipCpu)
{
    PVMCC pVM = RT_FROM_CPP_MEMBER(pData, VMCC, VMCC_CTX(tm).s.VirtualGetRawData);
    AssertFatalMsgFailed(("pVM=%p idApic=%#x iCpuSet=%#x iGipCpu=%#x pExtra=%p\n", pVM, idApic, iCpuSet, iGipCpu, pExtra));
#ifndef _MSC_VER
    return UINT64_MAX;
#endif
}


/**
 * Wrapper around the IPRT GIP time methods.
 */
DECLINLINE(uint64_t) tmVirtualGetRawNanoTS(PVMCC pVM)
{
#ifdef IN_RING3
    uint64_t u64 = pVM->tm.s.pfnVirtualGetRaw(&pVM->tm.s.VirtualGetRawData, NULL /*pExtra*/);
#elif defined(IN_RING0)
    uint32_t cPrevSteps = pVM->tmr0.s.VirtualGetRawData.c1nsSteps;
    uint64_t u64 = pVM->tmr0.s.pfnVirtualGetRaw(&pVM->tmr0.s.VirtualGetRawData, NULL /*pExtra*/);
    if (cPrevSteps != pVM->tmr0.s.VirtualGetRawData.c1nsSteps)
        VMCPU_FF_SET(VMMGetCpu(pVM), VMCPU_FF_TO_R3);
#else
# error "unsupported context"
#endif
    /*DBGFTRACE_POS_U64(pVM, u64);*/
    return u64;
}


/**
 * Wrapper around the IPRT GIP time methods, extended version.
 */
DECLINLINE(uint64_t) tmVirtualGetRawNanoTSEx(PVMCC pVM, uint64_t *puTscNow)
{
    RTITMENANOTSEXTRA Extra;
#ifdef IN_RING3
    uint64_t u64 = pVM->tm.s.pfnVirtualGetRaw(&pVM->tm.s.VirtualGetRawData, &Extra);
#elif defined(IN_RING0)
    uint32_t cPrevSteps = pVM->tmr0.s.VirtualGetRawData.c1nsSteps;
    uint64_t u64 = pVM->tmr0.s.pfnVirtualGetRaw(&pVM->tmr0.s.VirtualGetRawData, &Extra);
    if (cPrevSteps != pVM->tmr0.s.VirtualGetRawData.c1nsSteps)
        VMCPU_FF_SET(VMMGetCpu(pVM), VMCPU_FF_TO_R3);
#else
# error "unsupported context"
#endif
    if (puTscNow)
        *puTscNow = Extra.uTSCValue;
    /*DBGFTRACE_POS_U64(pVM, u64);*/
    return u64;
}


/**
 * Get the time when we're not running at 100%
 *
 * @returns The timestamp.
 * @param   pVM         The cross context VM structure.
 * @param   puTscNow    Where to return the TSC corresponding to the returned
 *                      timestamp (delta adjusted). Optional.
 */
static uint64_t tmVirtualGetRawNonNormal(PVMCC pVM, uint64_t *puTscNow)
{
    /*
     * Recalculate the RTTimeNanoTS() value for the period where
     * warp drive has been enabled.
     */
    uint64_t u64 = tmVirtualGetRawNanoTSEx(pVM, puTscNow);
    u64 -= pVM->tm.s.u64VirtualWarpDriveStart;
    u64 *= pVM->tm.s.u32VirtualWarpDrivePercentage;
    u64 /= 100;
    u64 += pVM->tm.s.u64VirtualWarpDriveStart;

    /*
     * Now we apply the virtual time offset.
     * (Which is the negated tmVirtualGetRawNanoTS() value for when the virtual
     * machine started if it had been running continuously without any suspends.)
     */
    u64 -= pVM->tm.s.u64VirtualOffset;
    return u64;
}


/**
 * Get the raw virtual time.
 *
 * @returns The current time stamp.
 * @param   pVM         The cross context VM structure.
 */
DECLINLINE(uint64_t) tmVirtualGetRaw(PVMCC pVM)
{
    if (RT_LIKELY(!pVM->tm.s.fVirtualWarpDrive))
        return tmVirtualGetRawNanoTS(pVM) - pVM->tm.s.u64VirtualOffset;
    return tmVirtualGetRawNonNormal(pVM, NULL /*puTscNow*/);
}


/**
 * Get the raw virtual time, extended version.
 *
 * @returns The current time stamp.
 * @param   pVM         The cross context VM structure.
 * @param   puTscNow    Where to return the TSC corresponding to the returned
 *                      timestamp (delta adjusted). Optional.
 */
DECLINLINE(uint64_t) tmVirtualGetRawEx(PVMCC pVM, uint64_t *puTscNow)
{
    if (RT_LIKELY(!pVM->tm.s.fVirtualWarpDrive))
        return tmVirtualGetRawNanoTSEx(pVM, puTscNow) - pVM->tm.s.u64VirtualOffset;
    return tmVirtualGetRawNonNormal(pVM, puTscNow);
}


/**
 * Inlined version of tmVirtualGetEx.
 */
DECLINLINE(uint64_t) tmVirtualGet(PVMCC pVM, bool fCheckTimers)
{
    uint64_t u64;
    if (RT_LIKELY(pVM->tm.s.cVirtualTicking))
    {
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualGet);
        u64 = tmVirtualGetRaw(pVM);

        /*
         * Use the chance to check for expired timers.
         */
        if (fCheckTimers)
        {
            PVMCPUCC pVCpuDst = VMCC_GET_CPU(pVM, pVM->tm.s.idTimerCpu);
            if (    !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
                &&  !pVM->tm.s.fRunningQueues
                &&  (   pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL].u64Expire <= u64
                     || (   pVM->tm.s.fVirtualSyncTicking
                         && pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64 - pVM->tm.s.offVirtualSync
                        )
                    )
                &&  !pVM->tm.s.fRunningQueues
               )
            {
                STAM_COUNTER_INC(&pVM->tm.s.StatVirtualGetSetFF);
                Log5(("TMAllVirtual(%u): FF: %d -> 1\n", __LINE__, VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)));
                VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
#ifdef IN_RING3
                VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM);
#endif
            }
        }
    }
    else
        u64 = pVM->tm.s.u64Virtual;
    return u64;
}


/**
 * Gets the current TMCLOCK_VIRTUAL time
 *
 * @returns The timestamp.
 * @param   pVM     The cross context VM structure.
 *
 * @remark  While the flow of time will never go backwards, the speed of the
 *          progress varies due to inaccurate RTTimeNanoTS and TSC. The latter can be
 *          influenced by power saving (SpeedStep, PowerNow!), while the former
 *          makes use of TSC and kernel timers.
 */
VMM_INT_DECL(uint64_t) TMVirtualGet(PVMCC pVM)
{
    return tmVirtualGet(pVM, true /*fCheckTimers*/);
}


/**
 * Gets the current TMCLOCK_VIRTUAL time without checking
 * timers or anything.
 *
 * Meaning, this has no side effect on FFs like TMVirtualGet may have.
 *
 * @returns The timestamp.
 * @param   pVM     The cross context VM structure.
 *
 * @remarks See TMVirtualGet.
 */
VMM_INT_DECL(uint64_t) TMVirtualGetNoCheck(PVMCC pVM)
{
    return tmVirtualGet(pVM, false /*fCheckTimers*/);
}


/**
 * Converts the dead line interval from TMCLOCK_VIRTUAL to host nano seconds.
 *
 * @returns Host nano second count.
 * @param   pVM                     The cross context VM structure.
 * @param   cVirtTicksToDeadline    The TMCLOCK_VIRTUAL interval.
 */
DECLINLINE(uint64_t) tmVirtualVirtToNsDeadline(PVM pVM, uint64_t cVirtTicksToDeadline)
{
    if (RT_UNLIKELY(pVM->tm.s.fVirtualWarpDrive))
        return ASMMultU64ByU32DivByU32(cVirtTicksToDeadline, 100, pVM->tm.s.u32VirtualWarpDrivePercentage);
    return cVirtTicksToDeadline;
}


/**
 * tmVirtualSyncGetLocked worker for handling catch-up when owning the lock.
 *
 * @returns The timestamp.
 * @param   pVM                 The cross context VM structure.
 * @param   u64                 raw virtual time.
 * @param   off                 offVirtualSync.
 * @param   pcNsToDeadline      Where to return the number of nano seconds to
 *                              the next virtual sync timer deadline. Can be
 *                              NULL.
 * @param   pnsAbsDeadline      Where to return the absolute deadline.
 *                              Optional.
 */
DECLINLINE(uint64_t) tmVirtualSyncGetHandleCatchUpLocked(PVMCC pVM, uint64_t u64, uint64_t off,
                                                         uint64_t *pcNsToDeadline, uint64_t *pnsAbsDeadline)
{
    STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetLocked);

    /*
     * Don't make updates until we've check the timer queue.
     */
    bool            fUpdatePrev = true;
    bool            fUpdateOff  = true;
    bool            fStop       = false;
    const uint64_t  u64Prev     = pVM->tm.s.u64VirtualSyncCatchUpPrev;
    uint64_t        u64Delta    = u64 - u64Prev;
    if (RT_LIKELY(!(u64Delta >> 32)))
    {
        uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
        if (off > u64Sub + pVM->tm.s.offVirtualSyncGivenUp)
        {
            off -= u64Sub;
            Log4(("TM: %'RU64/-%'8RU64: sub %RU32 [vsghcul]\n", u64 - off, off - pVM->tm.s.offVirtualSyncGivenUp, u64Sub));
        }
        else
        {
            /* we've completely caught up. */
            STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
            off = pVM->tm.s.offVirtualSyncGivenUp;
            fStop = true;
            Log4(("TM: %'RU64/0: caught up [vsghcul]\n", u64));
        }
    }
    else
    {
        /* More than 4 seconds since last time (or negative), ignore it. */
        fUpdateOff = false;
        fUpdatePrev = !(u64Delta & RT_BIT_64(63));
        Log(("TMVirtualGetSync: u64Delta=%RX64\n", u64Delta));
    }

    /*
     * Complete the calculation of the current TMCLOCK_VIRTUAL_SYNC time. The current
     * approach is to never pass the head timer. So, when we do stop the clock and
     * set the timer pending flag.
     */
    u64 -= off;

    uint64_t u64Last = ASMAtomicUoReadU64(&pVM->tm.s.u64VirtualSync);
    if (u64Last > u64)
    {
        u64 = u64Last + 1;
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetAdjLast);
    }

    uint64_t u64Expire = ASMAtomicReadU64(&pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL_SYNC].u64Expire);
    if (pnsAbsDeadline)
        *pnsAbsDeadline = u64Expire; /* Always return the unadjusted absolute deadline, or HM will waste time going
                                        thru this code over an over again even if there aren't any timer changes. */
    if (u64 < u64Expire)
    {
        ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64);
        if (fUpdateOff)
            ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, off);
        if (fStop)
            ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
        if (fUpdatePrev)
            ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev, u64);
        if (pcNsToDeadline)
        {
            uint64_t cNsToDeadline = u64Expire - u64;
            if (pVM->tm.s.fVirtualSyncCatchUp)
                cNsToDeadline = ASMMultU64ByU32DivByU32(cNsToDeadline, 100,
                                                        pVM->tm.s.u32VirtualSyncCatchUpPercentage + 100);
            *pcNsToDeadline = tmVirtualVirtToNsDeadline(pVM, cNsToDeadline);
        }
        PDMCritSectLeave(pVM, &pVM->tm.s.VirtualSyncLock);
    }
    else
    {
        u64 = u64Expire;
        ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64);
        ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);

        VM_FF_SET(pVM, VM_FF_TM_VIRTUAL_SYNC);
        PVMCPUCC pVCpuDst = VMCC_GET_CPU(pVM, pVM->tm.s.idTimerCpu);
        VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
        Log5(("TMAllVirtual(%u): FF: %d -> 1\n", __LINE__, VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)));
        Log4(("TM: %'RU64/-%'8RU64: exp tmr=>ff [vsghcul]\n", u64, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp));
        PDMCritSectLeave(pVM, &pVM->tm.s.VirtualSyncLock);

        if (pcNsToDeadline)
            *pcNsToDeadline = 0;
#ifdef IN_RING3
        VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM);
#endif
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetSetFF);
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetExpired);
    }
    STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetLocked);

    Log6(("tmVirtualSyncGetHandleCatchUpLocked -> %'RU64\n", u64));
    DBGFTRACE_U64_TAG(pVM, u64, "tmVirtualSyncGetHandleCatchUpLocked");
    return u64;
}


/**
 * tmVirtualSyncGetEx worker for when we get the lock.
 *
 * @returns timesamp.
 * @param   pVM                 The cross context VM structure.
 * @param   u64                 The virtual clock timestamp.
 * @param   pcNsToDeadline      Where to return the number of nano seconds to
 *                              the next virtual sync timer deadline.  Can be
 *                              NULL.
 * @param   pnsAbsDeadline      Where to return the absolute deadline.
 *                              Optional.
 */
DECLINLINE(uint64_t) tmVirtualSyncGetLocked(PVMCC pVM, uint64_t u64, uint64_t *pcNsToDeadline, uint64_t *pnsAbsDeadline)
{
    /*
     * Not ticking?
     */
    if (!pVM->tm.s.fVirtualSyncTicking)
    {
        u64 = ASMAtomicUoReadU64(&pVM->tm.s.u64VirtualSync);
        PDMCritSectLeave(pVM, &pVM->tm.s.VirtualSyncLock);
        if (pcNsToDeadline)
            *pcNsToDeadline = 0;
        if (pnsAbsDeadline)
            *pnsAbsDeadline = u64;
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetLocked);
        Log6(("tmVirtualSyncGetLocked -> %'RU64 [stopped]\n", u64));
        DBGFTRACE_U64_TAG(pVM, u64, "tmVirtualSyncGetLocked-stopped");
        return u64;
    }

    /*
     * Handle catch up in a separate function.
     */
    uint64_t off = ASMAtomicUoReadU64(&pVM->tm.s.offVirtualSync);
    if (ASMAtomicUoReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
        return tmVirtualSyncGetHandleCatchUpLocked(pVM, u64, off, pcNsToDeadline, pnsAbsDeadline);

    /*
     * Complete the calculation of the current TMCLOCK_VIRTUAL_SYNC time. The current
     * approach is to never pass the head timer. So, when we do stop the clock and
     * set the timer pending flag.
     */
    u64 -= off;

    uint64_t u64Last = ASMAtomicUoReadU64(&pVM->tm.s.u64VirtualSync);
    if (u64Last > u64)
    {
        u64 = u64Last + 1;
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetAdjLast);
    }

    uint64_t u64Expire = ASMAtomicReadU64(&pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL_SYNC].u64Expire);
    if (pnsAbsDeadline)
        *pnsAbsDeadline = u64Expire;
    if (u64 < u64Expire)
    {
        ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64);
        PDMCritSectLeave(pVM, &pVM->tm.s.VirtualSyncLock);
        if (pcNsToDeadline)
            *pcNsToDeadline = tmVirtualVirtToNsDeadline(pVM, u64Expire - u64);
    }
    else
    {
        u64 = u64Expire;
        ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64);
        ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);

        VM_FF_SET(pVM, VM_FF_TM_VIRTUAL_SYNC);
        PVMCPUCC pVCpuDst = VMCC_GET_CPU(pVM, pVM->tm.s.idTimerCpu);
        VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
        Log5(("TMAllVirtual(%u): FF: %d -> 1\n", __LINE__, VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)));
        Log4(("TM: %'RU64/-%'8RU64: exp tmr=>ff [vsgl]\n", u64, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp));
        PDMCritSectLeave(pVM, &pVM->tm.s.VirtualSyncLock);

#ifdef IN_RING3
        VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM);
#endif
        if (pcNsToDeadline)
            *pcNsToDeadline = 0;
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetSetFF);
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetExpired);
    }
    STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetLocked);
    Log6(("tmVirtualSyncGetLocked -> %'RU64\n", u64));
    DBGFTRACE_U64_TAG(pVM, u64, "tmVirtualSyncGetLocked");
    return u64;
}


/**
 * Gets the current TMCLOCK_VIRTUAL_SYNC time.
 *
 * @returns The timestamp.
 * @param   pVM                 The cross context VM structure.
 * @param   fCheckTimers        Check timers or not
 * @param   pcNsToDeadline      Where to return the number of nano seconds to
 *                              the next virtual sync timer deadline.  Can be
 *                              NULL.
 * @param   pnsAbsDeadline      Where to return the absolute deadline.
 *                              Optional.
 * @param   puTscNow            Where to return the TSC corresponding to the
 *                              returned timestamp (delta adjusted). Optional.
 * @thread  EMT.
 */
DECLINLINE(uint64_t) tmVirtualSyncGetEx(PVMCC pVM, bool fCheckTimers, uint64_t *pcNsToDeadline,
                                        uint64_t *pnsAbsDeadline, uint64_t *puTscNow)
{
    STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGet);

    uint64_t u64;
    if (!pVM->tm.s.fVirtualSyncTicking)
    {
        if (pcNsToDeadline)
            *pcNsToDeadline = 0;
        u64 = pVM->tm.s.u64VirtualSync;
        DBGFTRACE_U64_TAG(pVM, u64, "tmVirtualSyncGetEx-stopped1");
        return u64;
    }

    /*
     * Query the virtual clock and do the usual expired timer check.
     */
    Assert(pVM->tm.s.cVirtualTicking);
    u64 = tmVirtualGetRawEx(pVM, puTscNow);
    if (fCheckTimers)
    {
        PVMCPUCC pVCpuDst = VMCC_GET_CPU(pVM, pVM->tm.s.idTimerCpu);
        if (    !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
            &&  pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL].u64Expire <= u64)
        {
            Log5(("TMAllVirtual(%u): FF: 0 -> 1\n", __LINE__));
            VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
#ifdef IN_RING3
            VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM /** @todo |VMNOTIFYFF_FLAGS_POKE*/);
#endif
            STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetSetFF);
        }
    }

    /*
     * If we can get the lock, get it.  The result is much more reliable.
     *
     * Note! This is where all clock source devices branch off because they
     *       will be owning the lock already.  The 'else' is taken by code
     *       which is less picky or hasn't been adjusted yet
     */
    /** @todo switch this around, have the tmVirtualSyncGetLocked code inlined
     *        here and the remainder of this function in a static worker. */
    if (PDMCritSectTryEnter(pVM, &pVM->tm.s.VirtualSyncLock) == VINF_SUCCESS)
        return tmVirtualSyncGetLocked(pVM, u64, pcNsToDeadline, pnsAbsDeadline);

    /*
     * When the clock is ticking, not doing catch ups and not running into an
     * expired time, we can get away without locking. Try this first.
     */
    uint64_t off;
    if (ASMAtomicUoReadBool(&pVM->tm.s.fVirtualSyncTicking))
    {
        if (!ASMAtomicUoReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
        {
            off = ASMAtomicReadU64(&pVM->tm.s.offVirtualSync);
            if (RT_LIKELY(   ASMAtomicUoReadBool(&pVM->tm.s.fVirtualSyncTicking)
                          && !ASMAtomicUoReadBool(&pVM->tm.s.fVirtualSyncCatchUp)
                          && off == ASMAtomicReadU64(&pVM->tm.s.offVirtualSync)))
            {
                off = u64 - off;
                uint64_t const u64Expire = ASMAtomicReadU64(&pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL_SYNC].u64Expire);
                if (off < u64Expire)
                {
                    if (pnsAbsDeadline)
                        *pnsAbsDeadline = u64Expire;
                    if (pcNsToDeadline)
                        *pcNsToDeadline = tmVirtualVirtToNsDeadline(pVM, u64Expire - off);
                    STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetLockless);
                    Log6(("tmVirtualSyncGetEx -> %'RU64 [lockless]\n", off));
                    DBGFTRACE_U64_TAG(pVM, off, "tmVirtualSyncGetEx-lockless");
                    return off;
                }
            }
        }
    }
    else
    {
        off = ASMAtomicReadU64(&pVM->tm.s.u64VirtualSync);
        if (RT_LIKELY(!ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncTicking)))
        {
            if (pcNsToDeadline)
                *pcNsToDeadline = 0;
            if (pnsAbsDeadline)
                *pnsAbsDeadline = off;
            STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetLockless);
            Log6(("tmVirtualSyncGetEx -> %'RU64 [lockless/stopped]\n", off));
            DBGFTRACE_U64_TAG(pVM, off, "tmVirtualSyncGetEx-stopped2");
            return off;
        }
    }

    /*
     * Read the offset and adjust if we're playing catch-up.
     *
     * The catch-up adjusting work by us decrementing the offset by a percentage of
     * the time elapsed since the previous TMVirtualGetSync call.
     *
     * It's possible to get a very long or even negative interval between two read
     * for the following reasons:
     *  - Someone might have suspended the process execution, frequently the case when
     *    debugging the process.
     *  - We might be on a different CPU which TSC isn't quite in sync with the
     *    other CPUs in the system.
     *  - Another thread is racing us and we might have been preempted while inside
     *    this function.
     *
     * Assuming nano second virtual time, we can simply ignore any intervals which has
     * any of the upper 32 bits set.
     */
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    int cOuterTries = 42;
    for (;; cOuterTries--)
    {
        /* Try grab the lock, things get simpler when owning the lock. */
        int rcLock = PDMCritSectTryEnter(pVM, &pVM->tm.s.VirtualSyncLock);
        if (RT_SUCCESS_NP(rcLock))
            return tmVirtualSyncGetLocked(pVM, u64, pcNsToDeadline, pnsAbsDeadline);

        /* Re-check the ticking flag. */
        if (!ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncTicking))
        {
            off = ASMAtomicReadU64(&pVM->tm.s.u64VirtualSync);
            if (   ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncTicking)
                && cOuterTries > 0)
                continue;
            if (pcNsToDeadline)
                *pcNsToDeadline = 0;
            if (pnsAbsDeadline)
                *pnsAbsDeadline = off;
            Log6(("tmVirtualSyncGetEx -> %'RU64 [stopped]\n", off));
            DBGFTRACE_U64_TAG(pVM, off, "tmVirtualSyncGetEx-stopped3");
            return off;
        }

        off = ASMAtomicReadU64(&pVM->tm.s.offVirtualSync);
        if (ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
        {
            /* No changes allowed, try get a consistent set of parameters. */
            uint64_t const u64Prev    = ASMAtomicReadU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev);
            uint64_t const offGivenUp = ASMAtomicReadU64(&pVM->tm.s.offVirtualSyncGivenUp);
            uint32_t const u32Pct     = ASMAtomicReadU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage);
            if (    (   u64Prev    == ASMAtomicReadU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev)
                     && offGivenUp == ASMAtomicReadU64(&pVM->tm.s.offVirtualSyncGivenUp)
                     && u32Pct     == ASMAtomicReadU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage)
                     && ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
                ||  cOuterTries <= 0)
            {
                uint64_t u64Delta = u64 - u64Prev;
                if (RT_LIKELY(!(u64Delta >> 32)))
                {
                    uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, u32Pct, 100);
                    if (off > u64Sub + offGivenUp)
                    {
                        off -= u64Sub;
                        Log4(("TM: %'RU64/-%'8RU64: sub %RU32 [NoLock]\n", u64 - off, pVM->tm.s.offVirtualSync - offGivenUp, u64Sub));
                    }
                    else
                    {
                        /* we've completely caught up. */
                        STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
                        off = offGivenUp;
                        Log4(("TM: %'RU64/0: caught up [NoLock]\n", u64));
                    }
                }
                else
                    /* More than 4 seconds since last time (or negative), ignore it. */
                    Log(("TMVirtualGetSync: u64Delta=%RX64 (NoLock)\n", u64Delta));

                /* Check that we're still running and in catch up. */
                if (    ASMAtomicUoReadBool(&pVM->tm.s.fVirtualSyncTicking)
                    &&  ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
                    break;
                if (cOuterTries <= 0)
                    break; /* enough */
            }
        }
        else if (   off == ASMAtomicReadU64(&pVM->tm.s.offVirtualSync)
                 && !ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
            break; /* Got an consistent offset */
        else if (cOuterTries <= 0)
            break; /* enough */
    }
    if (cOuterTries <= 0)
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetELoop);

    /*
     * Complete the calculation of the current TMCLOCK_VIRTUAL_SYNC time. The current
     * approach is to never pass the head timer. So, when we do stop the clock and
     * set the timer pending flag.
     */
    u64 -= off;
/** @todo u64VirtualSyncLast */
    uint64_t u64Expire = ASMAtomicReadU64(&pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL_SYNC].u64Expire);
    if (pnsAbsDeadline)
        *pnsAbsDeadline = u64Expire;
    if (u64 >= u64Expire)
    {
        PVMCPUCC pVCpuDst = VMCC_GET_CPU(pVM, pVM->tm.s.idTimerCpu);
        if (!VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER))
        {
            Log5(("TMAllVirtual(%u): FF: %d -> 1 (NoLock)\n", __LINE__, VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)));
            VM_FF_SET(pVM, VM_FF_TM_VIRTUAL_SYNC); /* Hmm? */
            VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
#ifdef IN_RING3
            VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM);
#endif
            STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetSetFF);
            Log4(("TM: %'RU64/-%'8RU64: exp tmr=>ff [NoLock]\n", u64, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp));
        }
        else
            Log4(("TM: %'RU64/-%'8RU64: exp tmr [NoLock]\n", u64, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp));
        if (pcNsToDeadline)
            *pcNsToDeadline = 0;
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetExpired);
    }
    else if (pcNsToDeadline)
    {
        uint64_t cNsToDeadline = u64Expire - u64;
        if (ASMAtomicReadBool(&pVM->tm.s.fVirtualSyncCatchUp))
            cNsToDeadline = ASMMultU64ByU32DivByU32(cNsToDeadline, 100,
                                                    ASMAtomicReadU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage) + 100);
        *pcNsToDeadline = tmVirtualVirtToNsDeadline(pVM, cNsToDeadline);
    }

    Log6(("tmVirtualSyncGetEx -> %'RU64\n", u64));
    DBGFTRACE_U64_TAG(pVM, u64, "tmVirtualSyncGetEx-nolock");
    return u64;
}


/**
 * Gets the current TMCLOCK_VIRTUAL_SYNC time.
 *
 * @returns The timestamp.
 * @param   pVM             The cross context VM structure.
 * @thread  EMT.
 * @remarks May set the timer and virtual sync FFs.
 */
VMM_INT_DECL(uint64_t) TMVirtualSyncGet(PVMCC pVM)
{
    return tmVirtualSyncGetEx(pVM, true /*fCheckTimers*/, NULL /*pcNsToDeadline*/, NULL /*pnsAbsDeadline*/, NULL /*puTscNow*/);
}


/**
 * Gets the current TMCLOCK_VIRTUAL_SYNC time without checking timers running on
 * TMCLOCK_VIRTUAL.
 *
 * @returns The timestamp.
 * @param   pVM             The cross context VM structure.
 * @thread  EMT.
 * @remarks May set the timer and virtual sync FFs.
 */
VMM_INT_DECL(uint64_t) TMVirtualSyncGetNoCheck(PVMCC pVM)
{
    return tmVirtualSyncGetEx(pVM, false /*fCheckTimers*/, NULL /*pcNsToDeadline*/, NULL /*pnsAbsDeadline*/, NULL /*puTscNow*/);
}


/**
 * Gets the current TMCLOCK_VIRTUAL_SYNC time without checking timers running on
 * TMCLOCK_VIRTUAL, also returning corresponding TSC value.
 *
 * @returns The timestamp.
 * @param   pVM             The cross context VM structure.
 * @param   puTscNow        Where to return the TSC value that the return
 *                          value is relative to.   This is delta adjusted.
 * @thread  EMT.
 * @remarks May set the timer and virtual sync FFs.
 */
VMM_INT_DECL(uint64_t) TMVirtualSyncGetNoCheckWithTsc(PVMCC pVM, uint64_t *puTscNow)
{
    return tmVirtualSyncGetEx(pVM, false /*fCheckTimers*/, NULL /*pcNsToDeadline*/, NULL /*pnsAbsDeadline*/, puTscNow);
}


/**
 * Gets the current TMCLOCK_VIRTUAL_SYNC time.
 *
 * @returns The timestamp.
 * @param   pVM     The cross context VM structure.
 * @param   fCheckTimers    Check timers on the virtual clock or not.
 * @thread  EMT.
 * @remarks May set the timer and virtual sync FFs.
 */
VMM_INT_DECL(uint64_t) TMVirtualSyncGetEx(PVMCC pVM, bool fCheckTimers)
{
    return tmVirtualSyncGetEx(pVM, fCheckTimers, NULL /*pcNsToDeadline*/, NULL /*pnsAbsDeadline*/, NULL /*puTscNow*/);
}


/**
 * Gets the current TMCLOCK_VIRTUAL_SYNC time and ticks to the next deadline
 * without checking timers running on TMCLOCK_VIRTUAL.
 *
 * @returns The timestamp.
 * @param   pVM                 The cross context VM structure.
 * @param   pcNsToDeadline      Where to return the number of nano seconds to
 *                              the next virtual sync timer deadline.
 * @param   puTscNow            Where to return the TSC value that the return
 *                              value is relative to.   This is delta adjusted.
 * @param   puDeadlineVersion   Where to return the deadline "version" number.
 *                              Use with TMVirtualSyncIsCurrentDeadlineVersion()
 *                              to check if the absolute deadline is still up to
 *                              date and the caller can skip calling this
 *                              function.
 * @thread  EMT.
 * @remarks May set the timer and virtual sync FFs.
 */
VMM_INT_DECL(uint64_t) TMVirtualSyncGetWithDeadlineNoCheck(PVMCC pVM, uint64_t *pcNsToDeadline,
                                                           uint64_t *puDeadlineVersion, uint64_t *puTscNow)
{
    uint64_t cNsToDeadlineTmp;       /* try convince the compiler to skip the if tests. */
    uint64_t u64Now = tmVirtualSyncGetEx(pVM, false /*fCheckTimers*/, &cNsToDeadlineTmp, puDeadlineVersion, puTscNow);
    *pcNsToDeadline = cNsToDeadlineTmp;
    return u64Now;
}


/**
 * Gets the number of nano seconds to the next virtual sync deadline.
 *
 * @returns The number of TMCLOCK_VIRTUAL ticks.
 * @param   pVM                 The cross context VM structure.
 * @param   puTscNow            Where to return the TSC value that the return
 *                              value is relative to.   This is delta adjusted.
 * @param   puDeadlineVersion   Where to return the deadline "version" number.
 *                              Use with TMVirtualSyncIsCurrentDeadlineVersion()
 *                              to check if the absolute deadline is still up to
 *                              date and the caller can skip calling this
 *                              function.
 * @thread  EMT.
 * @remarks May set the timer and virtual sync FFs.
 */
VMMDECL(uint64_t) TMVirtualSyncGetNsToDeadline(PVMCC pVM, uint64_t *puDeadlineVersion, uint64_t *puTscNow)
{
    uint64_t cNsToDeadline;
    tmVirtualSyncGetEx(pVM, false /*fCheckTimers*/, &cNsToDeadline, puDeadlineVersion, puTscNow);
    return cNsToDeadline;
}


/**
 * Checks if the given deadline is still current.
 *
 * @retval  true if the deadline is still current.
 * @retval  false if the deadline is outdated.
 * @param   pVM                 The cross context VM structure.
 * @param   uDeadlineVersion    The deadline version to check.
 */
VMM_INT_DECL(bool) TMVirtualSyncIsCurrentDeadlineVersion(PVMCC pVM, uint64_t uDeadlineVersion)
{
    /** @todo Try use ASMAtomicUoReadU64 instead. */
    uint64_t u64Expire = ASMAtomicReadU64(&pVM->tm.s.aTimerQueues[TMCLOCK_VIRTUAL_SYNC].u64Expire);
    return u64Expire == uDeadlineVersion;
}


/**
 * Gets the current lag of the synchronous virtual clock (relative to the virtual clock).
 *
 * @return  The current lag.
 * @param   pVM     The cross context VM structure.
 */
VMM_INT_DECL(uint64_t) TMVirtualSyncGetLag(PVMCC pVM)
{
    return pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp;
}


/**
 * Get the current catch-up percent.
 *
 * @return  The current catch0up percent. 0 means running at the same speed as the virtual clock.
 * @param   pVM     The cross context VM structure.
 */
VMM_INT_DECL(uint32_t) TMVirtualSyncGetCatchUpPct(PVMCC pVM)
{
    if (pVM->tm.s.fVirtualSyncCatchUp)
        return pVM->tm.s.u32VirtualSyncCatchUpPercentage;
    return 0;
}


/**
 * Gets the current TMCLOCK_VIRTUAL frequency.
 *
 * @returns The frequency.
 * @param   pVM     The cross context VM structure.
 */
VMM_INT_DECL(uint64_t) TMVirtualGetFreq(PVM pVM)
{
    NOREF(pVM);
    return TMCLOCK_FREQ_VIRTUAL;
}


/**
 * Worker for TMR3PauseClocks.
 *
 * @returns VINF_SUCCESS or VERR_TM_VIRTUAL_TICKING_IPE (asserted).
 * @param   pVM     The cross context VM structure.
 */
int tmVirtualPauseLocked(PVMCC pVM)
{
    uint32_t c = ASMAtomicDecU32(&pVM->tm.s.cVirtualTicking);
    AssertMsgReturn(c < pVM->cCpus, ("%u vs %u\n", c, pVM->cCpus), VERR_TM_VIRTUAL_TICKING_IPE);
    if (c == 0)
    {
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualPause);
        pVM->tm.s.u64Virtual = tmVirtualGetRaw(pVM);
        ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
    }
    return VINF_SUCCESS;
}


/**
 * Worker for TMR3ResumeClocks.
 *
 * @returns VINF_SUCCESS or VERR_TM_VIRTUAL_TICKING_IPE (asserted).
 * @param   pVM     The cross context VM structure.
 */
int tmVirtualResumeLocked(PVMCC pVM)
{
    uint32_t c = ASMAtomicIncU32(&pVM->tm.s.cVirtualTicking);
    AssertMsgReturn(c <= pVM->cCpus, ("%u vs %u\n", c, pVM->cCpus), VERR_TM_VIRTUAL_TICKING_IPE);
    if (c == 1)
    {
        STAM_COUNTER_INC(&pVM->tm.s.StatVirtualResume);
        pVM->tm.s.u64VirtualRawPrev         = 0;
        pVM->tm.s.u64VirtualWarpDriveStart  = tmVirtualGetRawNanoTS(pVM);
        pVM->tm.s.u64VirtualOffset          = pVM->tm.s.u64VirtualWarpDriveStart - pVM->tm.s.u64Virtual;
        ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, true);
    }
    return VINF_SUCCESS;
}


/**
 * Converts from virtual ticks to nanoseconds.
 *
 * @returns nanoseconds.
 * @param   pVM             The cross context VM structure.
 * @param   u64VirtualTicks The virtual ticks to convert.
 * @remark  There could be rounding errors here. We just do a simple integer divide
 *          without any adjustments.
 */
VMM_INT_DECL(uint64_t) TMVirtualToNano(PVM pVM, uint64_t u64VirtualTicks)
{
    NOREF(pVM);
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    return u64VirtualTicks;
}


/**
 * Converts from virtual ticks to microseconds.
 *
 * @returns microseconds.
 * @param   pVM             The cross context VM structure.
 * @param   u64VirtualTicks The virtual ticks to convert.
 * @remark  There could be rounding errors here. We just do a simple integer divide
 *          without any adjustments.
 */
VMM_INT_DECL(uint64_t) TMVirtualToMicro(PVM pVM, uint64_t u64VirtualTicks)
{
    NOREF(pVM);
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    return u64VirtualTicks / 1000;
}


/**
 * Converts from virtual ticks to milliseconds.
 *
 * @returns milliseconds.
 * @param   pVM             The cross context VM structure.
 * @param   u64VirtualTicks The virtual ticks to convert.
 * @remark  There could be rounding errors here. We just do a simple integer divide
 *          without any adjustments.
 */
VMM_INT_DECL(uint64_t) TMVirtualToMilli(PVM pVM, uint64_t u64VirtualTicks)
{
    NOREF(pVM);
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    return u64VirtualTicks / 1000000;
}


/**
 * Converts from nanoseconds to virtual ticks.
 *
 * @returns virtual ticks.
 * @param   pVM             The cross context VM structure.
 * @param   u64NanoTS       The nanosecond value ticks to convert.
 * @remark  There could be rounding and overflow errors here.
 */
VMM_INT_DECL(uint64_t) TMVirtualFromNano(PVM pVM, uint64_t u64NanoTS)
{
    NOREF(pVM);
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    return u64NanoTS;
}


/**
 * Converts from microseconds to virtual ticks.
 *
 * @returns virtual ticks.
 * @param   pVM             The cross context VM structure.
 * @param   u64MicroTS      The microsecond value ticks to convert.
 * @remark  There could be rounding and overflow errors here.
 */
VMM_INT_DECL(uint64_t) TMVirtualFromMicro(PVM pVM, uint64_t u64MicroTS)
{
    NOREF(pVM);
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    return u64MicroTS * 1000;
}


/**
 * Converts from milliseconds to virtual ticks.
 *
 * @returns virtual ticks.
 * @param   pVM             The cross context VM structure.
 * @param   u64MilliTS      The millisecond value ticks to convert.
 * @remark  There could be rounding and overflow errors here.
 */
VMM_INT_DECL(uint64_t) TMVirtualFromMilli(PVM pVM, uint64_t u64MilliTS)
{
    NOREF(pVM);
    AssertCompile(TMCLOCK_FREQ_VIRTUAL == 1000000000);
    return u64MilliTS * 1000000;
}