VirtualBox

source: vbox/trunk/src/VBox/Main/Performance.cpp@ 28012

Last change on this file since 28012 was 28012, checked in by vboxsync, 15 years ago

Use PGMR3QueryFreeMemory instead

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.2 KB
Line 
1/* $Id: Performance.cpp 28012 2010-04-06 14:52:25Z vboxsync $ */
2
3/** @file
4 *
5 * VBox Performance Classes implementation.
6 */
7
8/*
9 * Copyright (C) 2008 Sun Microsystems, Inc.
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.215389.xyz. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
20 * Clara, CA 95054 USA or visit http://www.sun.com if you need
21 * additional information or have any questions.
22 */
23
24/*
25 * @todo list:
26 *
27 * 1) Detection of erroneous metric names
28 */
29
30#ifndef VBOX_COLLECTOR_TEST_CASE
31#include "VirtualBoxImpl.h"
32#include "MachineImpl.h"
33#endif
34#include "Performance.h"
35
36#include <VBox/com/array.h>
37#include <VBox/com/ptr.h>
38#include <VBox/com/string.h>
39#include <VBox/err.h>
40#include <iprt/string.h>
41#include <iprt/mem.h>
42#include <iprt/cpuset.h>
43
44#include <algorithm>
45
46#include "Logging.h"
47
48using namespace pm;
49
50// Stubs for non-pure virtual methods
51
52int CollectorHAL::getHostCpuLoad(ULONG * /* user */, ULONG * /* kernel */, ULONG * /* idle */)
53{
54 return E_NOTIMPL;
55}
56
57int CollectorHAL::getProcessCpuLoad(RTPROCESS /* process */, ULONG * /* user */, ULONG * /* kernel */)
58{
59 return E_NOTIMPL;
60}
61
62int CollectorHAL::getRawHostCpuLoad(uint64_t * /* user */, uint64_t * /* kernel */, uint64_t * /* idle */)
63{
64 return E_NOTIMPL;
65}
66
67int CollectorHAL::getRawProcessCpuLoad(RTPROCESS /* process */, uint64_t * /* user */, uint64_t * /* kernel */, uint64_t * /* total */)
68{
69 return E_NOTIMPL;
70}
71
72int CollectorHAL::getHostMemoryUsage(ULONG * /* total */, ULONG * /* used */, ULONG * /* available */)
73{
74 return E_NOTIMPL;
75}
76
77int CollectorHAL::getProcessMemoryUsage(RTPROCESS /* process */, ULONG * /* used */)
78{
79 return E_NOTIMPL;
80}
81
82int CollectorHAL::enable()
83{
84 return E_NOTIMPL;
85}
86
87int CollectorHAL::disable()
88{
89 return E_NOTIMPL;
90}
91
92/* Generic implementations */
93
94int CollectorHAL::getHostCpuMHz(ULONG *mhz)
95{
96 unsigned cCpus = 0;
97 uint64_t u64TotalMHz = 0;
98 RTCPUSET OnlineSet;
99 RTMpGetOnlineSet(&OnlineSet);
100 for (RTCPUID iCpu = 0; iCpu < RTCPUSET_MAX_CPUS; iCpu++)
101 {
102 LogAleksey(("{%p} " LOG_FN_FMT ": Checking if CPU %d is member of online set...\n",
103 this, __PRETTY_FUNCTION__, (int)iCpu));
104 if (RTCpuSetIsMemberByIndex(&OnlineSet, iCpu))
105 {
106 LogAleksey(("{%p} " LOG_FN_FMT ": Getting frequency for CPU %d...\n",
107 this, __PRETTY_FUNCTION__, (int)iCpu));
108 uint32_t uMHz = RTMpGetCurFrequency(RTMpCpuIdFromSetIndex(iCpu));
109 if (uMHz != 0)
110 {
111 LogAleksey(("{%p} " LOG_FN_FMT ": CPU %d %u MHz\n",
112 this, __PRETTY_FUNCTION__, (int)iCpu, uMHz));
113 u64TotalMHz += uMHz;
114 cCpus++;
115 }
116 }
117 }
118
119 AssertReturn(cCpus, VERR_NOT_IMPLEMENTED);
120 *mhz = (ULONG)(u64TotalMHz / cCpus);
121
122 return VINF_SUCCESS;
123}
124
125#ifndef VBOX_COLLECTOR_TEST_CASE
126CollectorGuestHAL::~CollectorGuestHAL()
127{
128 Assert(!cEnabled);
129}
130
131int CollectorGuestHAL::enable()
132{
133 HRESULT ret = S_OK;
134
135 if (ASMAtomicIncU32(&cEnabled) == 1)
136 {
137 ComPtr<IInternalSessionControl> directControl;
138
139 ret = mMachine->getDirectControl(&directControl);
140 if (ret != S_OK)
141 return ret;
142
143 /* get the associated console; this is a remote call (!) */
144 ret = directControl->GetRemoteConsole(mConsole.asOutParam());
145 if (ret != S_OK)
146 return ret;
147
148 ret = mConsole->COMGETTER(Guest)(mGuest.asOutParam());
149 if (ret == S_OK)
150 mGuest->COMSETTER(StatisticsUpdateInterval)(1 /* 1 sec */);
151 }
152 return ret;
153}
154
155int CollectorGuestHAL::disable()
156{
157 if (ASMAtomicDecU32(&cEnabled) == 0)
158 {
159 Assert(mGuest && mConsole);
160 mGuest->COMSETTER(StatisticsUpdateInterval)(0 /* off */);
161 }
162 return S_OK;
163}
164
165int CollectorGuestHAL::preCollect(const CollectorHints& hints, uint64_t iTick)
166{
167 if ( mGuest
168 && iTick != mLastTick)
169 {
170 ULONG ulMemFreeTotal;
171
172 mGuest->InternalGetStatistics(&mCpuUser, &mCpuKernel, &mCpuIdle,
173 &mMemTotal, &mMemFree, &mMemBalloon, &mMemCache,
174 &mPageTotal, &ulMemFreeTotal);
175
176 if (mHostHAL)
177 mHostHAL->setMemFreeTotal(ulMemFreeTotal);
178
179 mLastTick = iTick;
180 }
181 return S_OK;
182}
183
184#endif /* VBOX_COLLECTOR_TEST_CASE */
185
186bool BaseMetric::collectorBeat(uint64_t nowAt)
187{
188 if (isEnabled())
189 {
190 if (nowAt - mLastSampleTaken >= mPeriod * 1000)
191 {
192 mLastSampleTaken = nowAt;
193 Log4(("{%p} " LOG_FN_FMT ": Collecting %s for obj(%p)...\n",
194 this, __PRETTY_FUNCTION__, getName(), (void *)mObject));
195 return true;
196 }
197 }
198 return false;
199}
200
201/*bool BaseMetric::associatedWith(ComPtr<IUnknown> object)
202{
203 LogFlowThisFunc(("mObject(%p) == object(%p) is %s.\n", mObject, object, mObject == object ? "true" : "false"));
204 return mObject == object;
205}*/
206
207void HostCpuLoad::init(ULONG period, ULONG length)
208{
209 mPeriod = period;
210 mLength = length;
211 mUser->init(mLength);
212 mKernel->init(mLength);
213 mIdle->init(mLength);
214}
215
216void HostCpuLoad::collect()
217{
218 ULONG user, kernel, idle;
219 int rc = mHAL->getHostCpuLoad(&user, &kernel, &idle);
220 if (RT_SUCCESS(rc))
221 {
222 mUser->put(user);
223 mKernel->put(kernel);
224 mIdle->put(idle);
225 }
226}
227
228void HostCpuLoadRaw::preCollect(CollectorHints& hints, uint64_t iTick)
229{
230 hints.collectHostCpuLoad();
231}
232
233void HostCpuLoadRaw::collect()
234{
235 uint64_t user, kernel, idle;
236 uint64_t userDiff, kernelDiff, idleDiff, totalDiff;
237
238 int rc = mHAL->getRawHostCpuLoad(&user, &kernel, &idle);
239 if (RT_SUCCESS(rc))
240 {
241 userDiff = user - mUserPrev;
242 kernelDiff = kernel - mKernelPrev;
243 idleDiff = idle - mIdlePrev;
244 totalDiff = userDiff + kernelDiff + idleDiff;
245
246 if (totalDiff == 0)
247 {
248 /* This is only possible if none of counters has changed! */
249 LogFlowThisFunc(("Impossible! User, kernel and idle raw "
250 "counters has not changed since last sample.\n" ));
251 mUser->put(0);
252 mKernel->put(0);
253 mIdle->put(0);
254 }
255 else
256 {
257 mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * userDiff / totalDiff));
258 mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * kernelDiff / totalDiff));
259 mIdle->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * idleDiff / totalDiff));
260 }
261
262 mUserPrev = user;
263 mKernelPrev = kernel;
264 mIdlePrev = idle;
265 }
266}
267
268void HostCpuMhz::init(ULONG period, ULONG length)
269{
270 mPeriod = period;
271 mLength = length;
272 mMHz->init(mLength);
273}
274
275void HostCpuMhz::collect()
276{
277 ULONG mhz;
278 int rc = mHAL->getHostCpuMHz(&mhz);
279 if (RT_SUCCESS(rc))
280 mMHz->put(mhz);
281}
282
283void HostRamUsage::init(ULONG period, ULONG length)
284{
285 mPeriod = period;
286 mLength = length;
287 mTotal->init(mLength);
288 mUsed->init(mLength);
289 mAvailable->init(mLength);
290}
291
292void HostRamUsage::preCollect(CollectorHints& hints, uint64_t iTick)
293{
294 hints.collectHostRamUsage();
295}
296
297void HostRamUsage::collect()
298{
299 ULONG total, used, available;
300 int rc = mHAL->getHostMemoryUsage(&total, &used, &available);
301 if (RT_SUCCESS(rc))
302 {
303 mTotal->put(total);
304 mUsed->put(used);
305 mAvailable->put(available + mHAL->getMemFreeTotal());
306 }
307}
308
309
310
311void MachineCpuLoad::init(ULONG period, ULONG length)
312{
313 mPeriod = period;
314 mLength = length;
315 mUser->init(mLength);
316 mKernel->init(mLength);
317}
318
319void MachineCpuLoad::collect()
320{
321 ULONG user, kernel;
322 int rc = mHAL->getProcessCpuLoad(mProcess, &user, &kernel);
323 if (RT_SUCCESS(rc))
324 {
325 mUser->put(user);
326 mKernel->put(kernel);
327 }
328}
329
330void MachineCpuLoadRaw::preCollect(CollectorHints& hints, uint64_t iTick)
331{
332 hints.collectProcessCpuLoad(mProcess);
333}
334
335void MachineCpuLoadRaw::collect()
336{
337 uint64_t processUser, processKernel, hostTotal;
338
339 int rc = mHAL->getRawProcessCpuLoad(mProcess, &processUser, &processKernel, &hostTotal);
340 if (RT_SUCCESS(rc))
341 {
342 if (hostTotal == mHostTotalPrev)
343 {
344 /* Nearly impossible, but... */
345 mUser->put(0);
346 mKernel->put(0);
347 }
348 else
349 {
350 mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * (processUser - mProcessUserPrev) / (hostTotal - mHostTotalPrev)));
351 mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * (processKernel - mProcessKernelPrev ) / (hostTotal - mHostTotalPrev)));
352 }
353
354 mHostTotalPrev = hostTotal;
355 mProcessUserPrev = processUser;
356 mProcessKernelPrev = processKernel;
357 }
358}
359
360void MachineRamUsage::init(ULONG period, ULONG length)
361{
362 mPeriod = period;
363 mLength = length;
364 mUsed->init(mLength);
365}
366
367void MachineRamUsage::preCollect(CollectorHints& hints, uint64_t iTick)
368{
369 hints.collectProcessRamUsage(mProcess);
370}
371
372void MachineRamUsage::collect()
373{
374 ULONG used;
375 int rc = mHAL->getProcessMemoryUsage(mProcess, &used);
376 if (RT_SUCCESS(rc))
377 mUsed->put(used);
378}
379
380
381void GuestCpuLoad::init(ULONG period, ULONG length)
382{
383 mPeriod = period;
384 mLength = length;
385
386 mUser->init(mLength);
387 mKernel->init(mLength);
388 mIdle->init(mLength);
389}
390
391void GuestCpuLoad::preCollect(CollectorHints& hints, uint64_t iTick)
392{
393 mHAL->preCollect(hints, iTick);
394}
395
396void GuestCpuLoad::collect()
397{
398 ULONG CpuUser = 0, CpuKernel = 0, CpuIdle = 0;
399
400 mGuestHAL->getGuestCpuLoad(&CpuUser, &CpuKernel, &CpuIdle);
401 mUser->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * CpuUser) / 100);
402 mKernel->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * CpuKernel) / 100);
403 mIdle->put((ULONG)(PM_CPU_LOAD_MULTIPLIER * CpuIdle) / 100);
404}
405
406void GuestRamUsage::init(ULONG period, ULONG length)
407{
408 mPeriod = period;
409 mLength = length;
410
411 mTotal->init(mLength);
412 mFree->init(mLength);
413 mBallooned->init(mLength);
414 mCache->init(mLength);
415 mPagedTotal->init(mLength);
416}
417
418void GuestRamUsage::preCollect(CollectorHints& hints, uint64_t iTick)
419{
420 mHAL->preCollect(hints, iTick);
421}
422
423void GuestRamUsage::collect()
424{
425 ULONG ulMemTotal = 0, ulMemFree = 0, ulMemBalloon = 0, ulMemCache = 0, ulPageTotal = 0;
426
427 mGuestHAL->getGuestMemLoad(&ulMemTotal, &ulMemFree, &ulMemBalloon, &ulMemCache, &ulPageTotal);
428 mTotal->put(ulMemTotal);
429 mFree->put(ulMemFree);
430 mBallooned->put(ulMemBalloon);
431 mCache->put(ulMemCache);
432 mPagedTotal->put(ulPageTotal);
433}
434
435void CircularBuffer::init(ULONG ulLength)
436{
437 if (mData)
438 RTMemFree(mData);
439 mLength = ulLength;
440 if (mLength)
441 mData = (ULONG*)RTMemAllocZ(ulLength * sizeof(ULONG));
442 else
443 mData = NULL;
444 mWrapped = false;
445 mEnd = 0;
446 mSequenceNumber = 0;
447}
448
449ULONG CircularBuffer::length()
450{
451 return mWrapped ? mLength : mEnd;
452}
453
454void CircularBuffer::put(ULONG value)
455{
456 if (mData)
457 {
458 mData[mEnd++] = value;
459 if (mEnd >= mLength)
460 {
461 mEnd = 0;
462 mWrapped = true;
463 }
464 ++mSequenceNumber;
465 }
466}
467
468void CircularBuffer::copyTo(ULONG *data)
469{
470 if (mWrapped)
471 {
472 memcpy(data, mData + mEnd, (mLength - mEnd) * sizeof(ULONG));
473 // Copy the wrapped part
474 if (mEnd)
475 memcpy(data + (mLength - mEnd), mData, mEnd * sizeof(ULONG));
476 }
477 else
478 memcpy(data, mData, mEnd * sizeof(ULONG));
479}
480
481void SubMetric::query(ULONG *data)
482{
483 copyTo(data);
484}
485
486void Metric::query(ULONG **data, ULONG *count, ULONG *sequenceNumber)
487{
488 ULONG length;
489 ULONG *tmpData;
490
491 length = mSubMetric->length();
492 *sequenceNumber = mSubMetric->getSequenceNumber() - length;
493 if (length)
494 {
495 tmpData = (ULONG*)RTMemAlloc(sizeof(*tmpData)*length);
496 mSubMetric->query(tmpData);
497 if (mAggregate)
498 {
499 *count = 1;
500 *data = (ULONG*)RTMemAlloc(sizeof(**data));
501 **data = mAggregate->compute(tmpData, length);
502 RTMemFree(tmpData);
503 }
504 else
505 {
506 *count = length;
507 *data = tmpData;
508 }
509 }
510 else
511 {
512 *count = 0;
513 *data = 0;
514 }
515}
516
517ULONG AggregateAvg::compute(ULONG *data, ULONG length)
518{
519 uint64_t tmp = 0;
520 for (ULONG i = 0; i < length; ++i)
521 tmp += data[i];
522 return (ULONG)(tmp / length);
523}
524
525const char * AggregateAvg::getName()
526{
527 return "avg";
528}
529
530ULONG AggregateMin::compute(ULONG *data, ULONG length)
531{
532 ULONG tmp = *data;
533 for (ULONG i = 0; i < length; ++i)
534 if (data[i] < tmp)
535 tmp = data[i];
536 return tmp;
537}
538
539const char * AggregateMin::getName()
540{
541 return "min";
542}
543
544ULONG AggregateMax::compute(ULONG *data, ULONG length)
545{
546 ULONG tmp = *data;
547 for (ULONG i = 0; i < length; ++i)
548 if (data[i] > tmp)
549 tmp = data[i];
550 return tmp;
551}
552
553const char * AggregateMax::getName()
554{
555 return "max";
556}
557
558Filter::Filter(ComSafeArrayIn(IN_BSTR, metricNames),
559 ComSafeArrayIn(IUnknown *, objects))
560{
561 /*
562 * Let's work around null/empty safe array mess. I am not sure there is
563 * a way to pass null arrays via webservice, I haven't found one. So I
564 * guess the users will be forced to use empty arrays instead. Constructing
565 * an empty SafeArray is a bit awkward, so what we do in this method is
566 * actually convert null arrays to empty arrays and pass them down to
567 * init() method. If someone knows how to do it better, please be my guest,
568 * fix it.
569 */
570 if (ComSafeArrayInIsNull(metricNames))
571 {
572 com::SafeArray<BSTR> nameArray;
573 if (ComSafeArrayInIsNull(objects))
574 {
575 com::SafeIfaceArray<IUnknown> objectArray;
576 objectArray.reset(0);
577 init(ComSafeArrayAsInParam(nameArray),
578 ComSafeArrayAsInParam(objectArray));
579 }
580 else
581 {
582 com::SafeIfaceArray<IUnknown> objectArray(ComSafeArrayInArg(objects));
583 init(ComSafeArrayAsInParam(nameArray),
584 ComSafeArrayAsInParam(objectArray));
585 }
586 }
587 else
588 {
589 com::SafeArray<IN_BSTR> nameArray(ComSafeArrayInArg(metricNames));
590 if (ComSafeArrayInIsNull(objects))
591 {
592 com::SafeIfaceArray<IUnknown> objectArray;
593 objectArray.reset(0);
594 init(ComSafeArrayAsInParam(nameArray),
595 ComSafeArrayAsInParam(objectArray));
596 }
597 else
598 {
599 com::SafeIfaceArray<IUnknown> objectArray(ComSafeArrayInArg(objects));
600 init(ComSafeArrayAsInParam(nameArray),
601 ComSafeArrayAsInParam(objectArray));
602 }
603 }
604}
605
606void Filter::init(ComSafeArrayIn(IN_BSTR, metricNames),
607 ComSafeArrayIn(IUnknown *, objects))
608{
609 com::SafeArray<IN_BSTR> nameArray(ComSafeArrayInArg(metricNames));
610 com::SafeIfaceArray<IUnknown> objectArray(ComSafeArrayInArg(objects));
611
612 if (!objectArray.size())
613 {
614 if (nameArray.size())
615 {
616 for (size_t i = 0; i < nameArray.size(); ++i)
617 processMetricList(com::Utf8Str(nameArray[i]), ComPtr<IUnknown>());
618 }
619 else
620 processMetricList("*", ComPtr<IUnknown>());
621 }
622 else
623 {
624 for (size_t i = 0; i < objectArray.size(); ++i)
625 switch (nameArray.size())
626 {
627 case 0:
628 processMetricList("*", objectArray[i]);
629 break;
630 case 1:
631 processMetricList(com::Utf8Str(nameArray[0]), objectArray[i]);
632 break;
633 default:
634 processMetricList(com::Utf8Str(nameArray[i]), objectArray[i]);
635 break;
636 }
637 }
638}
639
640void Filter::processMetricList(const com::Utf8Str &name, const ComPtr<IUnknown> object)
641{
642 size_t startPos = 0;
643
644 for (size_t pos = name.find(",");
645 pos != com::Utf8Str::npos;
646 pos = name.find(",", startPos))
647 {
648 mElements.push_back(std::make_pair(object, iprt::MiniString(name.substr(startPos, pos - startPos).c_str())));
649 startPos = pos + 1;
650 }
651 mElements.push_back(std::make_pair(object, iprt::MiniString(name.substr(startPos).c_str())));
652}
653
654/**
655 * The following method was borrowed from stamR3Match (VMM/STAM.cpp) and
656 * modified to handle the special case of trailing colon in the pattern.
657 *
658 * @returns True if matches, false if not.
659 * @param pszPat Pattern.
660 * @param pszName Name to match against the pattern.
661 * @param fSeenColon Seen colon (':').
662 */
663bool Filter::patternMatch(const char *pszPat, const char *pszName,
664 bool fSeenColon)
665{
666 /* ASSUMES ASCII */
667 for (;;)
668 {
669 char chPat = *pszPat;
670 switch (chPat)
671 {
672 default:
673 if (*pszName != chPat)
674 return false;
675 break;
676
677 case '*':
678 {
679 while ((chPat = *++pszPat) == '*' || chPat == '?')
680 /* nothing */;
681
682 /* Handle a special case, the mask terminating with a colon. */
683 if (chPat == ':')
684 {
685 if (!fSeenColon && !pszPat[1])
686 return !strchr(pszName, ':');
687 fSeenColon = true;
688 }
689
690 for (;;)
691 {
692 char ch = *pszName++;
693 if ( ch == chPat
694 && ( !chPat
695 || patternMatch(pszPat + 1, pszName, fSeenColon)))
696 return true;
697 if (!ch)
698 return false;
699 }
700 /* won't ever get here */
701 break;
702 }
703
704 case '?':
705 if (!*pszName)
706 return false;
707 break;
708
709 /* Handle a special case, the mask terminating with a colon. */
710 case ':':
711 if (!fSeenColon && !pszPat[1])
712 return !*pszName;
713 if (*pszName != ':')
714 return false;
715 fSeenColon = true;
716 break;
717
718 case '\0':
719 return !*pszName;
720 }
721 pszName++;
722 pszPat++;
723 }
724 return true;
725}
726
727bool Filter::match(const ComPtr<IUnknown> object, const iprt::MiniString &name) const
728{
729 ElementList::const_iterator it;
730
731 LogAleksey(("Filter::match(%p, %s)\n", static_cast<const IUnknown*> (object), name.c_str()));
732 for (it = mElements.begin(); it != mElements.end(); it++)
733 {
734 LogAleksey(("...matching against(%p, %s)\n", static_cast<const IUnknown*> ((*it).first), (*it).second.c_str()));
735 if ((*it).first.isNull() || (*it).first == object)
736 {
737 // Objects match, compare names
738 if (patternMatch((*it).second.c_str(), name.c_str()))
739 {
740 LogFlowThisFunc(("...found!\n"));
741 return true;
742 }
743 }
744 }
745 LogAleksey(("...no matches!\n"));
746 return false;
747}
748/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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