summaryrefslogtreecommitdiffstats
path: root/src/VBox/VMM/VMMR3/EMRaw.cpp
blob: 749ab20f7b09ce2709aa6ed969aef25530240de1 (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
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
/* $Id: EMRaw.cpp $ */
/** @file
 * EM - Execution Monitor / Manager - software virtualization
 */

/*
 * Copyright (C) 2006-2019 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_EM
#define VMCPU_INCL_CPUM_GST_CTX
#include <VBox/vmm/em.h>
#include <VBox/vmm/vmm.h>
#include <VBox/vmm/patm.h>
#include <VBox/vmm/csam.h>
#include <VBox/vmm/selm.h>
#include <VBox/vmm/trpm.h>
#include <VBox/vmm/iem.h>
#include <VBox/vmm/iom.h>
#include <VBox/vmm/dbgf.h>
#include <VBox/vmm/pgm.h>
#ifdef VBOX_WITH_REM
# include <VBox/vmm/rem.h>
#endif
#include <VBox/vmm/tm.h>
#include <VBox/vmm/mm.h>
#include <VBox/vmm/ssm.h>
#include <VBox/vmm/pdmapi.h>
#include <VBox/vmm/pdmcritsect.h>
#include <VBox/vmm/pdmqueue.h>
#include <VBox/vmm/patm.h>
#include "EMInternal.h"
#include <VBox/vmm/vm.h>
#include <VBox/vmm/gim.h>
#include <VBox/vmm/cpumdis.h>
#include <VBox/dis.h>
#include <VBox/disopcode.h>
#include <VBox/vmm/dbgf.h>
#include "VMMTracing.h"

#include <VBox/err.h>
#include <VBox/log.h>
#include <iprt/asm.h>
#include <iprt/string.h>
#include <iprt/stream.h>



/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static int      emR3RawHandleRC(PVM pVM, PVMCPU pVCpu, int rc);
static int      emR3RawForcedActions(PVM pVM, PVMCPU pVCpu);
DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, PVMCPU pVCpu, const char *pszPrefix, int rcGC = VINF_SUCCESS);
static int      emR3RawGuestTrap(PVM pVM, PVMCPU pVCpu);
static int      emR3RawPatchTrap(PVM pVM, PVMCPU pVCpu, int gcret);
static int      emR3RawPrivileged(PVM pVM, PVMCPU pVCpu);
static int      emR3RawExecuteIOInstruction(PVM pVM, PVMCPU pVCpu);
static int      emR3RawRingSwitch(PVM pVM, PVMCPU pVCpu);
static int      emR3RawUpdateForceFlag(PVM pVM, PVMCPU pVCpu, int rc);

#define EMHANDLERC_WITH_PATM
#define emR3ExecuteInstruction   emR3RawExecuteInstruction
#define emR3ExecuteIOInstruction emR3RawExecuteIOInstruction
#include "EMHandleRCTmpl.h"



#ifdef VBOX_WITH_STATISTICS
/**
 * Just a braindead function to keep track of cli addresses.
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 * @param   GCPtrInstr  The EIP of the cli instruction.
 */
static void emR3RecordCli(PVM pVM, PVMCPU pVCpu, RTGCPTR GCPtrInstr)
{
    PCLISTAT pRec;

    pRec = (PCLISTAT)RTAvlGCPtrGet(&pVCpu->em.s.pCliStatTree, GCPtrInstr);
    if (!pRec)
    {
        /* New cli instruction; insert into the tree. */
        pRec = (PCLISTAT)MMR3HeapAllocZ(pVM, MM_TAG_EM, sizeof(*pRec));
        Assert(pRec);
        if (!pRec)
            return;
        pRec->Core.Key = GCPtrInstr;

        char szCliStatName[32];
        RTStrPrintf(szCliStatName, sizeof(szCliStatName), "/EM/Cli/0x%RGv", GCPtrInstr);
        STAM_REG(pVM, &pRec->Counter, STAMTYPE_COUNTER, szCliStatName, STAMUNIT_OCCURENCES, "Number of times cli was executed.");

        bool fRc = RTAvlGCPtrInsert(&pVCpu->em.s.pCliStatTree, &pRec->Core);
        Assert(fRc); NOREF(fRc);
    }
    STAM_COUNTER_INC(&pRec->Counter);
    STAM_COUNTER_INC(&pVCpu->em.s.StatTotalClis);
}
#endif /* VBOX_WITH_STATISTICS */



/**
 * Resumes executing hypervisor after a debug event.
 *
 * This is kind of special since our current guest state is
 * potentially out of sync.
 *
 * @returns VBox status code.
 * @param   pVM     The cross context VM structure.
 * @param   pVCpu   The cross context virtual CPU structure.
 */
int emR3RawResumeHyper(PVM pVM, PVMCPU pVCpu)
{
    int         rc;
    Assert(pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER);
    Log(("emR3RawResumeHyper: cs:eip=%RTsel:%RGr efl=%RGr\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.eflags));

    /*
     * Resume execution.
     */
    CPUMRawEnter(pVCpu);
    CPUMSetHyperEFlags(pVCpu, CPUMGetHyperEFlags(pVCpu) | X86_EFL_RF);
    rc = VMMR3ResumeHyper(pVM, pVCpu);
    Log(("emR3RawResumeHyper: cs:eip=%RTsel:%RGr efl=%RGr - returned from GC with rc=%Rrc\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.eflags, rc));
    rc = CPUMRawLeave(pVCpu, rc);
    VMCPU_FF_CLEAR_MASK(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);

    /*
     * Deal with the return code.
     */
    rc = VBOXSTRICTRC_TODO(emR3HighPriorityPostForcedActions(pVM, pVCpu, rc));
    rc = emR3RawHandleRC(pVM, pVCpu, rc);
    rc = emR3RawUpdateForceFlag(pVM, pVCpu, rc);
    return rc;
}


/**
 * Steps rawmode.
 *
 * @returns VBox status code.
 * @param   pVM     The cross context VM structure.
 * @param   pVCpu   The cross context virtual CPU structure.
 */
int emR3RawStep(PVM pVM, PVMCPU pVCpu)
{
    Assert(   pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER
           || pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_RAW
           || pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_REM);
    int         rc;
    bool        fGuest = pVCpu->em.s.enmState != EMSTATE_DEBUG_HYPER;
#ifndef DEBUG_sander
    Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr\n", fGuest ? CPUMGetGuestCS(pVCpu) : CPUMGetHyperCS(pVCpu),
         fGuest ? CPUMGetGuestEIP(pVCpu) : CPUMGetHyperEIP(pVCpu), fGuest ? CPUMGetGuestEFlags(pVCpu) : CPUMGetHyperEFlags(pVCpu)));
#endif
    if (fGuest)
    {
        /*
         * Check vital forced actions, but ignore pending interrupts and timers.
         */
        if (    VM_FF_IS_ANY_SET(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
            ||  VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
        {
            rc = emR3RawForcedActions(pVM, pVCpu);
            VBOXVMM_EM_FF_RAW_RET(pVCpu, rc);
            if (rc != VINF_SUCCESS)
                return rc;
        }

        /*
         * Set flags for single stepping.
         */
        CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) | X86_EFL_TF | X86_EFL_RF);
    }
    else
        CPUMSetHyperEFlags(pVCpu, CPUMGetHyperEFlags(pVCpu) | X86_EFL_TF | X86_EFL_RF);

    /*
     * Single step.
     * We do not start time or anything, if anything we should just do a few nanoseconds.
     */
    CPUMRawEnter(pVCpu);
    do
    {
        if (pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER)
            rc = VMMR3ResumeHyper(pVM, pVCpu);
        else
            rc = VMMR3RawRunGC(pVM, pVCpu);
#ifndef DEBUG_sander
        Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr - GC rc %Rrc\n", fGuest ? CPUMGetGuestCS(pVCpu) : CPUMGetHyperCS(pVCpu),
             fGuest ? CPUMGetGuestEIP(pVCpu) : CPUMGetHyperEIP(pVCpu), fGuest ? CPUMGetGuestEFlags(pVCpu) : CPUMGetHyperEFlags(pVCpu), rc));
#endif
    } while (   rc == VINF_SUCCESS
             || rc == VINF_EM_RAW_INTERRUPT);
    rc = CPUMRawLeave(pVCpu, rc);
    VMCPU_FF_CLEAR_MASK(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);

    /*
     * Make sure the trap flag is cleared.
     * (Too bad if the guest is trying to single step too.)
     */
    if (fGuest)
        CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
    else
        CPUMSetHyperEFlags(pVCpu, CPUMGetHyperEFlags(pVCpu) & ~X86_EFL_TF);

    /*
     * Deal with the return codes.
     */
    rc = VBOXSTRICTRC_TODO(emR3HighPriorityPostForcedActions(pVM, pVCpu, rc));
    rc = emR3RawHandleRC(pVM, pVCpu, rc);
    rc = emR3RawUpdateForceFlag(pVM, pVCpu, rc);
    return rc;
}


#ifdef DEBUG


int emR3SingleStepExecRaw(PVM pVM, PVMCPU pVCpu, uint32_t cIterations)
{
    int     rc          = VINF_SUCCESS;
    EMSTATE enmOldState = pVCpu->em.s.enmState;
    pVCpu->em.s.enmState  = EMSTATE_DEBUG_GUEST_RAW;

    Log(("Single step BEGIN:\n"));
    for (uint32_t i = 0; i < cIterations; i++)
    {
        DBGFR3PrgStep(pVCpu);
        DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "RSS");
        rc = emR3RawStep(pVM, pVCpu);
        if (   rc != VINF_SUCCESS
            && rc != VINF_EM_DBG_STEPPED)
            break;
    }
    Log(("Single step END: rc=%Rrc\n", rc));
    CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
    pVCpu->em.s.enmState = enmOldState;
    return rc;
}

#endif /* DEBUG */


/**
 * Executes one (or perhaps a few more) instruction(s).
 *
 * @returns VBox status code suitable for EM.
 *
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 * @param   rcGC        GC return code
 * @param   pszPrefix   Disassembly prefix. If not NULL we'll disassemble the
 *                      instruction and prefix the log output with this text.
 */
#if defined(LOG_ENABLED) || defined(DOXYGEN_RUNNING)
static int emR3RawExecuteInstructionWorker(PVM pVM, PVMCPU pVCpu, int rcGC, const char *pszPrefix)
#else
static int emR3RawExecuteInstructionWorker(PVM pVM, PVMCPU pVCpu, int rcGC)
#endif
{
    int      rc;

#ifdef LOG_ENABLED
    /*
     * Disassemble the instruction if requested.
     */
    if (pszPrefix)
    {
        DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", pszPrefix);
        DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, pszPrefix);
    }
#endif /* LOG_ENABLED */

    /*
     * PATM is making life more interesting.
     * We cannot hand anything to REM which has an EIP inside patch code. So, we'll
     * tell PATM there is a trap in this code and have it take the appropriate actions
     * to allow us execute the code in REM.
     */
    if (PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
    {
        Log(("emR3RawExecuteInstruction: In patch block. eip=%RRv\n", (RTRCPTR)pVCpu->cpum.GstCtx.eip));

        RTGCPTR uNewEip;
        rc = PATMR3HandleTrap(pVM, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.eip, &uNewEip);
        switch (rc)
        {
            /*
             * It's not very useful to emulate a single instruction and then go back to raw
             * mode; just execute the whole block until IF is set again.
             */
            case VINF_SUCCESS:
                Log(("emR3RawExecuteInstruction: Executing instruction starting at new address %RGv IF=%d VMIF=%x\n",
                     uNewEip, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
                pVCpu->cpum.GstCtx.eip = uNewEip;
                Assert(pVCpu->cpum.GstCtx.eip);

                if (pVCpu->cpum.GstCtx.eflags.Bits.u1IF)
                {
                    /*
                     * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
                     */
                    Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
                    return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
                }
                else if (rcGC == VINF_PATM_PENDING_IRQ_AFTER_IRET)
                {
                    /* special case: iret, that sets IF,  detected a pending irq/event */
                    return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIRET");
                }
                return VINF_EM_RESCHEDULE_REM;

            /*
             * One instruction.
             */
            case VINF_PATCH_EMULATE_INSTR:
                Log(("emR3RawExecuteInstruction: Emulate patched instruction at %RGv IF=%d VMIF=%x\n",
                     uNewEip, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
                pVCpu->cpum.GstCtx.eip = uNewEip;
                return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");

            /*
             * The patch was disabled, hand it to the REM.
             */
            case VERR_PATCH_DISABLED:
                Log(("emR3RawExecuteInstruction: Disabled patch -> new eip %RGv IF=%d VMIF=%x\n",
                     uNewEip, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
                pVCpu->cpum.GstCtx.eip = uNewEip;
                if (pVCpu->cpum.GstCtx.eflags.Bits.u1IF)
                {
                    /*
                     * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
                     */
                    Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
                    return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
                }
                return VINF_EM_RESCHEDULE_REM;

            /* Force continued patch exection; usually due to write monitored stack. */
            case VINF_PATCH_CONTINUE:
                return VINF_SUCCESS;

            default:
                AssertReleaseMsgFailed(("Unknown return code %Rrc from PATMR3HandleTrap\n", rc));
                return VERR_IPE_UNEXPECTED_STATUS;
        }
    }


    /*
     * Use IEM and fallback on REM if the functionality is missing.
     * Once IEM gets mature enough, nothing should ever fall back.
     */
#define VBOX_WITH_FIRST_IEM_STEP_B
#if defined(VBOX_WITH_FIRST_IEM_STEP_B) || !defined(VBOX_WITH_REM)
    Log(("EMINS: %04x:%RGv RSP=%RGv\n", pVCpu->cpum.GstCtx.cs.Sel, (RTGCPTR)pVCpu->cpum.GstCtx.rip, (RTGCPTR)pVCpu->cpum.GstCtx.rsp));
    STAM_PROFILE_START(&pVCpu->em.s.StatIEMEmu, a);
    rc = VBOXSTRICTRC_TODO(IEMExecOne(pVCpu));
    STAM_PROFILE_STOP(&pVCpu->em.s.StatIEMEmu, a);
    if (RT_SUCCESS(rc))
    {
        if (rc == VINF_SUCCESS || rc == VINF_EM_RESCHEDULE)
            rc = VINF_EM_RESCHEDULE;
    }
    else if (   rc == VERR_IEM_ASPECT_NOT_IMPLEMENTED
             || rc == VERR_IEM_INSTR_NOT_IMPLEMENTED)
#endif
    {
#ifdef VBOX_WITH_REM
        STAM_PROFILE_START(&pVCpu->em.s.StatREMEmu, b);
# ifndef VBOX_WITH_FIRST_IEM_STEP_B
        Log(("EMINS[rem]: %04x:%RGv RSP=%RGv\n", pVCpu->cpum.GstCtx.cs.Sel, (RTGCPTR)pVCpu->cpum.GstCtx.rip, (RTGCPTR)pVCpu->cpum.GstCtx.rsp));
//# elif defined(DEBUG_bird)
//        AssertFailed();
# endif
        EMRemLock(pVM);
        /* Flush the recompiler TLB if the VCPU has changed. */
        if (pVM->em.s.idLastRemCpu != pVCpu->idCpu)
            CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_ALL);
        pVM->em.s.idLastRemCpu = pVCpu->idCpu;

        rc = REMR3EmulateInstruction(pVM, pVCpu);
        EMRemUnlock(pVM);
        STAM_PROFILE_STOP(&pVCpu->em.s.StatREMEmu, b);
#else  /* !VBOX_WITH_REM */
        NOREF(pVM);
#endif /* !VBOX_WITH_REM */
    }
    return rc;
}


/**
 * Executes one (or perhaps a few more) instruction(s).
 * This is just a wrapper for discarding pszPrefix in non-logging builds.
 *
 * @returns VBox status code suitable for EM.
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 * @param   pszPrefix   Disassembly prefix. If not NULL we'll disassemble the
 *                      instruction and prefix the log output with this text.
 * @param   rcGC        GC return code
 */
DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, PVMCPU pVCpu, const char *pszPrefix, int rcGC)
{
#ifdef LOG_ENABLED
    return emR3RawExecuteInstructionWorker(pVM, pVCpu, rcGC, pszPrefix);
#else
    RT_NOREF_PV(pszPrefix);
    return emR3RawExecuteInstructionWorker(pVM, pVCpu, rcGC);
#endif
}

/**
 * Executes one (or perhaps a few more) IO instruction(s).
 *
 * @returns VBox status code suitable for EM.
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 */
static int emR3RawExecuteIOInstruction(PVM pVM, PVMCPU pVCpu)
{
    STAM_PROFILE_START(&pVCpu->em.s.StatIOEmu, a);
    RT_NOREF_PV(pVM);

    /* Hand it over to the interpreter. */
    VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
    LogFlow(("emR3RawExecuteIOInstruction: %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
    STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatIoIem);
    STAM_PROFILE_STOP(&pVCpu->em.s.StatIOEmu, a);
    return VBOXSTRICTRC_TODO(rcStrict);
}


/**
 * Handle a guest context trap.
 *
 * @returns VBox status code suitable for EM.
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 */
static int emR3RawGuestTrap(PVM pVM, PVMCPU pVCpu)
{
    /*
     * Get the trap info.
     */
    uint8_t         u8TrapNo;
    TRPMEVENT       enmType;
    RTGCUINT        uErrorCode;
    RTGCUINTPTR     uCR2;
    int rc = TRPMQueryTrapAll(pVCpu, &u8TrapNo, &enmType, &uErrorCode, &uCR2, NULL /* pu8InstrLen */);
    if (RT_FAILURE(rc))
    {
        AssertReleaseMsgFailed(("No trap! (rc=%Rrc)\n", rc));
        return rc;
    }


#if 1 /* Experimental: Review, disable if it causes trouble. */
    /*
     * Handle traps in patch code first.
     *
     * We catch a few of these cases in RC before returning to R3 (#PF, #GP, #BP)
     * but several traps isn't handled specially by TRPM in RC and we end up here
     * instead. One example is #DE.
     */
    uint32_t uCpl = CPUMGetGuestCPL(pVCpu);
    if (    uCpl == 0
        &&  PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
    {
        LogFlow(("emR3RawGuestTrap: trap %#x in patch code; eip=%08x\n", u8TrapNo, pVCpu->cpum.GstCtx.eip));
        return emR3RawPatchTrap(pVM, pVCpu, rc);
    }
#endif

    /*
     * If the guest gate is marked unpatched, then we will check again if we can patch it.
     * (This assumes that we've already tried and failed to dispatch the trap in
     * RC for the gates that already has been patched. Which is true for most high
     * volume traps, because these are handled specially, but not for odd ones like #DE.)
     */
    if (TRPMR3GetGuestTrapHandler(pVM, u8TrapNo) == TRPM_INVALID_HANDLER)
    {
        CSAMR3CheckGates(pVM, u8TrapNo, 1);
        Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8TrapNo, TRPMR3GetGuestTrapHandler(pVM, u8TrapNo) != TRPM_INVALID_HANDLER));

        /* If it was successful, then we could go back to raw mode. */
        if (TRPMR3GetGuestTrapHandler(pVM, u8TrapNo) != TRPM_INVALID_HANDLER)
        {
            /* Must check pending forced actions as our IDT or GDT might be out of sync. */
            rc = EMR3CheckRawForcedActions(pVM, pVCpu);
            AssertRCReturn(rc, rc);

            TRPMERRORCODE enmError = uErrorCode != ~0U
                                   ? TRPM_TRAP_HAS_ERRORCODE
                                   : TRPM_TRAP_NO_ERRORCODE;
            rc = TRPMForwardTrap(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), u8TrapNo, uErrorCode, enmError, TRPM_TRAP, -1);
            if (rc == VINF_SUCCESS /* Don't use RT_SUCCESS */)
            {
                TRPMResetTrap(pVCpu);
                return VINF_EM_RESCHEDULE_RAW;
            }
            AssertMsg(rc == VINF_EM_RAW_GUEST_TRAP, ("%Rrc\n", rc));
        }
    }

    /*
     * Scan kernel code that traps; we might not get another chance.
     */
    /** @todo move this up before the dispatching? */
    if (    (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) <= 1
        &&  !pVCpu->cpum.GstCtx.eflags.Bits.u1VM)
    {
        Assert(!PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip));
        CSAMR3CheckCodeEx(pVM, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.eip);
    }

    /*
     * Trap specific handling.
     */
    if (u8TrapNo == 6) /* (#UD) Invalid opcode. */
    {
        /*
         * If MONITOR & MWAIT are supported, then interpret them here.
         */
        DISCPUSTATE cpu;
        rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.rip, &cpu, "Guest Trap (#UD): ");
        if (    RT_SUCCESS(rc)
            && (cpu.pCurInstr->uOpcode == OP_MONITOR || cpu.pCurInstr->uOpcode == OP_MWAIT))
        {
            uint32_t u32Dummy, u32Features, u32ExtFeatures;
            CPUMGetGuestCpuId(pVCpu, 1, 0, &u32Dummy, &u32Dummy, &u32ExtFeatures, &u32Features);
            if (u32ExtFeatures & X86_CPUID_FEATURE_ECX_MONITOR)
            {
                rc = TRPMResetTrap(pVCpu);
                AssertRC(rc);

                rc = VBOXSTRICTRC_TODO(EMInterpretInstructionDisasState(pVCpu, &cpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx),
                                                                        0, EMCODETYPE_SUPERVISOR));
                if (RT_SUCCESS(rc))
                    return rc;
                return emR3RawExecuteInstruction(pVM, pVCpu, "Monitor: ");
            }
        }
    }
    else if (u8TrapNo == 13) /* (#GP) Privileged exception */
    {
        /*
         * Handle I/O bitmap?
         */
        /** @todo We're not supposed to be here with a false guest trap concerning
         *        I/O access. We can easily handle those in RC.  */
        DISCPUSTATE cpu;
        rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.rip, &cpu, "Guest Trap: ");
        if (    RT_SUCCESS(rc)
            &&  (cpu.pCurInstr->fOpType & DISOPTYPE_PORTIO))
        {
            /*
             * We should really check the TSS for the IO bitmap, but it's not like this
             * lazy approach really makes things worse.
             */
            rc = TRPMResetTrap(pVCpu);
            AssertRC(rc);
            return emR3RawExecuteInstruction(pVM, pVCpu, "IO Guest Trap: ");
        }
    }

#ifdef LOG_ENABLED
    DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", "Guest trap");
    DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Guest trap");

    /* Get guest page information. */
    uint64_t    fFlags = 0;
    RTGCPHYS    GCPhys = 0;
    int rc2 = PGMGstGetPage(pVCpu, uCR2, &fFlags, &GCPhys);
    Log(("emR3RawGuestTrap: cs:eip=%04x:%08x: trap=%02x err=%08x cr2=%08x cr0=%08x%s: Phys=%RGp fFlags=%08llx %s %s %s%s rc2=%d\n",
         pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, u8TrapNo, uErrorCode, uCR2, (uint32_t)pVCpu->cpum.GstCtx.cr0,
         (enmType == TRPM_SOFTWARE_INT) ? " software" : "",  GCPhys, fFlags,
         fFlags & X86_PTE_P  ? "P " : "NP", fFlags & X86_PTE_US ? "U"  : "S",
         fFlags & X86_PTE_RW ? "RW" : "R0", fFlags & X86_PTE_G  ? " G" : "", rc2));
#endif

    /*
     * #PG has CR2.
     * (Because of stuff like above we must set CR2 in a delayed fashion.)
     */
    if (u8TrapNo == 14 /* #PG */)
        pVCpu->cpum.GstCtx.cr2 = uCR2;

    return VINF_EM_RESCHEDULE_REM;
}


/**
 * Handle a ring switch trap.
 * Need to do statistics and to install patches. The result is going to REM.
 *
 * @returns VBox status code suitable for EM.
 * @param   pVM     The cross context VM structure.
 * @param   pVCpu   The cross context virtual CPU structure.
 */
static int emR3RawRingSwitch(PVM pVM, PVMCPU pVCpu)
{
    int         rc;
    DISCPUSTATE Cpu;

    /*
     * sysenter, syscall & callgate
     */
    rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.rip, &Cpu, "RSWITCH: ");
    if (RT_SUCCESS(rc))
    {
        if (Cpu.pCurInstr->uOpcode == OP_SYSENTER)
        {
            if (pVCpu->cpum.GstCtx.SysEnter.cs != 0)
            {
                rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, DISSELREG_CS, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pVCpu->cpum.GstCtx.eip),
                                        CPUMGetGuestCodeBits(pVCpu) == 32 ? PATMFL_CODE32 : 0);
                if (RT_SUCCESS(rc))
                {
                    DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Patched sysenter instruction");
                    return VINF_EM_RESCHEDULE_RAW;
                }
            }
        }

#ifdef VBOX_WITH_STATISTICS
        switch (Cpu.pCurInstr->uOpcode)
        {
            case OP_SYSENTER:
                STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysEnter);
                break;
            case OP_SYSEXIT:
                STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysExit);
                break;
            case OP_SYSCALL:
                STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysCall);
                break;
            case OP_SYSRET:
                STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysRet);
                break;
        }
#endif
    }
    else
        AssertRC(rc);

    /* go to the REM to emulate a single instruction */
    return emR3RawExecuteInstruction(pVM, pVCpu, "RSWITCH: ");
}


/**
 * Handle a trap (\#PF or \#GP) in patch code
 *
 * @returns VBox status code suitable for EM.
 * @param   pVM     The cross context VM structure.
 * @param   pVCpu   The cross context virtual CPU structure.
 * @param   gcret   GC return code.
 */
static int emR3RawPatchTrap(PVM pVM, PVMCPU pVCpu, int gcret)
{
    uint8_t         u8TrapNo;
    int             rc;
    TRPMEVENT       enmType;
    RTGCUINT        uErrorCode;
    RTGCUINTPTR     uCR2;

    Assert(PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip));

    if (gcret == VINF_PATM_PATCH_INT3)
    {
        u8TrapNo   = 3;
        uCR2       = 0;
        uErrorCode = 0;
    }
    else if (gcret == VINF_PATM_PATCH_TRAP_GP)
    {
        /* No active trap in this case. Kind of ugly. */
        u8TrapNo   = X86_XCPT_GP;
        uCR2       = 0;
        uErrorCode = 0;
    }
    else
    {
        rc = TRPMQueryTrapAll(pVCpu, &u8TrapNo, &enmType, &uErrorCode, &uCR2, NULL /* pu8InstrLen */);
        if (RT_FAILURE(rc))
        {
            AssertReleaseMsgFailed(("emR3RawPatchTrap: no trap! (rc=%Rrc) gcret=%Rrc\n", rc, gcret));
            return rc;
        }
        /* Reset the trap as we'll execute the original instruction again. */
        TRPMResetTrap(pVCpu);
    }

    /*
     * Deal with traps inside patch code.
     * (This code won't run outside GC.)
     */
    if (u8TrapNo != 1)
    {
#ifdef LOG_ENABLED
        DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", "Trap in patch code");
        DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Patch code");

        DISCPUSTATE Cpu;
        rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.eip, &Cpu, "Patch code: ");
        if (    RT_SUCCESS(rc)
            &&  Cpu.pCurInstr->uOpcode == OP_IRET)
        {
            uint32_t eip, selCS, uEFlags;

            /* Iret crashes are bad as we have already changed the flags on the stack */
            rc  = PGMPhysSimpleReadGCPtr(pVCpu, &eip,     pVCpu->cpum.GstCtx.esp, 4);
            rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selCS,   pVCpu->cpum.GstCtx.esp+4, 4);
            rc |= PGMPhysSimpleReadGCPtr(pVCpu, &uEFlags, pVCpu->cpum.GstCtx.esp+8, 4);
            if (rc == VINF_SUCCESS)
            {
                if (    (uEFlags & X86_EFL_VM)
                    ||  (selCS & X86_SEL_RPL) == 3)
                {
                    uint32_t selSS, esp;

                    rc |= PGMPhysSimpleReadGCPtr(pVCpu, &esp,     pVCpu->cpum.GstCtx.esp + 12, 4);
                    rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selSS,   pVCpu->cpum.GstCtx.esp + 16, 4);

                    if (uEFlags & X86_EFL_VM)
                    {
                        uint32_t selDS, selES, selFS, selGS;
                        rc  = PGMPhysSimpleReadGCPtr(pVCpu, &selES,   pVCpu->cpum.GstCtx.esp + 20, 4);
                        rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selDS,   pVCpu->cpum.GstCtx.esp + 24, 4);
                        rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selFS,   pVCpu->cpum.GstCtx.esp + 28, 4);
                        rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selGS,   pVCpu->cpum.GstCtx.esp + 32, 4);
                        if (rc == VINF_SUCCESS)
                        {
                            Log(("Patch code: IRET->VM stack frame: return address %04X:%08RX32 eflags=%08x ss:esp=%04X:%08RX32\n", selCS, eip, uEFlags, selSS, esp));
                            Log(("Patch code: IRET->VM stack frame: DS=%04X ES=%04X FS=%04X GS=%04X\n", selDS, selES, selFS, selGS));
                        }
                    }
                    else
                        Log(("Patch code: IRET stack frame: return address %04X:%08RX32 eflags=%08x ss:esp=%04X:%08RX32\n", selCS, eip, uEFlags, selSS, esp));
                }
                else
                    Log(("Patch code: IRET stack frame: return address %04X:%08RX32 eflags=%08x\n", selCS, eip, uEFlags));
            }
        }
#endif /* LOG_ENABLED */
        Log(("emR3RawPatchTrap: in patch: eip=%08x: trap=%02x err=%08x cr2=%08x cr0=%08x\n",
             pVCpu->cpum.GstCtx.eip, u8TrapNo, uErrorCode, uCR2, (uint32_t)pVCpu->cpum.GstCtx.cr0));

        RTGCPTR uNewEip;
        rc = PATMR3HandleTrap(pVM, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.eip, &uNewEip);
        switch (rc)
        {
            /*
             * Execute the faulting instruction.
             */
            case VINF_SUCCESS:
            {
                /** @todo execute a whole block */
                Log(("emR3RawPatchTrap: Executing faulting instruction at new address %RGv\n", uNewEip));
                if (!(pVCpu->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
                    Log(("emR3RawPatchTrap: Virtual IF flag disabled!!\n"));

                pVCpu->cpum.GstCtx.eip = uNewEip;
                AssertRelease(pVCpu->cpum.GstCtx.eip);

                if (pVCpu->cpum.GstCtx.eflags.Bits.u1IF)
                {
                    /* Windows XP lets irets fault intentionally and then takes action based on the opcode; an
                     * int3 patch overwrites it and leads to blue screens. Remove the patch in this case.
                     */
                    if (    u8TrapNo == X86_XCPT_GP
                        &&  PATMIsInt3Patch(pVM, pVCpu->cpum.GstCtx.eip, NULL, NULL))
                    {
                        /** @todo move to PATMR3HandleTrap */
                        Log(("Possible Windows XP iret fault at %08RX32\n", pVCpu->cpum.GstCtx.eip));
                        PATMR3RemovePatch(pVM, pVCpu->cpum.GstCtx.eip);
                    }

                    /** @todo Knoppix 5 regression when returning VINF_SUCCESS here and going back to raw mode. */
                    /* Note: possibly because a reschedule is required (e.g. iret to V86 code) */

                    return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
                    /* Interrupts are enabled; just go back to the original instruction.
                    return VINF_SUCCESS; */
                }
                return VINF_EM_RESCHEDULE_REM;
            }

            /*
             * One instruction.
             */
            case VINF_PATCH_EMULATE_INSTR:
                Log(("emR3RawPatchTrap: Emulate patched instruction at %RGv IF=%d VMIF=%x\n",
                     uNewEip, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
                pVCpu->cpum.GstCtx.eip = uNewEip;
                AssertRelease(pVCpu->cpum.GstCtx.eip);
                return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHEMUL: ");

            /*
             * The patch was disabled, hand it to the REM.
             */
            case VERR_PATCH_DISABLED:
                if (!(pVCpu->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
                    Log(("emR3RawPatchTrap: Virtual IF flag disabled!!\n"));
                pVCpu->cpum.GstCtx.eip = uNewEip;
                AssertRelease(pVCpu->cpum.GstCtx.eip);

                if (pVCpu->cpum.GstCtx.eflags.Bits.u1IF)
                {
                    /*
                     * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
                     */
                    Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
                    return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
                }
                return VINF_EM_RESCHEDULE_REM;

            /* Force continued patch exection; usually due to write monitored stack. */
            case VINF_PATCH_CONTINUE:
                return VINF_SUCCESS;

            /*
             * Anything else is *fatal*.
             */
            default:
                AssertReleaseMsgFailed(("Unknown return code %Rrc from PATMR3HandleTrap!\n", rc));
                return VERR_IPE_UNEXPECTED_STATUS;
        }
    }
    return VINF_SUCCESS;
}


/**
 * Handle a privileged instruction.
 *
 * @returns VBox status code suitable for EM.
 * @param   pVM     The cross context VM structure.
 * @param   pVCpu   The cross context virtual CPU structure.
 */
static int emR3RawPrivileged(PVM pVM, PVMCPU pVCpu)
{
    Assert(!pVCpu->cpum.GstCtx.eflags.Bits.u1VM);

    if (PATMIsEnabled(pVM))
    {
        /*
         * Check if in patch code.
         */
        if (PATMR3IsInsidePatchJump(pVM, pVCpu->cpum.GstCtx.eip, NULL))
        {
#ifdef LOG_ENABLED
            DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", "PRIV");
#endif
            AssertMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08x\n", pVCpu->cpum.GstCtx.eip));
            return VERR_EM_RAW_PATCH_CONFLICT;
        }
        if (   (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 0
            && !pVCpu->cpum.GstCtx.eflags.Bits.u1VM
            && !PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
        {
            int rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, DISSELREG_CS, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pVCpu->cpum.GstCtx.eip),
                                        CPUMGetGuestCodeBits(pVCpu) == 32 ? PATMFL_CODE32 : 0);
            if (RT_SUCCESS(rc))
            {
#ifdef LOG_ENABLED
                DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", "PRIV");
#endif
                DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Patched privileged instruction");
                return VINF_SUCCESS;
            }
        }
    }

#ifdef LOG_ENABLED
    if (!PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
    {
        DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", "PRIV");
        DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Privileged instr");
    }
#endif

    /*
     * Instruction statistics and logging.
     */
    DISCPUSTATE Cpu;
    int         rc;

    rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.rip, &Cpu, "PRIV: ");
    if (RT_SUCCESS(rc))
    {
#ifdef VBOX_WITH_STATISTICS
        PEMSTATS pStats = pVCpu->em.s.CTX_SUFF(pStats);
        switch (Cpu.pCurInstr->uOpcode)
        {
            case OP_INVLPG:
                STAM_COUNTER_INC(&pStats->StatInvlpg);
                break;
            case OP_IRET:
                STAM_COUNTER_INC(&pStats->StatIret);
                break;
            case OP_CLI:
                STAM_COUNTER_INC(&pStats->StatCli);
                emR3RecordCli(pVM, pVCpu, pVCpu->cpum.GstCtx.rip);
                break;
            case OP_STI:
                STAM_COUNTER_INC(&pStats->StatSti);
                break;
            case OP_INSB:
            case OP_INSWD:
            case OP_IN:
            case OP_OUTSB:
            case OP_OUTSWD:
            case OP_OUT:
                AssertMsgFailed(("Unexpected privileged exception due to port IO\n"));
                break;

            case OP_MOV_CR:
                if (Cpu.Param1.fUse & DISUSE_REG_GEN32)
                {
                    //read
                    Assert(Cpu.Param2.fUse & DISUSE_REG_CR);
                    Assert(Cpu.Param2.Base.idxCtrlReg <= DISCREG_CR4);
                    STAM_COUNTER_INC(&pStats->StatMovReadCR[Cpu.Param2.Base.idxCtrlReg]);
                }
                else
                {
                    //write
                    Assert(Cpu.Param1.fUse & DISUSE_REG_CR);
                    Assert(Cpu.Param1.Base.idxCtrlReg <= DISCREG_CR4);
                    STAM_COUNTER_INC(&pStats->StatMovWriteCR[Cpu.Param1.Base.idxCtrlReg]);
                }
                break;

            case OP_MOV_DR:
                STAM_COUNTER_INC(&pStats->StatMovDRx);
                break;
            case OP_LLDT:
                STAM_COUNTER_INC(&pStats->StatMovLldt);
                break;
            case OP_LIDT:
                STAM_COUNTER_INC(&pStats->StatMovLidt);
                break;
            case OP_LGDT:
                STAM_COUNTER_INC(&pStats->StatMovLgdt);
                break;
            case OP_SYSENTER:
                STAM_COUNTER_INC(&pStats->StatSysEnter);
                break;
            case OP_SYSEXIT:
                STAM_COUNTER_INC(&pStats->StatSysExit);
                break;
            case OP_SYSCALL:
                STAM_COUNTER_INC(&pStats->StatSysCall);
                break;
            case OP_SYSRET:
                STAM_COUNTER_INC(&pStats->StatSysRet);
                break;
            case OP_HLT:
                STAM_COUNTER_INC(&pStats->StatHlt);
                break;
            default:
                STAM_COUNTER_INC(&pStats->StatMisc);
                Log4(("emR3RawPrivileged: opcode=%d\n", Cpu.pCurInstr->uOpcode));
                break;
        }
#endif /* VBOX_WITH_STATISTICS */
        if (    (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 0
            &&  !pVCpu->cpum.GstCtx.eflags.Bits.u1VM
            &&  CPUMGetGuestCodeBits(pVCpu) == 32)
        {
            STAM_PROFILE_START(&pVCpu->em.s.StatPrivEmu, a);
            switch (Cpu.pCurInstr->uOpcode)
            {
                case OP_CLI:
                    pVCpu->cpum.GstCtx.eflags.u32 &= ~X86_EFL_IF;
                    Assert(Cpu.cbInstr == 1);
                    pVCpu->cpum.GstCtx.rip += Cpu.cbInstr;
                    STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
                    return VINF_EM_RESCHEDULE_REM; /* must go to the recompiler now! */

                case OP_STI:
                    pVCpu->cpum.GstCtx.eflags.u32 |= X86_EFL_IF;
                    EMSetInhibitInterruptsPC(pVCpu, pVCpu->cpum.GstCtx.rip + Cpu.cbInstr);
                    Assert(Cpu.cbInstr == 1);
                    pVCpu->cpum.GstCtx.rip += Cpu.cbInstr;
                    STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
                    return VINF_SUCCESS;

                case OP_HLT:
                    if (PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
                    {
                        PATMTRANSSTATE  enmState;
                        RTGCPTR         pOrgInstrGC = PATMR3PatchToGCPtr(pVM, pVCpu->cpum.GstCtx.eip, &enmState);

                        if (enmState == PATMTRANS_OVERWRITTEN)
                        {
                            rc = PATMR3DetectConflict(pVM, pOrgInstrGC, pOrgInstrGC);
                            Assert(rc == VERR_PATCH_DISABLED);
                            /* Conflict detected, patch disabled */
                            Log(("emR3RawPrivileged: detected conflict -> disabled patch at %08RX32\n", pVCpu->cpum.GstCtx.eip));

                            enmState = PATMTRANS_SAFE;
                        }

                        /* The translation had better be successful. Otherwise we can't recover. */
                        AssertReleaseMsg(pOrgInstrGC && enmState != PATMTRANS_OVERWRITTEN, ("Unable to translate instruction address at %08RX32\n", pVCpu->cpum.GstCtx.eip));
                        if (enmState != PATMTRANS_OVERWRITTEN)
                            pVCpu->cpum.GstCtx.eip = pOrgInstrGC;
                    }
                    /* no break; we could just return VINF_EM_HALT here */
                    RT_FALL_THRU();

                case OP_MOV_CR:
                case OP_MOV_DR:
#ifdef LOG_ENABLED
                    if (PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
                    {
                        DBGFR3_INFO_LOG(pVM, pVCpu, "cpumguest", "PRIV");
                        DBGFR3_DISAS_INSTR_CUR_LOG(pVCpu, "Privileged instr");
                    }
#endif

                    rc = VBOXSTRICTRC_TODO(EMInterpretInstructionDisasState(pVCpu, &Cpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx),
                                                                            0, EMCODETYPE_SUPERVISOR));
                    if (RT_SUCCESS(rc))
                    {
                        STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);

                        if (    Cpu.pCurInstr->uOpcode == OP_MOV_CR
                            &&  Cpu.Param1.fUse == DISUSE_REG_CR /* write */
                           )
                        {
                            /* Deal with CR0 updates inside patch code that force
                             * us to go to the recompiler.
                             */
                            if (   PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.rip)
                                && (pVCpu->cpum.GstCtx.cr0 & (X86_CR0_WP|X86_CR0_PG|X86_CR0_PE)) != (X86_CR0_WP|X86_CR0_PG|X86_CR0_PE))
                            {
                                PATMTRANSSTATE  enmState;
                                RTGCPTR         pOrgInstrGC = PATMR3PatchToGCPtr(pVM, pVCpu->cpum.GstCtx.rip, &enmState);

                                Log(("Force recompiler switch due to cr0 (%RGp) update rip=%RGv -> %RGv (enmState=%d)\n", pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.rip, pOrgInstrGC, enmState));
                                if (enmState == PATMTRANS_OVERWRITTEN)
                                {
                                    rc = PATMR3DetectConflict(pVM, pOrgInstrGC, pOrgInstrGC);
                                    Assert(rc == VERR_PATCH_DISABLED);
                                    /* Conflict detected, patch disabled */
                                    Log(("emR3RawPrivileged: detected conflict -> disabled patch at %RGv\n", (RTGCPTR)pVCpu->cpum.GstCtx.rip));
                                    enmState = PATMTRANS_SAFE;
                                }
                                /* The translation had better be successful. Otherwise we can't recover. */
                                AssertReleaseMsg(pOrgInstrGC && enmState != PATMTRANS_OVERWRITTEN, ("Unable to translate instruction address at %RGv\n", (RTGCPTR)pVCpu->cpum.GstCtx.rip));
                                if (enmState != PATMTRANS_OVERWRITTEN)
                                    pVCpu->cpum.GstCtx.rip = pOrgInstrGC;
                            }

                            /* Reschedule is necessary as the execution/paging mode might have changed. */
                            return VINF_EM_RESCHEDULE;
                        }
                        return rc; /* can return VINF_EM_HALT as well. */
                    }
                    AssertMsgReturn(rc == VERR_EM_INTERPRETER, ("%Rrc\n", rc), rc);
                    break; /* fall back to the recompiler */
            }
            STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
        }
    }

    if (PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
        return emR3RawPatchTrap(pVM, pVCpu, VINF_PATM_PATCH_TRAP_GP);

    return emR3RawExecuteInstruction(pVM, pVCpu, "PRIV");
}


/**
 * Update the forced rawmode execution modifier.
 *
 * This function is called when we're returning from the raw-mode loop(s). If we're
 * in patch code, it will set a flag forcing execution to be resumed in raw-mode,
 * if not in patch code, the flag will be cleared.
 *
 * We should never interrupt patch code while it's being executed. Cli patches can
 * contain big code blocks, but they are always executed with IF=0. Other patches
 * replace single instructions and should be atomic.
 *
 * @returns Updated rc.
 *
 * @param   pVM     The cross context VM structure.
 * @param   pVCpu   The cross context virtual CPU structure.
 * @param   rc      The result code.
 */
static int emR3RawUpdateForceFlag(PVM pVM, PVMCPU pVCpu, int rc)
{
    if (PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip)) /** @todo check cs selector base/type */
    {
        /* ignore reschedule attempts. */
        switch (rc)
        {
            case VINF_EM_RESCHEDULE:
            case VINF_EM_RESCHEDULE_REM:
                LogFlow(("emR3RawUpdateForceFlag: patch address -> force raw reschedule\n"));
                rc = VINF_SUCCESS;
                break;
        }
        pVCpu->em.s.fForceRAW = true;
    }
    else
        pVCpu->em.s.fForceRAW = false;
    return rc;
}


/**
 * Check for pending raw actions
 *
 * @returns VBox status code. May return VINF_EM_NO_MEMORY but none of the other
 *          EM statuses.
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 */
VMMR3_INT_DECL(int) EMR3CheckRawForcedActions(PVM pVM, PVMCPU pVCpu)
{
    int rc = emR3RawForcedActions(pVM, pVCpu);
    VBOXVMM_EM_FF_RAW_RET(pVCpu, rc);
    return rc;
}


/**
 * Process raw-mode specific forced actions.
 *
 * This function is called when any FFs in the VM_FF_HIGH_PRIORITY_PRE_RAW_MASK is pending.
 *
 * @returns VBox status code. May return VINF_EM_NO_MEMORY but none of the other
 *          EM statuses.
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 */
static int emR3RawForcedActions(PVM pVM, PVMCPU pVCpu)
{
    /*
     * Note that the order is *vitally* important!
     * Also note that SELMR3UpdateFromCPUM may trigger VM_FF_SELM_SYNC_TSS.
     */
    VBOXVMM_EM_FF_RAW(pVCpu, pVM->fGlobalForcedActions, pVCpu->fLocalForcedActions);

    /*
     * Sync selector tables.
     */
    if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT))
    {
        VBOXSTRICTRC rcStrict = SELMR3UpdateFromCPUM(pVM, pVCpu);
        if (rcStrict != VINF_SUCCESS)
            return VBOXSTRICTRC_TODO(rcStrict);
    }

    /*
     * Sync IDT.
     *
     * The CSAMR3CheckGates call in TRPMR3SyncIDT may call PGMPrefetchPage
     * and PGMShwModifyPage, so we're in for trouble if for instance a
     * PGMSyncCR3+pgmR3PoolClearAll is pending.
     */
    if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TRPM_SYNC_IDT))
    {
        if (   VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3)
            && EMIsRawRing0Enabled(pVM)
            && CSAMIsEnabled(pVM))
        {
            int rc = PGMSyncCR3(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr3, pVCpu->cpum.GstCtx.cr4, VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
            if (RT_FAILURE(rc))
                return rc;
        }

        int rc = TRPMR3SyncIDT(pVM, pVCpu);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Sync TSS.
     */
    if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS))
    {
        int rc = SELMR3SyncTSS(pVM, pVCpu);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Sync page directory.
     */
    if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
    {
        Assert(pVCpu->em.s.enmState != EMSTATE_WAIT_SIPI);
        int rc = PGMSyncCR3(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr3, pVCpu->cpum.GstCtx.cr4, VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
        if (RT_FAILURE(rc))
            return rc == VERR_PGM_NO_HYPERVISOR_ADDRESS ? VINF_EM_RESCHEDULE_REM : rc;

        Assert(!VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT));

        /* Prefetch pages for EIP and ESP. */
        /** @todo This is rather expensive. Should investigate if it really helps at all. */
        rc = PGMPrefetchPage(pVCpu, SELMToFlat(pVM, DISSELREG_CS, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pVCpu->cpum.GstCtx.rip));
        if (rc == VINF_SUCCESS)
            rc = PGMPrefetchPage(pVCpu, SELMToFlat(pVM, DISSELREG_SS, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pVCpu->cpum.GstCtx.rsp));
        if (rc != VINF_SUCCESS)
        {
            if (rc != VINF_PGM_SYNC_CR3)
            {
                AssertLogRelMsgReturn(RT_FAILURE(rc), ("%Rrc\n", rc), VERR_IPE_UNEXPECTED_INFO_STATUS);
                return rc;
            }
            rc = PGMSyncCR3(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr3, pVCpu->cpum.GstCtx.cr4, VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
            if (RT_FAILURE(rc))
                return rc;
        }
        /** @todo maybe prefetch the supervisor stack page as well */
        Assert(!VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT));
    }

    /*
     * Allocate handy pages (just in case the above actions have consumed some pages).
     */
    if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_PGM_NEED_HANDY_PAGES, VM_FF_PGM_NO_MEMORY))
    {
        int rc = PGMR3PhysAllocateHandyPages(pVM);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Check whether we're out of memory now.
     *
     * This may stem from some of the above actions or operations that has been executed
     * since we ran FFs. The allocate handy pages must for instance always be followed by
     * this check.
     */
    if (VM_FF_IS_SET(pVM, VM_FF_PGM_NO_MEMORY))
        return VINF_EM_NO_MEMORY;

    return VINF_SUCCESS;
}


/**
 * Executes raw code.
 *
 * This function contains the raw-mode version of the inner
 * execution loop (the outer loop being in EMR3ExecuteVM()).
 *
 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE,
 *          VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
 *
 * @param   pVM         The cross context VM structure.
 * @param   pVCpu       The cross context virtual CPU structure.
 * @param   pfFFDone    Where to store an indicator telling whether or not
 *                      FFs were done before returning.
 */
int emR3RawExecute(PVM pVM, PVMCPU pVCpu, bool *pfFFDone)
{
    STAM_REL_PROFILE_ADV_START(&pVCpu->em.s.StatRAWTotal, a);

    int      rc = VERR_IPE_UNINITIALIZED_STATUS;
    LogFlow(("emR3RawExecute: (cs:eip=%04x:%08x)\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip));
    pVCpu->em.s.fForceRAW = false;
    *pfFFDone = false;


    /*
     *
     * Spin till we get a forced action or raw mode status code resulting in
     * in anything but VINF_SUCCESS or VINF_EM_RESCHEDULE_RAW.
     *
     */
    for (;;)
    {
        STAM_PROFILE_ADV_START(&pVCpu->em.s.StatRAWEntry, b);

        /*
         * Check various preconditions.
         */
#ifdef VBOX_STRICT
        Assert(pVCpu->cpum.GstCtx.eflags.Bits.u1VM || (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 3 || (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 0
               || (EMIsRawRing1Enabled(pVM) && (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 1));
        AssertMsg(   (pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_IF)
                  || PATMShouldUseRawMode(pVM, (RTGCPTR)pVCpu->cpum.GstCtx.eip),
                  ("Tried to execute code with IF at EIP=%08x!\n", pVCpu->cpum.GstCtx.eip));
        if (    !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL)
            &&  PGMMapHasConflicts(pVM))
        {
            PGMMapCheck(pVM);
            AssertMsgFailed(("We should not get conflicts any longer!!!\n"));
            return VERR_EM_UNEXPECTED_MAPPING_CONFLICT;
        }
#endif /* VBOX_STRICT */

        /*
         * Process high priority pre-execution raw-mode FFs.
         */
        if (    VM_FF_IS_ANY_SET(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
            ||  VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
        {
            rc = emR3RawForcedActions(pVM, pVCpu);
            VBOXVMM_EM_FF_RAW_RET(pVCpu, rc);
            if (rc != VINF_SUCCESS)
                break;
        }

        /*
         * If we're going to execute ring-0 code, the guest state needs to
         * be modified a bit and some of the state components (IF, SS/CS RPL,
         * and perhaps EIP) needs to be stored with PATM.
         */
        rc = CPUMRawEnter(pVCpu);
        if (rc != VINF_SUCCESS)
        {
            STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWEntry, b);
            break;
        }

        /*
         * Scan code before executing it. Don't bother with user mode or V86 code
         */
        if (    (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) <= 1
            &&  !pVCpu->cpum.GstCtx.eflags.Bits.u1VM
            && !PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip))
        {
            STAM_PROFILE_ADV_SUSPEND(&pVCpu->em.s.StatRAWEntry, b);
            CSAMR3CheckCodeEx(pVM, &pVCpu->cpum.GstCtx, pVCpu->cpum.GstCtx.eip);
            STAM_PROFILE_ADV_RESUME(&pVCpu->em.s.StatRAWEntry, b);
            if (    VM_FF_IS_ANY_SET(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
                ||  VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
            {
                rc = emR3RawForcedActions(pVM, pVCpu);
                VBOXVMM_EM_FF_RAW_RET(pVCpu, rc);
                if (rc != VINF_SUCCESS)
                {
                    rc = CPUMRawLeave(pVCpu, rc);
                    break;
                }
            }
        }

#ifdef LOG_ENABLED
        /*
         * Log important stuff before entering GC.
         */
        PPATMGCSTATE pGCState = PATMR3QueryGCStateHC(pVM);
        if (pVCpu->cpum.GstCtx.eflags.Bits.u1VM)
            Log(("RV86: %04x:%08x IF=%d VMFlags=%x\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pGCState->uVMFlags));
        else if ((pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 1)
            Log(("RR0: %x:%08x ESP=%x:%08x EFL=%x IF=%d/%d VMFlags=%x PIF=%d CPL=%d (Scanned=%d)\n",
                 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.ss.Sel, pVCpu->cpum.GstCtx.esp, CPUMRawGetEFlags(pVCpu), !!(pGCState->uVMFlags & X86_EFL_IF), pVCpu->cpum.GstCtx.eflags.Bits.u1IF,
                 pGCState->uVMFlags, pGCState->fPIF, (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL), CSAMIsPageScanned(pVM, (RTGCPTR)pVCpu->cpum.GstCtx.eip)));
# ifdef VBOX_WITH_RAW_RING1
        else if ((pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 2)
            Log(("RR1: %x:%08x ESP=%x:%08x IF=%d VMFlags=%x CPL=%x\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.ss.Sel, pVCpu->cpum.GstCtx.esp, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pGCState->uVMFlags, (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL)));
# endif
        else if ((pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) == 3)
            Log(("RR3: %x:%08x ESP=%x:%08x IF=%d VMFlags=%x\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.ss.Sel, pVCpu->cpum.GstCtx.esp, pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pGCState->uVMFlags));
#endif /* LOG_ENABLED */



        /*
         * Execute the code.
         */
        STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWEntry, b);
        if (RT_LIKELY(emR3IsExecutionAllowed(pVM, pVCpu)))
        {
            STAM_PROFILE_START(&pVCpu->em.s.StatRAWExec, c);
            VBOXVMM_EM_RAW_RUN_PRE(pVCpu, &pVCpu->cpum.GstCtx);
            rc = VMMR3RawRunGC(pVM, pVCpu);
            VBOXVMM_EM_RAW_RUN_RET(pVCpu, &pVCpu->cpum.GstCtx, rc);
            STAM_PROFILE_STOP(&pVCpu->em.s.StatRAWExec, c);
        }
        else
        {
            /* Give up this time slice; virtual time continues */
            STAM_REL_PROFILE_ADV_START(&pVCpu->em.s.StatCapped, u);
            RTThreadSleep(5);
            STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatCapped, u);
            rc = VINF_SUCCESS;
        }
        STAM_PROFILE_ADV_START(&pVCpu->em.s.StatRAWTail, d);

        LogFlow(("RR%u-E: %08x ESP=%08x EFL=%x IF=%d/%d VMFlags=%x PIF=%d\n",
                 (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL), pVCpu->cpum.GstCtx.eip, pVCpu->cpum.GstCtx.esp, CPUMRawGetEFlags(pVCpu),
                 !!(pGCState->uVMFlags & X86_EFL_IF), pVCpu->cpum.GstCtx.eflags.Bits.u1IF, pGCState->uVMFlags, pGCState->fPIF));
        LogFlow(("VMMR3RawRunGC returned %Rrc\n", rc));



        /*
         * Restore the real CPU state and deal with high priority post
         * execution FFs before doing anything else.
         */
        rc = CPUMRawLeave(pVCpu, rc);
        VMCPU_FF_CLEAR_MASK(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
        if (    VM_FF_IS_ANY_SET(pVM, VM_FF_HIGH_PRIORITY_POST_MASK)
            ||  VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HIGH_PRIORITY_POST_MASK))
            rc = VBOXSTRICTRC_TODO(emR3HighPriorityPostForcedActions(pVM, pVCpu, rc));

#ifdef VBOX_STRICT
        /*
         * Assert TSS consistency & rc vs patch code.
         */
        if (   !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS | VMCPU_FF_SELM_SYNC_GDT) /* GDT implies TSS at the moment. */
            &&  EMIsRawRing0Enabled(pVM))
            SELMR3CheckTSS(pVM);
        switch (rc)
        {
            case VINF_SUCCESS:
            case VINF_EM_RAW_INTERRUPT:
            case VINF_PATM_PATCH_TRAP_PF:
            case VINF_PATM_PATCH_TRAP_GP:
            case VINF_PATM_PATCH_INT3:
            case VINF_PATM_CHECK_PATCH_PAGE:
            case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
            case VINF_EM_RAW_GUEST_TRAP:
            case VINF_EM_RESCHEDULE_RAW:
                break;

            default:
                if (PATMIsPatchGCAddr(pVM, pVCpu->cpum.GstCtx.eip) && !(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_TF))
                    LogIt(0, LOG_GROUP_PATM, ("Patch code interrupted at %RRv for reason %Rrc\n", (RTRCPTR)CPUMGetGuestEIP(pVCpu), rc));
                break;
        }
        /*
         * Let's go paranoid!
         */
        if (    !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL)
            &&  PGMMapHasConflicts(pVM))
        {
            PGMMapCheck(pVM);
            AssertMsgFailed(("We should not get conflicts any longer!!! rc=%Rrc\n", rc));
            return VERR_EM_UNEXPECTED_MAPPING_CONFLICT;
        }
#endif /* VBOX_STRICT */

        /*
         * Process the returned status code.
         */
        if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
        {
            STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTail, d);
            break;
        }
        rc = emR3RawHandleRC(pVM, pVCpu, rc);
        if (rc != VINF_SUCCESS)
        {
            rc = emR3RawUpdateForceFlag(pVM, pVCpu, rc);
            if (rc != VINF_SUCCESS)
            {
                STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTail, d);
                break;
            }
        }

        /*
         * Check and execute forced actions.
         */
#ifdef VBOX_HIGH_RES_TIMERS_HACK
        TMTimerPollVoid(pVM, pVCpu);
#endif
        STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTail, d);
        if (    VM_FF_IS_ANY_SET(pVM, ~VM_FF_HIGH_PRIORITY_PRE_RAW_MASK | VM_FF_PGM_NO_MEMORY)
            ||  VMCPU_FF_IS_ANY_SET(pVCpu, ~VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
        {
            Assert(pVCpu->cpum.GstCtx.eflags.Bits.u1VM || (pVCpu->cpum.GstCtx.ss.Sel & X86_SEL_RPL) != (EMIsRawRing1Enabled(pVM) ? 2U : 1U));

            STAM_REL_PROFILE_ADV_SUSPEND(&pVCpu->em.s.StatRAWTotal, a);
            rc = emR3ForcedActions(pVM, pVCpu, rc);
            VBOXVMM_EM_FF_ALL_RET(pVCpu, rc);
            STAM_REL_PROFILE_ADV_RESUME(&pVCpu->em.s.StatRAWTotal, a);
            if (    rc != VINF_SUCCESS
                &&  rc != VINF_EM_RESCHEDULE_RAW)
            {
                rc = emR3RawUpdateForceFlag(pVM, pVCpu, rc);
                if (rc != VINF_SUCCESS)
                {
                    *pfFFDone = true;
                    break;
                }
            }
        }
    }

    /*
     * Return to outer loop.
     */
#if defined(LOG_ENABLED) && defined(DEBUG)
    RTLogFlush(NULL);
#endif
    STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTotal, a);
    return rc;
}