summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-server/Performance.cpp
blob: 153ca4e36185568aab3d0dba339c935473912c5c (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
/* $Id: Performance.cpp $ */
/** @file
 * VBox Performance Classes implementation.
 */

/*
 * Copyright (C) 2008-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
 */

/**
 * @todo list:
 *
 * 1) Detection of erroneous metric names
 */

#define LOG_GROUP LOG_GROUP_MAIN_PERFORMANCECOLLECTOR
#ifndef VBOX_COLLECTOR_TEST_CASE
# include "VirtualBoxImpl.h"
# include "MachineImpl.h"
# include "MediumImpl.h"
# include "AutoCaller.h"
#endif
#include "Performance.h"
#include "HostNetworkInterfaceImpl.h"
#include "netif.h"

#include <VBox/com/array.h>
#include <VBox/com/ptr.h>
#include <VBox/com/string.h>
#include <iprt/errcore.h>
#include <iprt/string.h>
#include <iprt/mem.h>
#include <iprt/cpuset.h>

#include <algorithm>

#include "LoggingNew.h"

using namespace pm;

// Stubs for non-pure virtual methods

int CollectorHAL::getHostCpuLoad(ULONG * /* user */, ULONG * /* kernel */, ULONG * /* idle */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getProcessCpuLoad(RTPROCESS  /* process */, ULONG * /* user */, ULONG * /* kernel */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getRawHostCpuLoad(uint64_t * /* user */, uint64_t * /* kernel */, uint64_t * /* idle */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getRawHostNetworkLoad(const char * /* name */, uint64_t * /* rx */, uint64_t * /* tx */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getRawHostDiskLoad(const char * /* name */, uint64_t * /* disk_ms */, uint64_t * /* total_ms */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getRawProcessCpuLoad(RTPROCESS  /* process */, uint64_t * /* user */,
                                       uint64_t * /* kernel */, uint64_t * /* total */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getHostMemoryUsage(ULONG * /* total */, ULONG * /* used */, ULONG * /* available */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getHostFilesystemUsage(const char * /* name */, ULONG * /* total */, ULONG * /* used */,
                                         ULONG * /* available */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getHostDiskSize(const char * /* name */, uint64_t * /* size */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getProcessMemoryUsage(RTPROCESS /* process */, ULONG * /* used */)
{
    return VERR_NOT_IMPLEMENTED;
}

int CollectorHAL::getDiskListByFs(const char * /* name */, DiskList& /* listUsage */, DiskList& /* listLoad */)
{
    return VERR_NOT_IMPLEMENTED;
}

/* Generic implementations */

int CollectorHAL::getHostCpuMHz(ULONG *mhz)
{
    unsigned cCpus = 0;
    uint64_t u64TotalMHz = 0;
    RTCPUSET OnlineSet;
    RTMpGetOnlineSet(&OnlineSet);
    for (int iCpu = 0; iCpu < RTCPUSET_MAX_CPUS; iCpu++)
    {
        Log7Func(("{%p}: Checking if CPU %d is member of online set...\n", this, (int)iCpu));
        if (RTCpuSetIsMemberByIndex(&OnlineSet, iCpu))
        {
            Log7Func(("{%p}: Getting frequency for CPU %d...\n", this, (int)iCpu));
            uint32_t uMHz = RTMpGetCurFrequency(RTMpCpuIdFromSetIndex(iCpu));
            if (uMHz != 0)
            {
                Log7Func(("{%p}: CPU %d %u MHz\n", this, (int)iCpu, uMHz));
                u64TotalMHz += uMHz;
                cCpus++;
            }
        }
    }

    if (cCpus)
    {
        *mhz = (ULONG)(u64TotalMHz / cCpus);
        return VINF_SUCCESS;
    }

    /* This is always the case on darwin, so don't assert there. */
#ifndef RT_OS_DARWIN
    AssertFailed();
#endif
    *mhz = 0;
    return VERR_NOT_IMPLEMENTED;
}

#ifndef VBOX_COLLECTOR_TEST_CASE

CollectorGuestQueue::CollectorGuestQueue()
{
    mEvent = NIL_RTSEMEVENT;
    RTSemEventCreate(&mEvent);
}

CollectorGuestQueue::~CollectorGuestQueue()
{
    RTSemEventDestroy(mEvent);
}

void CollectorGuestQueue::push(CollectorGuestRequest* rq)
{
    RTCLock lock(mLockMtx);

    mQueue.push(rq);
    RTSemEventSignal(mEvent);
}

CollectorGuestRequest* CollectorGuestQueue::pop()
{
    int vrc = VINF_SUCCESS;
    CollectorGuestRequest *rq = NULL;

    do
    {
        {
            RTCLock lock(mLockMtx);

            if (!mQueue.empty())
            {
                rq = mQueue.front();
                mQueue.pop();
            }
        }

        if (rq)
            return rq;
        vrc = RTSemEventWaitNoResume(mEvent, RT_INDEFINITE_WAIT);
    } while (RT_SUCCESS(vrc));

    return NULL;
}

HRESULT CGRQEnable::execute()
{
    Assert(mCGuest);
    return mCGuest->enableInternal(mMask);
}

void CGRQEnable::debugPrint(void *aObject, const char *aFunction, const char *aText)
{
    NOREF(aObject);
    NOREF(aFunction);
    NOREF(aText);
    Log7((LOG_FN_FMT ": {%p}: CGRQEnable(mask=0x%x) %s\n", aObject, aFunction, mMask, aText));
}

HRESULT CGRQDisable::execute()
{
    Assert(mCGuest);
    return mCGuest->disableInternal(mMask);
}

void CGRQDisable::debugPrint(void *aObject, const char *aFunction, const char *aText)
{
    NOREF(aObject);
    NOREF(aFunction);
    NOREF(aText);
    Log7((LOG_FN_FMT ": {%p}: CGRQDisable(mask=0x%x) %s\n", aObject, aFunction, mMask, aText));
}

HRESULT CGRQAbort::execute()
{
    return E_ABORT;
}

void CGRQAbort::debugPrint(void *aObject, const char *aFunction, const char *aText)
{
    NOREF(aObject);
    NOREF(aFunction);
    NOREF(aText);
    Log7((LOG_FN_FMT ": {%p}: CGRQAbort %s\n", aObject, aFunction, aText));
}

CollectorGuest::CollectorGuest(Machine *machine, RTPROCESS process) :
    mUnregistered(false), mEnabled(false), mValid(false), mMachine(machine), mProcess(process),
    mCpuUser(0), mCpuKernel(0), mCpuIdle(0),
    mMemTotal(0), mMemFree(0), mMemBalloon(0), mMemShared(0), mMemCache(0), mPageTotal(0),
    mAllocVMM(0), mFreeVMM(0), mBalloonedVMM(0), mSharedVMM(0), mVmNetRx(0), mVmNetTx(0)
{
    Assert(mMachine);
    /* cannot use ComObjPtr<Machine> in Performance.h, do it manually */
    mMachine->AddRef();
}

CollectorGuest::~CollectorGuest()
{
    /* cannot use ComObjPtr<Machine> in Performance.h, do it manually */
    mMachine->Release();
    // Assert(!cEnabled); why?
}

HRESULT CollectorGuest::enableVMMStats(bool mCollectVMMStats)
{
    HRESULT hrc = S_OK;

    if (mGuest)
    {
        /** @todo replace this with a direct call to mGuest in trunk! */
        AutoCaller autoCaller(mMachine);
        if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

        ComPtr<IInternalSessionControl> directControl;

        hrc = mMachine->i_getDirectControl(&directControl);
        if (hrc != S_OK)
            return hrc;

        /* enable statistics collection; this is a remote call (!) */
        hrc = directControl->EnableVMMStatistics(mCollectVMMStats);
        Log7Func(("{%p}: %sable VMM stats (%s)\n",
                  this, mCollectVMMStats ? "En" : "Dis", SUCCEEDED(hrc) ? "success" : "failed"));
    }

    return hrc;
}

HRESULT CollectorGuest::enable(ULONG mask)
{
    return enqueueRequest(new CGRQEnable(mask));
}

HRESULT CollectorGuest::disable(ULONG mask)
{
    return enqueueRequest(new CGRQDisable(mask));
}

HRESULT CollectorGuest::enableInternal(ULONG mask)
{
    HRESULT ret = S_OK;

    if ((mEnabled & mask) == mask)
        return E_UNEXPECTED;

    if (!mEnabled)
    {
        /* Must make sure that the machine object does not get uninitialized
         * in the middle of enabling this collector. Causes timing-related
         * behavior otherwise, which we don't want. In particular the
         * GetRemoteConsole call below can hang if the VM didn't completely
         * terminate (the VM processes stop processing events shortly before
         * closing the session). This avoids the hang. */
        AutoCaller autoCaller(mMachine);
        if (FAILED(autoCaller.hrc())) return autoCaller.hrc();

        mMachineName = mMachine->i_getName();

        ComPtr<IInternalSessionControl> directControl;

        ret = mMachine->i_getDirectControl(&directControl);
        if (ret != S_OK)
            return ret;

        /* get the associated console; this is a remote call (!) */
        ret = directControl->COMGETTER(RemoteConsole)(mConsole.asOutParam());
        if (ret != S_OK)
            return ret;

        ret = mConsole->COMGETTER(Guest)(mGuest.asOutParam());
        if (ret == S_OK)
        {
            ret = mGuest->COMSETTER(StatisticsUpdateInterval)(1 /* 1 sec */);
            Log7Func(("{%p}: Set guest statistics update interval to 1 sec (%s)\n",
                  this, SUCCEEDED(ret) ? "success" : "failed"));
        }
    }
    if ((mask & VMSTATS_VMM_RAM) == VMSTATS_VMM_RAM)
        enableVMMStats(true);
    mEnabled |= mask;

    return ret;
}

HRESULT CollectorGuest::disableInternal(ULONG mask)
{
    if (!(mEnabled & mask))
        return E_UNEXPECTED;

    if ((mask & VMSTATS_VMM_RAM) == VMSTATS_VMM_RAM)
        enableVMMStats(false);
    mEnabled &= ~mask;
    if (!mEnabled)
    {
        Assert(mGuest && mConsole);
        HRESULT ret = mGuest->COMSETTER(StatisticsUpdateInterval)(0 /* off */);
        NOREF(ret);
        Log7Func(("{%p}: Set guest statistics update interval to 0 sec (%s)\n",
              this, SUCCEEDED(ret) ? "success" : "failed"));
        invalidate(VMSTATS_ALL);
    }

    return S_OK;
}

HRESULT CollectorGuest::enqueueRequest(CollectorGuestRequest *aRequest)
{
    if (mManager)
    {
        aRequest->setGuest(this);
        return mManager->enqueueRequest(aRequest);
    }

    Log7Func(("{%p}: Attempted enqueue guest request when mManager is null\n", this));
    return E_POINTER;
}

void CollectorGuest::updateStats(ULONG aValidStats, ULONG aCpuUser,
                                 ULONG aCpuKernel, ULONG aCpuIdle,
                                 ULONG aMemTotal, ULONG aMemFree,
                                 ULONG aMemBalloon, ULONG aMemShared,
                                 ULONG aMemCache, ULONG aPageTotal,
                                 ULONG aAllocVMM, ULONG aFreeVMM,
                                 ULONG aBalloonedVMM, ULONG aSharedVMM,
                                 ULONG aVmNetRx, ULONG aVmNetTx)
{
    if ((aValidStats & VMSTATS_GUEST_CPULOAD) == VMSTATS_GUEST_CPULOAD)
    {
        mCpuUser   = aCpuUser;
        mCpuKernel = aCpuKernel,
        mCpuIdle   = aCpuIdle;
    }
    if ((aValidStats & VMSTATS_GUEST_RAMUSAGE) == VMSTATS_GUEST_RAMUSAGE)
    {
        mMemTotal   = aMemTotal;
        mMemFree    = aMemFree;
        mMemBalloon = aMemBalloon;
        mMemShared  = aMemShared;
        mMemCache   = aMemCache;
        mPageTotal  = aPageTotal;
    }
    if ((aValidStats & VMSTATS_VMM_RAM) == VMSTATS_VMM_RAM)
    {
        mAllocVMM     = aAllocVMM;
        mFreeVMM      = aFreeVMM;
        mBalloonedVMM = aBalloonedVMM;
        mSharedVMM    = aSharedVMM;
    }
    if ((aValidStats & VMSTATS_NET_RATE) == VMSTATS_NET_RATE)
    {
        mVmNetRx = aVmNetRx;
        mVmNetTx = aVmNetTx;
    }
    mValid = aValidStats;
}

CollectorGuestManager::CollectorGuestManager()
  : mVMMStatsProvider(NULL), mGuestBeingCalled(NULL)
{
    int vrc = RTThreadCreate(&mThread, CollectorGuestManager::requestProcessingThread,
                            this, 0, RTTHREADTYPE_MAIN_WORKER, RTTHREADFLAGS_WAITABLE,
                            "CGMgr");
    NOREF(vrc);
    Log7Func(("{%p}: RTThreadCreate returned %Rrc (mThread=%p)\n", this, vrc, mThread));
}

CollectorGuestManager::~CollectorGuestManager()
{
    Assert(mGuests.size() == 0);
    HRESULT hrc = enqueueRequest(new CGRQAbort());
    if (SUCCEEDED(hrc))
    {
        /* We wait only if we were able to put the abort request to a queue */
        Log7Func(("{%p}: Waiting for CGM request processing thread to stop...\n", this));
        int vrcThread = VINF_SUCCESS;
        int vrc = RTThreadWait(mThread, 1000 /* 1 sec */, &vrcThread);
        Log7Func(("{%p}: RTThreadWait returned %Rrc (thread exit code: %Rrc)\n", this, vrc, vrcThread));
        RT_NOREF(vrc);
    }
}

void CollectorGuestManager::registerGuest(CollectorGuest* pGuest)
{
    pGuest->setManager(this);
    mGuests.push_back(pGuest);
    /*
     * If no VMM stats provider was elected previously than this is our
     * candidate.
     */
    if (!mVMMStatsProvider)
        mVMMStatsProvider = pGuest;
    Log7Func(("{%p}: Registered guest=%p provider=%p\n", this, pGuest, mVMMStatsProvider));
}

void CollectorGuestManager::unregisterGuest(CollectorGuest* pGuest)
{
    Log7Func(("{%p}: About to unregister guest=%p provider=%p\n", this, pGuest, mVMMStatsProvider));
    //mGuests.remove(pGuest); => destroyUnregistered()
    pGuest->unregister();
    if (pGuest == mVMMStatsProvider)
    {
        /* This was our VMM stats provider, it is time to re-elect */
        CollectorGuestList::iterator it;
        /* Assume that nobody can provide VMM stats */
        mVMMStatsProvider = NULL;

        for (it = mGuests.begin(); it != mGuests.end(); ++it)
        {
            /* Skip unregistered as they are about to be destroyed */
            if ((*it)->isUnregistered())
                continue;

            if ((*it)->isEnabled())
            {
                /* Found the guest already collecting stats, elect it */
                mVMMStatsProvider = *it;
                HRESULT hrc = mVMMStatsProvider->enqueueRequest(new CGRQEnable(VMSTATS_VMM_RAM));
                if (FAILED(hrc))
                {
                    /* This is not a good candidate -- try to find another */
                    mVMMStatsProvider = NULL;
                    continue;
                }
                break;
            }
        }
        if (!mVMMStatsProvider)
        {
            /* If nobody collects stats, take the first registered */
            for (it = mGuests.begin(); it != mGuests.end(); ++it)
            {
                /* Skip unregistered as they are about to be destroyed */
                if ((*it)->isUnregistered())
                    continue;

                mVMMStatsProvider = *it;
                //mVMMStatsProvider->enable(VMSTATS_VMM_RAM);
                HRESULT hrc = mVMMStatsProvider->enqueueRequest(new CGRQEnable(VMSTATS_VMM_RAM));
                if (SUCCEEDED(hrc))
                    break;
                /* This was not a good candidate -- try to find another */
                mVMMStatsProvider = NULL;
            }
        }
    }
    Log7Func(("[%p}: LEAVE new provider=%p\n", this, mVMMStatsProvider));
}

void CollectorGuestManager::destroyUnregistered()
{
    CollectorGuestList::iterator it;

    for (it = mGuests.begin(); it != mGuests.end();)
        if ((*it)->isUnregistered())
        {
            delete *it;
            it = mGuests.erase(it);
            Log7Func(("{%p}: Number of guests after erasing unregistered is %d\n",
                     this, mGuests.size()));
        }
        else
            ++it;
}

HRESULT CollectorGuestManager::enqueueRequest(CollectorGuestRequest *aRequest)
{
#ifdef DEBUG
    aRequest->debugPrint(this, __PRETTY_FUNCTION__, "added to CGM queue");
#endif /* DEBUG */
    /*
     * It is very unlikely that we will get high frequency calls to configure
     * guest metrics collection, so we rely on this fact to detect blocked
     * guests. If the guest has not finished processing the previous request
     * after half a second we consider it blocked.
     */
    if (aRequest->getGuest() && aRequest->getGuest() == mGuestBeingCalled)
    {
        /*
         * Before we can declare a guest blocked we need to wait for a while
         * and then check again as it may never had a chance to process
         * the previous request. Half a second is an eternity for processes
         * and is barely noticable by humans.
         */
        Log7Func(("{%p}: Suspecting %s is stalled. Waiting for .5 sec...\n",
              this, aRequest->getGuest()->getVMName().c_str()));
        RTThreadSleep(500 /* ms */);
        if (aRequest->getGuest() == mGuestBeingCalled) {
            Log7Func(("{%p}: Request processing stalled for %s\n",
                     this, aRequest->getGuest()->getVMName().c_str()));
            /* Request execution got stalled for this guest -- report an error */
            return E_FAIL;
        }
    }
    mQueue.push(aRequest);
    return S_OK;
}

/* static */
DECLCALLBACK(int) CollectorGuestManager::requestProcessingThread(RTTHREAD /* aThread */, void *pvUser)
{
    CollectorGuestRequest *pReq;
    CollectorGuestManager *mgr = static_cast<CollectorGuestManager*>(pvUser);

    HRESULT hrc = S_OK;

    Log7Func(("{%p}: Starting request processing loop...\n", mgr));
    while ((pReq = mgr->mQueue.pop()) != NULL)
    {
#ifdef DEBUG
        pReq->debugPrint(mgr, __PRETTY_FUNCTION__, "is being executed...");
#endif /* DEBUG */
        mgr->mGuestBeingCalled = pReq->getGuest();
        hrc = pReq->execute();
        mgr->mGuestBeingCalled = NULL;
        delete pReq;
        if (hrc == E_ABORT)
            break;
        if (FAILED(hrc))
            Log7Func(("{%p}: request::execute returned %Rhrc\n", mgr, hrc));
    }
    Log7Func(("{%p}: Exiting request processing loop... hrc=%Rhrc\n", mgr, hrc));

    return VINF_SUCCESS;
}


#endif /* !VBOX_COLLECTOR_TEST_CASE */

bool BaseMetric::collectorBeat(uint64_t nowAt)
{
    if (isEnabled())
    {
        if (mLastSampleTaken == 0)
        {
            mLastSampleTaken = nowAt;
            Log4Func(("{%p}: Collecting %s for obj(%p)...\n",
                      this, getName(), (void *)mObject));
            return true;
        }
        /*
         * We use low resolution timers which may fire just a little bit early.
         * We compensate for that by jumping into the future by several
         * milliseconds (see @bugref{6345}).
         */
        if (nowAt - mLastSampleTaken + PM_SAMPLER_PRECISION_MS >= mPeriod * 1000)
        {
            /*
             * We don't want the beat to drift. This is why the timestamp of
             * the last taken sample is not the actual time but the time we
             * should have taken the measurement at.
             */
            mLastSampleTaken += mPeriod * 1000;
            Log4Func(("{%p}: Collecting %s for obj(%p)...\n",
                        this, getName(), (void *)mObject));
            return true;
        }
        Log4Func(("{%p}: Enabled but too early to collect %s for obj(%p)\n",
                 this, getName(), (void *)mObject));
    }
    return false;
}

void HostCpuLoad::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mUser->init(mLength);
    mKernel->init(mLength);
    mIdle->init(mLength);
}

void HostCpuLoad::collect()
{
    ULONG user, kernel, idle;
    int vrc = mHAL->getHostCpuLoad(&user, &kernel, &idle);
    if (RT_SUCCESS(vrc))
    {
        mUser->put(user);
        mKernel->put(kernel);
        mIdle->put(idle);
    }
}

void HostCpuLoadRaw::init(ULONG period, ULONG length)
{
    HostCpuLoad::init(period, length);
    mHAL->getRawHostCpuLoad(&mUserPrev, &mKernelPrev, &mIdlePrev);
}

void HostCpuLoadRaw::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectHostCpuLoad();
}

void HostCpuLoadRaw::collect()
{
    uint64_t user, kernel, idle;
    uint64_t userDiff, kernelDiff, idleDiff, totalDiff;

    int vrc = mHAL->getRawHostCpuLoad(&user, &kernel, &idle);
    if (RT_SUCCESS(vrc))
    {
        userDiff   = user   - mUserPrev;
        kernelDiff = kernel - mKernelPrev;
        idleDiff   = idle   - mIdlePrev;
        totalDiff  = userDiff + kernelDiff + idleDiff;

        if (totalDiff == 0)
        {
            /* This is only possible if none of counters has changed! */
            LogFlowThisFunc(("Impossible! User, kernel and idle raw "
                "counters has not changed since last sample.\n" ));
            mUser->put(0);
            mKernel->put(0);
            mIdle->put(0);
        }
        else
        {
            mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * userDiff / totalDiff));
            mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * kernelDiff / totalDiff));
            mIdle->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * idleDiff / totalDiff));
        }

        mUserPrev   = user;
        mKernelPrev = kernel;
        mIdlePrev   = idle;
    }
}

#ifndef VBOX_COLLECTOR_TEST_CASE
static bool getLinkSpeed(const char *szShortName, uint32_t *pSpeed)
{
# ifdef VBOX_WITH_HOSTNETIF_API
    NETIFSTATUS enmState = NETIF_S_UNKNOWN;
    int vrc = NetIfGetState(szShortName, &enmState);
    if (RT_FAILURE(vrc))
        return false;
    if (enmState != NETIF_S_UP)
        *pSpeed = 0;
    else
    {
        vrc = NetIfGetLinkSpeed(szShortName, pSpeed);
        if (RT_FAILURE(vrc))
            return false;
    }
    return true;
# else  /* !VBOX_WITH_HOSTNETIF_API */
    RT_NOREF(szShortName, pSpeed);
    return false;
# endif /* VBOX_WITH_HOSTNETIF_API */
}

void HostNetworkSpeed::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mLinkSpeed->init(length);
    /*
     * Retrieve the link speed now as it may be wrong if the metric was
     * registered at boot (see @bugref{6613}).
     */
    getLinkSpeed(mShortName.c_str(), &mSpeed);
}

void HostNetworkLoadRaw::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mRx->init(mLength);
    mTx->init(mLength);
    /*
     * Retrieve the link speed now as it may be wrong if the metric was
     * registered at boot (see @bugref{6613}).
     */
    uint32_t uSpeedMbit = 65535;
    if (getLinkSpeed(mShortName.c_str(), &uSpeedMbit))
        mSpeed = (uint64_t)uSpeedMbit * (1000000/8); /* Convert to bytes/sec */
    /*int vrc =*/ mHAL->getRawHostNetworkLoad(mShortName.c_str(), &mRxPrev, &mTxPrev);
    //AssertRC(vrc);
}

void HostNetworkLoadRaw::preCollect(CollectorHints& /* hints */, uint64_t /* iTick */)
{
    if (RT_FAILURE(mRc))
    {
        ComPtr<IHostNetworkInterface> networkInterface;
        ComPtr<IHost> host = getObject();
        HRESULT hrc = host->FindHostNetworkInterfaceByName(com::Bstr(mInterfaceName).raw(), networkInterface.asOutParam());
        if (SUCCEEDED(hrc))
        {
            static uint32_t s_tsLogRelLast;
            uint32_t tsNow = RTTimeProgramSecTS();
            if (   tsNow < RT_SEC_1HOUR
                || (tsNow - s_tsLogRelLast >= 60))
            {
                s_tsLogRelLast = tsNow;
                LogRel(("Failed to collect network metrics for %s: %Rrc (%d). Max one msg/min.\n", mInterfaceName.c_str(), mRc, mRc));
            }
            mRc = VINF_SUCCESS;
        }
    }
}

void HostNetworkLoadRaw::collect()
{
    uint64_t rx = mRxPrev;
    uint64_t tx = mTxPrev;

    if (RT_UNLIKELY(mSpeed * getPeriod() == 0))
    {
        LogFlowThisFunc(("Check cable for %s! speed=%llu period=%d.\n", mShortName.c_str(), mSpeed, getPeriod()));
        /* We do not collect host network metrics for unplugged interfaces! */
        return;
    }
    mRc = mHAL->getRawHostNetworkLoad(mShortName.c_str(), &rx, &tx);
    if (RT_SUCCESS(mRc))
    {
        uint64_t rxDiff = rx - mRxPrev;
        uint64_t txDiff = tx - mTxPrev;

        mRx->put((ULONG)(PM_NETWORK_LOAD_MULTIPLIER * rxDiff / (mSpeed * getPeriod())));
        mTx->put((ULONG)(PM_NETWORK_LOAD_MULTIPLIER * txDiff / (mSpeed * getPeriod())));

        mRxPrev = rx;
        mTxPrev = tx;
    }
    else
        LogFlowThisFunc(("Failed to collect data: %Rrc (%d)."
                         " Will update the list of interfaces...\n", mRc,mRc));
}
#endif /* !VBOX_COLLECTOR_TEST_CASE */

void HostDiskLoadRaw::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mUtil->init(mLength);
    int vrc = mHAL->getRawHostDiskLoad(mDiskName.c_str(), &mDiskPrev, &mTotalPrev);
    AssertRC(vrc);
}

void HostDiskLoadRaw::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectHostCpuLoad();
}

void HostDiskLoadRaw::collect()
{
    uint64_t disk, total;

    int vrc = mHAL->getRawHostDiskLoad(mDiskName.c_str(), &disk, &total);
    if (RT_SUCCESS(vrc))
    {
        uint64_t diskDiff = disk - mDiskPrev;
        uint64_t totalDiff = total - mTotalPrev;

        if (RT_UNLIKELY(totalDiff == 0))
        {
            Assert(totalDiff);
            LogFlowThisFunc(("Improbable! Less than millisecond passed! Disk=%s\n", mDiskName.c_str()));
            mUtil->put(0);
        }
        else if (diskDiff > totalDiff)
        {
            /*
             * It is possible that the disk spent more time than CPU because
             * CPU measurements are taken during the pre-collect phase. We try
             * to compensate for than by adding the extra to the next round of
             * measurements.
             */
            mUtil->put(PM_NETWORK_LOAD_MULTIPLIER);
            Assert((diskDiff - totalDiff) < mPeriod * 1000);
            if ((diskDiff - totalDiff) > mPeriod * 1000)
            {
                LogRel(("Disk utilization time exceeds CPU time by more"
                        " than the collection period (%llu ms)\n", diskDiff - totalDiff));
            }
            else
            {
                disk = mDiskPrev + totalDiff;
                LogFlowThisFunc(("Moved %u milliseconds to the next period.\n", (unsigned)(diskDiff - totalDiff)));
            }
        }
        else
        {
            mUtil->put((ULONG)(PM_NETWORK_LOAD_MULTIPLIER * diskDiff / totalDiff));
        }

        mDiskPrev = disk;
        mTotalPrev = total;
    }
    else
        LogFlowThisFunc(("Failed to collect data: %Rrc (%d)\n", vrc, vrc));
}

void HostCpuMhz::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mMHz->init(mLength);
}

void HostCpuMhz::collect()
{
    ULONG mhz;
    int vrc = mHAL->getHostCpuMHz(&mhz);
    if (RT_SUCCESS(vrc))
        mMHz->put(mhz);
}

void HostRamUsage::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mTotal->init(mLength);
    mUsed->init(mLength);
    mAvailable->init(mLength);
}

void HostRamUsage::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectHostRamUsage();
}

void HostRamUsage::collect()
{
    ULONG total, used, available;
    int vrc = mHAL->getHostMemoryUsage(&total, &used, &available);
    if (RT_SUCCESS(vrc))
    {
        mTotal->put(total);
        mUsed->put(used);
        mAvailable->put(available);
    }
}

void HostFilesystemUsage::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mTotal->init(mLength);
    mUsed->init(mLength);
    mAvailable->init(mLength);
}

void HostFilesystemUsage::preCollect(CollectorHints& /* hints */, uint64_t /* iTick */)
{
}

void HostFilesystemUsage::collect()
{
    ULONG total, used, available;
    int vrc = mHAL->getHostFilesystemUsage(mFsName.c_str(), &total, &used, &available);
    if (RT_SUCCESS(vrc))
    {
        mTotal->put(total);
        mUsed->put(used);
        mAvailable->put(available);
    }
}

void HostDiskUsage::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mTotal->init(mLength);
}

void HostDiskUsage::preCollect(CollectorHints& /* hints */, uint64_t /* iTick */)
{
}

void HostDiskUsage::collect()
{
    uint64_t total;
    int vrc = mHAL->getHostDiskSize(mDiskName.c_str(), &total);
    if (RT_SUCCESS(vrc))
        mTotal->put((ULONG)(total / _1M));
}

#ifndef VBOX_COLLECTOR_TEST_CASE

void HostRamVmm::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mAllocVMM->init(mLength);
    mFreeVMM->init(mLength);
    mBalloonVMM->init(mLength);
    mSharedVMM->init(mLength);
}

HRESULT HostRamVmm::enable()
{
    HRESULT hrc = S_OK;
    CollectorGuest *provider = mCollectorGuestManager->getVMMStatsProvider();
    if (provider)
        hrc = provider->enable(VMSTATS_VMM_RAM);
    BaseMetric::enable();
    return hrc;
}

HRESULT HostRamVmm::disable()
{
    HRESULT hrc = S_OK;
    BaseMetric::disable();
    CollectorGuest *provider = mCollectorGuestManager->getVMMStatsProvider();
    if (provider)
        hrc = provider->disable(VMSTATS_VMM_RAM);
    return hrc;
}

void HostRamVmm::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectHostRamVmm();
}

void HostRamVmm::collect()
{
    CollectorGuest *provider = mCollectorGuestManager->getVMMStatsProvider();
    if (provider)
    {
        Log7Func(("{%p}: provider=%p enabled=%RTbool valid=%RTbool...\n",
              this, provider, provider->isEnabled(), provider->isValid(VMSTATS_VMM_RAM) ));
        if (provider->isValid(VMSTATS_VMM_RAM))
        {
            /* Provider is ready, get updated stats */
            mAllocCurrent     = provider->getAllocVMM();
            mFreeCurrent      = provider->getFreeVMM();
            mBalloonedCurrent = provider->getBalloonedVMM();
            mSharedCurrent    = provider->getSharedVMM();
            provider->invalidate(VMSTATS_VMM_RAM);
        }
        /*
         * Note that if there are no new values from the provider we will use
         * the ones most recently provided instead of zeros, which is probably
         * a desirable behavior.
         */
    }
    else
    {
        mAllocCurrent     = 0;
        mFreeCurrent      = 0;
        mBalloonedCurrent = 0;
        mSharedCurrent    = 0;
    }
    Log7Func(("{%p}: mAllocCurrent=%u mFreeCurrent=%u mBalloonedCurrent=%u mSharedCurrent=%u\n",
             this, mAllocCurrent, mFreeCurrent, mBalloonedCurrent, mSharedCurrent));
    mAllocVMM->put(mAllocCurrent);
    mFreeVMM->put(mFreeCurrent);
    mBalloonVMM->put(mBalloonedCurrent);
    mSharedVMM->put(mSharedCurrent);
}

#endif /* !VBOX_COLLECTOR_TEST_CASE */



void MachineCpuLoad::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mUser->init(mLength);
    mKernel->init(mLength);
}

void MachineCpuLoad::collect()
{
    ULONG user, kernel;
    int vrc = mHAL->getProcessCpuLoad(mProcess, &user, &kernel);
    if (RT_SUCCESS(vrc))
    {
        mUser->put(user);
        mKernel->put(kernel);
    }
}

void MachineCpuLoadRaw::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectProcessCpuLoad(mProcess);
}

void MachineCpuLoadRaw::collect()
{
    uint64_t processUser, processKernel, hostTotal;

    int vrc = mHAL->getRawProcessCpuLoad(mProcess, &processUser, &processKernel, &hostTotal);
    if (RT_SUCCESS(vrc))
    {
        if (hostTotal == mHostTotalPrev)
        {
            /* Nearly impossible, but... */
            mUser->put(0);
            mKernel->put(0);
        }
        else
        {
            mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * (processUser - mProcessUserPrev) / (hostTotal - mHostTotalPrev)));
            mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * (processKernel - mProcessKernelPrev ) / (hostTotal - mHostTotalPrev)));
        }

        mHostTotalPrev     = hostTotal;
        mProcessUserPrev   = processUser;
        mProcessKernelPrev = processKernel;
    }
}

void MachineRamUsage::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mUsed->init(mLength);
}

void MachineRamUsage::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectProcessRamUsage(mProcess);
}

void MachineRamUsage::collect()
{
    ULONG used;
    int vrc = mHAL->getProcessMemoryUsage(mProcess, &used);
    if (RT_SUCCESS(vrc))
        mUsed->put(used);
}


#ifndef VBOX_COLLECTOR_TEST_CASE

void MachineDiskUsage::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;
    mUsed->init(mLength);
}

void MachineDiskUsage::preCollect(CollectorHints& /* hints */, uint64_t /* iTick */)
{
}

void MachineDiskUsage::collect()
{
    ULONG used = 0;

    for (MediaList::iterator it = mDisks.begin(); it != mDisks.end(); ++it)
    {
        ComObjPtr<Medium> pMedium = *it;

        /* just in case */
        AssertContinue(!pMedium.isNull());

        AutoCaller localAutoCaller(pMedium);
        if (FAILED(localAutoCaller.hrc())) continue;

        AutoReadLock local_alock(pMedium COMMA_LOCKVAL_SRC_POS);

        used += (ULONG)(pMedium->i_getSize() / _1M);
    }

    mUsed->put(used);
}

void MachineNetRate::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;

    mRx->init(mLength);
    mTx->init(mLength);
}

void MachineNetRate::collect()
{
    if (mCGuest->isValid(VMSTATS_NET_RATE))
    {
        mRx->put(mCGuest->getVmNetRx());
        mTx->put(mCGuest->getVmNetTx());
        mCGuest->invalidate(VMSTATS_NET_RATE);
    }
}

HRESULT MachineNetRate::enable()
{
    HRESULT hrc = mCGuest->enable(VMSTATS_NET_RATE);
    BaseMetric::enable();
    return hrc;
}

HRESULT MachineNetRate::disable()
{
    BaseMetric::disable();
    return mCGuest->disable(VMSTATS_NET_RATE);
}

void MachineNetRate::preCollect(CollectorHints& hints,  uint64_t /* iTick */)
{
    hints.collectGuestStats(mCGuest->getProcess());
}

void GuestCpuLoad::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;

    mUser->init(mLength);
    mKernel->init(mLength);
    mIdle->init(mLength);
}

void GuestCpuLoad::preCollect(CollectorHints& hints, uint64_t /* iTick */)
{
    hints.collectGuestStats(mCGuest->getProcess());
}

void GuestCpuLoad::collect()
{
    if (mCGuest->isValid(VMSTATS_GUEST_CPULOAD))
    {
        mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * mCGuest->getCpuUser()) / 100);
        mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * mCGuest->getCpuKernel()) / 100);
        mIdle->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * mCGuest->getCpuIdle()) / 100);
        mCGuest->invalidate(VMSTATS_GUEST_CPULOAD);
    }
}

HRESULT GuestCpuLoad::enable()
{
    HRESULT hrc = mCGuest->enable(VMSTATS_GUEST_CPULOAD);
    BaseMetric::enable();
    return hrc;
}

HRESULT GuestCpuLoad::disable()
{
    BaseMetric::disable();
    return mCGuest->disable(VMSTATS_GUEST_CPULOAD);
}

void GuestRamUsage::init(ULONG period, ULONG length)
{
    mPeriod = period;
    mLength = length;

    mTotal->init(mLength);
    mFree->init(mLength);
    mBallooned->init(mLength);
    mShared->init(mLength);
    mCache->init(mLength);
    mPagedTotal->init(mLength);
}

void GuestRamUsage::collect()
{
    if (mCGuest->isValid(VMSTATS_GUEST_RAMUSAGE))
    {
        mTotal->put(mCGuest->getMemTotal());
        mFree->put(mCGuest->getMemFree());
        mBallooned->put(mCGuest->getMemBalloon());
        mShared->put(mCGuest->getMemShared());
        mCache->put(mCGuest->getMemCache());
        mPagedTotal->put(mCGuest->getPageTotal());
        mCGuest->invalidate(VMSTATS_GUEST_RAMUSAGE);
    }
}

HRESULT GuestRamUsage::enable()
{
    HRESULT hrc = mCGuest->enable(VMSTATS_GUEST_RAMUSAGE);
    BaseMetric::enable();
    return hrc;
}

HRESULT GuestRamUsage::disable()
{
    BaseMetric::disable();
    return mCGuest->disable(VMSTATS_GUEST_RAMUSAGE);
}

void GuestRamUsage::preCollect(CollectorHints& hints,  uint64_t /* iTick */)
{
    hints.collectGuestStats(mCGuest->getProcess());
}

#endif /* !VBOX_COLLECTOR_TEST_CASE */

void CircularBuffer::init(ULONG ulLength)
{
    if (mData)
        RTMemFree(mData);
    mLength = ulLength;
    if (mLength)
        mData = (ULONG*)RTMemAllocZ(ulLength * sizeof(ULONG));
    else
        mData = NULL;
    mWrapped = false;
    mEnd = 0;
    mSequenceNumber = 0;
}

ULONG CircularBuffer::length()
{
    return mWrapped ? mLength : mEnd;
}

void CircularBuffer::put(ULONG value)
{
    if (mData)
    {
        mData[mEnd++] = value;
        if (mEnd >= mLength)
        {
            mEnd = 0;
            mWrapped = true;
        }
        ++mSequenceNumber;
    }
}

void CircularBuffer::copyTo(ULONG *data)
{
    if (mWrapped)
    {
        memcpy(data, mData + mEnd, (mLength - mEnd) * sizeof(ULONG));
        // Copy the wrapped part
        if (mEnd)
            memcpy(data + (mLength - mEnd), mData, mEnd * sizeof(ULONG));
    }
    else
        memcpy(data, mData, mEnd * sizeof(ULONG));
}

void SubMetric::query(ULONG *data)
{
    copyTo(data);
}

void Metric::query(ULONG **data, ULONG *count, ULONG *sequenceNumber)
{
    ULONG length;
    ULONG *tmpData;

    length = mSubMetric->length();
    *sequenceNumber = mSubMetric->getSequenceNumber() - length;
    if (length)
    {
        tmpData = (ULONG*)RTMemAlloc(sizeof(*tmpData)*length);
        mSubMetric->query(tmpData);
        if (mAggregate)
        {
            *count = 1;
            *data  = (ULONG*)RTMemAlloc(sizeof(**data));
            **data = mAggregate->compute(tmpData, length);
            RTMemFree(tmpData);
        }
        else
        {
            *count = length;
            *data  = tmpData;
        }
    }
    else
    {
        *count = 0;
        *data  = 0;
    }
}

ULONG AggregateAvg::compute(ULONG *data, ULONG length)
{
    uint64_t tmp = 0;
    for (ULONG i = 0; i < length; ++i)
        tmp += data[i];
    return (ULONG)(tmp / length);
}

const char * AggregateAvg::getName()
{
    return "avg";
}

ULONG AggregateMin::compute(ULONG *data, ULONG length)
{
    ULONG tmp = *data;
    for (ULONG i = 0; i < length; ++i)
        if (data[i] < tmp)
            tmp = data[i];
    return tmp;
}

const char * AggregateMin::getName()
{
    return "min";
}

ULONG AggregateMax::compute(ULONG *data, ULONG length)
{
    ULONG tmp = *data;
    for (ULONG i = 0; i < length; ++i)
        if (data[i] > tmp)
            tmp = data[i];
    return tmp;
}

const char * AggregateMax::getName()
{
    return "max";
}

Filter::Filter(const std::vector<com::Utf8Str> &metricNames,
               const std::vector<ComPtr<IUnknown> > &objects)
{
    if (!objects.size())
    {
        if (metricNames.size())
        {
            for (size_t i = 0; i < metricNames.size(); ++i)
                processMetricList(metricNames[i], ComPtr<IUnknown>());
        }
        else
            processMetricList("*", ComPtr<IUnknown>());
    }
    else
    {
        for (size_t i = 0; i < objects.size(); ++i)
            switch (metricNames.size())
            {
                case 0:
                    processMetricList("*", objects[i]);
                    break;
                case 1:
                    processMetricList(metricNames[0], objects[i]);
                    break;
                default:
                    processMetricList(metricNames[i], objects[i]);
                    break;
            }
    }
}

Filter::Filter(const com::Utf8Str &name, const ComPtr<IUnknown> &aObject)
{
    processMetricList(name, aObject);
}

void Filter::processMetricList(const com::Utf8Str &name, const ComPtr<IUnknown> object)
{
    size_t startPos = 0;

    for (size_t pos = name.find(",");
         pos != com::Utf8Str::npos;
         pos = name.find(",", startPos))
    {
        mElements.push_back(std::make_pair(object, RTCString(name.substr(startPos, pos - startPos).c_str())));
        startPos = pos + 1;
    }
    mElements.push_back(std::make_pair(object, RTCString(name.substr(startPos).c_str())));
}

/**
 * The following method was borrowed from stamR3Match (VMM/STAM.cpp) and
 * modified to handle the special case of trailing colon in the pattern.
 *
 * @returns True if matches, false if not.
 * @param   pszPat      Pattern.
 * @param   pszName     Name to match against the pattern.
 * @param   fSeenColon  Seen colon (':').
 */
bool Filter::patternMatch(const char *pszPat, const char *pszName,
                          bool fSeenColon)
{
    /* ASSUMES ASCII */
    for (;;)
    {
        char chPat = *pszPat;
        switch (chPat)
        {
            default:
                if (*pszName != chPat)
                    return false;
                break;

            case '*':
            {
                while ((chPat = *++pszPat) == '*' || chPat == '?')
                    /* nothing */;

                /* Handle a special case, the mask terminating with a colon. */
                if (chPat == ':')
                {
                    if (!fSeenColon && !pszPat[1])
                        return !strchr(pszName, ':');
                    fSeenColon = true;
                }

                for (;;)
                {
                    char ch = *pszName++;
                    if (    ch == chPat
                        &&  (   !chPat
                             || patternMatch(pszPat + 1, pszName, fSeenColon)))
                        return true;
                    if (!ch)
                        return false;
                }
                /* won't ever get here */
                break;
            }

            case '?':
                if (!*pszName)
                    return false;
                break;

            /* Handle a special case, the mask terminating with a colon. */
            case ':':
                if (!fSeenColon && !pszPat[1])
                    return !*pszName;
                if (*pszName != ':')
                    return false;
                fSeenColon = true;
                break;

            case '\0':
                return !*pszName;
        }
        pszName++;
        pszPat++;
    }
    /* not reached */
}

bool Filter::match(const ComPtr<IUnknown> object, const RTCString &name) const
{
    ElementList::const_iterator it;

    //Log7(("Filter::match(%p, %s)\n", static_cast<const IUnknown*> (object), name.c_str()));
    for (it = mElements.begin(); it != mElements.end(); ++it)
    {
        //Log7(("...matching against(%p, %s)\n", static_cast<const IUnknown*> ((*it).first), (*it).second.c_str()));
        if ((*it).first.isNull() || (*it).first == object)
        {
            // Objects match, compare names
            if (patternMatch((*it).second.c_str(), name.c_str()))
            {
                //LogFlowThisFunc(("...found!\n"));
                return true;
            }
        }
    }
    //Log7(("...no matches!\n"));
    return false;
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */