VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestImpl.cpp@ 52901

Last change on this file since 52901 was 52085, checked in by vboxsync, 10 years ago

6813 - GuestImpl using COM Wrappers - bug fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.1 KB
Line 
1/* $Id: GuestImpl.cpp 52085 2014-07-17 19:26:24Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation: Guest features.
4 */
5
6/*
7 * Copyright (C) 2006-2014 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include "GuestImpl.h"
19#include "GuestSessionImpl.h"
20
21#include "Global.h"
22#include "ConsoleImpl.h"
23#include "ProgressImpl.h"
24#ifdef VBOX_WITH_DRAG_AND_DROP
25# include "GuestDnDPrivate.h"
26#endif
27#include "VMMDev.h"
28
29#include "AutoCaller.h"
30#include "Logging.h"
31#include "Performance.h"
32#include "VBoxEvents.h"
33
34#include <VBox/VMMDev.h>
35#include <iprt/cpp/utils.h>
36#include <iprt/ctype.h>
37#include <iprt/stream.h>
38#include <iprt/timer.h>
39#include <VBox/vmm/pgm.h>
40#include <VBox/version.h>
41
42// defines
43/////////////////////////////////////////////////////////////////////////////
44
45// constructor / destructor
46/////////////////////////////////////////////////////////////////////////////
47
48DEFINE_EMPTY_CTOR_DTOR(Guest)
49
50HRESULT Guest::FinalConstruct()
51{
52 return BaseFinalConstruct();
53}
54
55void Guest::FinalRelease()
56{
57 uninit();
58 BaseFinalRelease();
59}
60
61// public methods only for internal purposes
62/////////////////////////////////////////////////////////////////////////////
63
64/**
65 * Initializes the guest object.
66 */
67HRESULT Guest::init(Console *aParent)
68{
69 LogFlowThisFunc(("aParent=%p\n", aParent));
70
71 ComAssertRet(aParent, E_INVALIDARG);
72
73 /* Enclose the state transition NotReady->InInit->Ready */
74 AutoInitSpan autoInitSpan(this);
75 AssertReturn(autoInitSpan.isOk(), E_FAIL);
76
77 unconst(mParent) = aParent;
78
79 /* Confirm a successful initialization when it's the case */
80 autoInitSpan.setSucceeded();
81
82 ULONG aMemoryBalloonSize;
83 HRESULT hr = mParent->i_machine()->COMGETTER(MemoryBalloonSize)(&aMemoryBalloonSize);
84 if (hr == S_OK) /** @todo r=andy SUCCEEDED? */
85 mMemoryBalloonSize = aMemoryBalloonSize;
86 else
87 mMemoryBalloonSize = 0; /* Default is no ballooning */
88
89 BOOL fPageFusionEnabled;
90 hr = mParent->i_machine()->COMGETTER(PageFusionEnabled)(&fPageFusionEnabled);
91 if (hr == S_OK) /** @todo r=andy SUCCEEDED? */
92 mfPageFusionEnabled = fPageFusionEnabled;
93 else
94 mfPageFusionEnabled = false; /* Default is no page fusion*/
95
96 mStatUpdateInterval = 0; /* Default is not to report guest statistics at all */
97 mCollectVMMStats = false;
98
99 /* Clear statistics. */
100 mNetStatRx = mNetStatTx = 0;
101 mNetStatLastTs = RTTimeNanoTS();
102 for (unsigned i = 0 ; i < GUESTSTATTYPE_MAX; i++)
103 mCurrentGuestStat[i] = 0;
104 mVmValidStats = pm::VMSTATMASK_NONE;
105
106 mMagic = GUEST_MAGIC;
107 int vrc = RTTimerLRCreate(&mStatTimer, 1000 /* ms */,
108 &Guest::i_staticUpdateStats, this);
109 AssertMsgRC(vrc, ("Failed to create guest statistics update timer (%Rrc)\n", vrc));
110
111#ifdef VBOX_WITH_GUEST_CONTROL
112 hr = unconst(mEventSource).createObject();
113 if (SUCCEEDED(hr))
114 hr = mEventSource->init();
115#else
116 hr = S_OK;
117#endif
118
119#ifdef VBOX_WITH_DRAG_AND_DROP
120 try
121 {
122 GuestDnD::createInstance(this /* pGuest */);
123 hr = unconst(mDnDSource).createObject();
124 if (SUCCEEDED(hr))
125 hr = mDnDSource->init(this /* pGuest */);
126 if (SUCCEEDED(hr))
127 {
128 hr = unconst(mDnDTarget).createObject();
129 if (SUCCEEDED(hr))
130 hr = mDnDTarget->init(this /* pGuest */);
131 }
132
133 LogFlowFunc(("Drag'n drop initializied with hr=%Rhrc\n", hr));
134 }
135 catch (std::bad_alloc &)
136 {
137 hr = E_OUTOFMEMORY;
138 }
139#endif
140
141 LogFlowFunc(("hr=%Rhrc\n", hr));
142 return hr;
143}
144
145/**
146 * Uninitializes the instance and sets the ready flag to FALSE.
147 * Called either from FinalRelease() or by the parent when it gets destroyed.
148 */
149void Guest::uninit()
150{
151 LogFlowThisFunc(("\n"));
152
153 /* Enclose the state transition Ready->InUninit->NotReady */
154 AutoUninitSpan autoUninitSpan(this);
155 if (autoUninitSpan.uninitDone())
156 return;
157
158 /* Destroy stat update timer */
159 int vrc = RTTimerLRDestroy(mStatTimer);
160 AssertMsgRC(vrc, ("Failed to create guest statistics update timer(%Rra)\n", vrc));
161 mStatTimer = NULL;
162 mMagic = 0;
163
164#ifdef VBOX_WITH_GUEST_CONTROL
165 LogFlowThisFunc(("Closing sessions (%RU64 total)\n",
166 mData.mGuestSessions.size()));
167 GuestSessions::iterator itSessions = mData.mGuestSessions.begin();
168 while (itSessions != mData.mGuestSessions.end())
169 {
170# ifdef DEBUG
171 ULONG cRefs = itSessions->second->AddRef();
172 LogFlowThisFunc(("sessionID=%RU32, cRefs=%RU32\n", itSessions->first, cRefs > 1 ? cRefs - 1 : 0));
173 itSessions->second->Release();
174# endif
175 itSessions->second->uninit();
176 itSessions++;
177 }
178 mData.mGuestSessions.clear();
179#endif
180
181#ifdef VBOX_WITH_DRAG_AND_DROP
182 GuestDnD::destroyInstance();
183 unconst(mDnDSource).setNull();
184 unconst(mDnDTarget).setNull();
185#endif
186
187#ifdef VBOX_WITH_GUEST_CONTROL
188 unconst(mEventSource).setNull();
189#endif
190 unconst(mParent) = NULL;
191
192 LogFlowFuncLeave();
193}
194
195/* static */
196DECLCALLBACK(void) Guest::i_staticUpdateStats(RTTIMERLR hTimerLR, void *pvUser, uint64_t iTick)
197{
198 AssertReturnVoid(pvUser != NULL);
199 Guest *guest = static_cast<Guest *>(pvUser);
200 Assert(guest->mMagic == GUEST_MAGIC);
201 if (guest->mMagic == GUEST_MAGIC)
202 guest->i_updateStats(iTick);
203
204 NOREF(hTimerLR);
205}
206
207/* static */
208int Guest::i_staticEnumStatsCallback(const char *pszName, STAMTYPE enmType, void *pvSample, STAMUNIT enmUnit,
209 STAMVISIBILITY enmVisiblity, const char *pszDesc, void *pvUser)
210{
211 AssertLogRelMsgReturn(enmType == STAMTYPE_COUNTER, ("Unexpected sample type %d ('%s')\n", enmType, pszName), VINF_SUCCESS);
212 AssertLogRelMsgReturn(enmUnit == STAMUNIT_BYTES, ("Unexpected sample unit %d ('%s')\n", enmUnit, pszName), VINF_SUCCESS);
213
214 /* Get the base name w/ slash. */
215 const char *pszLastSlash = strrchr(pszName, '/');
216 AssertLogRelMsgReturn(pszLastSlash, ("Unexpected sample '%s'\n", pszName), VINF_SUCCESS);
217
218 /* Receive or transmit? */
219 bool fRx;
220 if (!strcmp(pszLastSlash, "/BytesReceived"))
221 fRx = true;
222 else if (!strcmp(pszLastSlash, "/BytesTransmitted"))
223 fRx = false;
224 else
225 AssertLogRelMsgFailedReturn(("Unexpected sample '%s'\n", pszName), VINF_SUCCESS);
226
227#if 0 /* not used for anything, so don't bother parsing it. */
228 /* Find start of instance number. ASSUMES '/Public/Net/Name<Instance digits>/Bytes...' */
229 do
230 --pszLastSlash;
231 while (pszLastSlash > pszName && RT_C_IS_DIGIT(*pszLastSlash));
232 pszLastSlash++;
233
234 uint8_t uInstance;
235 int rc = RTStrToUInt8Ex(pszLastSlash, NULL, 10, &uInstance);
236 AssertLogRelMsgReturn(RT_SUCCESS(rc) && rc != VWRN_NUMBER_TOO_BIG && rc != VWRN_NEGATIVE_UNSIGNED,
237 ("%Rrc '%s'\n", rc, pszName), VINF_SUCCESS)
238#endif
239
240 /* Add the bytes to our counters. */
241 PSTAMCOUNTER pCnt = (PSTAMCOUNTER)pvSample;
242 Guest *pGuest = (Guest *)pvUser;
243 uint64_t cb = pCnt->c;
244#if 0
245 LogFlowFunc(("%s i=%u d=%s %llu bytes\n", pszName, uInstance, fRx ? "RX" : "TX", cb));
246#else
247 LogFlowFunc(("%s d=%s %llu bytes\n", pszName, fRx ? "RX" : "TX", cb));
248#endif
249 if (fRx)
250 pGuest->mNetStatRx += cb;
251 else
252 pGuest->mNetStatTx += cb;
253
254 return VINF_SUCCESS;
255}
256
257void Guest::i_updateStats(uint64_t iTick)
258{
259 uint64_t cbFreeTotal = 0;
260 uint64_t cbAllocTotal = 0;
261 uint64_t cbBalloonedTotal = 0;
262 uint64_t cbSharedTotal = 0;
263 uint64_t cbSharedMem = 0;
264 ULONG uNetStatRx = 0;
265 ULONG uNetStatTx = 0;
266 ULONG aGuestStats[GUESTSTATTYPE_MAX];
267 RT_ZERO(aGuestStats);
268
269 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
270
271 ULONG validStats = mVmValidStats;
272 /* Check if we have anything to report */
273 if (validStats)
274 {
275 mVmValidStats = pm::VMSTATMASK_NONE;
276 memcpy(aGuestStats, mCurrentGuestStat, sizeof(aGuestStats));
277 }
278 alock.release();
279
280 /*
281 * Calling SessionMachine may take time as the object resides in VBoxSVC
282 * process. This is why we took a snapshot of currently collected stats
283 * and released the lock.
284 */
285 Console::SafeVMPtrQuiet ptrVM(mParent);
286 if (ptrVM.isOk())
287 {
288 int rc;
289
290 /*
291 * There is no point in collecting VM shared memory if other memory
292 * statistics are not available yet. Or is there?
293 */
294 if (validStats)
295 {
296 /* Query the missing per-VM memory statistics. */
297 uint64_t cbTotalMemIgn, cbPrivateMemIgn, cbZeroMemIgn;
298 rc = PGMR3QueryMemoryStats(ptrVM.rawUVM(), &cbTotalMemIgn, &cbPrivateMemIgn, &cbSharedMem, &cbZeroMemIgn);
299 if (rc == VINF_SUCCESS)
300 validStats |= pm::VMSTATMASK_GUEST_MEMSHARED;
301 }
302
303 if (mCollectVMMStats)
304 {
305 rc = PGMR3QueryGlobalMemoryStats(ptrVM.rawUVM(), &cbAllocTotal, &cbFreeTotal, &cbBalloonedTotal, &cbSharedTotal);
306 AssertRC(rc);
307 if (rc == VINF_SUCCESS)
308 validStats |= pm::VMSTATMASK_VMM_ALLOC | pm::VMSTATMASK_VMM_FREE
309 | pm::VMSTATMASK_VMM_BALOON | pm::VMSTATMASK_VMM_SHARED;
310 }
311
312 uint64_t uRxPrev = mNetStatRx;
313 uint64_t uTxPrev = mNetStatTx;
314 mNetStatRx = mNetStatTx = 0;
315 rc = STAMR3Enum(ptrVM.rawUVM(), "/Public/Net/*/Bytes*", i_staticEnumStatsCallback, this);
316 AssertRC(rc);
317
318 uint64_t uTsNow = RTTimeNanoTS();
319 uint64_t cNsPassed = uTsNow - mNetStatLastTs;
320 if (cNsPassed >= 1000)
321 {
322 mNetStatLastTs = uTsNow;
323
324 uNetStatRx = (ULONG)((mNetStatRx - uRxPrev) * 1000000 / (cNsPassed / 1000)); /* in bytes per second */
325 uNetStatTx = (ULONG)((mNetStatTx - uTxPrev) * 1000000 / (cNsPassed / 1000)); /* in bytes per second */
326 validStats |= pm::VMSTATMASK_NET_RX | pm::VMSTATMASK_NET_TX;
327 LogFlowThisFunc(("Net Rx=%llu Tx=%llu Ts=%llu Delta=%llu\n", mNetStatRx, mNetStatTx, uTsNow, cNsPassed));
328 }
329 else
330 {
331 /* Can happen on resume or if we're using a non-monotonic clock
332 source for the timer and the time is adjusted. */
333 mNetStatRx = uRxPrev;
334 mNetStatTx = uTxPrev;
335 LogThisFunc(("Net Ts=%llu cNsPassed=%llu - too small interval\n", uTsNow, cNsPassed));
336 }
337 }
338
339 mParent->i_reportVmStatistics(validStats,
340 aGuestStats[GUESTSTATTYPE_CPUUSER],
341 aGuestStats[GUESTSTATTYPE_CPUKERNEL],
342 aGuestStats[GUESTSTATTYPE_CPUIDLE],
343 /* Convert the units for RAM usage stats: page (4K) -> 1KB units */
344 mCurrentGuestStat[GUESTSTATTYPE_MEMTOTAL] * (_4K/_1K),
345 mCurrentGuestStat[GUESTSTATTYPE_MEMFREE] * (_4K/_1K),
346 mCurrentGuestStat[GUESTSTATTYPE_MEMBALLOON] * (_4K/_1K),
347 (ULONG)(cbSharedMem / _1K), /* bytes -> KB */
348 mCurrentGuestStat[GUESTSTATTYPE_MEMCACHE] * (_4K/_1K),
349 mCurrentGuestStat[GUESTSTATTYPE_PAGETOTAL] * (_4K/_1K),
350 (ULONG)(cbAllocTotal / _1K), /* bytes -> KB */
351 (ULONG)(cbFreeTotal / _1K),
352 (ULONG)(cbBalloonedTotal / _1K),
353 (ULONG)(cbSharedTotal / _1K),
354 uNetStatRx,
355 uNetStatTx);
356}
357
358// IGuest properties
359/////////////////////////////////////////////////////////////////////////////
360
361HRESULT Guest::getOSTypeId(com::Utf8Str &aOSTypeId)
362{
363 HRESULT hrc = S_OK;
364 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
365 if (!mData.mInterfaceVersion.isEmpty())
366 aOSTypeId = mData.mOSTypeId;
367 else
368 {
369 /* Redirect the call to IMachine if no additions are installed. */
370 ComPtr<IMachine> ptrMachine(mParent->i_machine());
371 alock.release();
372 BSTR bstr;
373 hrc = ptrMachine->COMGETTER(OSTypeId)(&bstr);
374 aOSTypeId = bstr;
375 }
376 return hrc;
377}
378
379HRESULT Guest::getAdditionsRunLevel(AdditionsRunLevelType_T *aAdditionsRunLevel)
380{
381 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
382
383 *aAdditionsRunLevel = mData.mAdditionsRunLevel;
384
385 return S_OK;
386}
387
388HRESULT Guest::getAdditionsVersion(com::Utf8Str &aAdditionsVersion)
389{
390 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
391 HRESULT hrc = S_OK;
392
393 /*
394 * Return the ReportGuestInfo2 version info if available.
395 */
396 if ( !mData.mAdditionsVersionNew.isEmpty()
397 || mData.mAdditionsRunLevel <= AdditionsRunLevelType_None)
398 aAdditionsVersion = mData.mAdditionsVersionNew;
399 else
400 {
401 /*
402 * If we're running older guest additions (< 3.2.0) try get it from
403 * the guest properties. Detected switched around Version and
404 * Revision in early 3.1.x releases (see r57115).
405 */
406 ComPtr<IMachine> ptrMachine = mParent->i_machine();
407 alock.release(); /* No need to hold this during the IPC fun. */
408
409 Bstr bstr;
410 hrc = ptrMachine->GetGuestPropertyValue(Bstr("/VirtualBox/GuestAdd/Version").raw(), bstr.asOutParam());
411 if ( SUCCEEDED(hrc)
412 && !bstr.isEmpty())
413 {
414 Utf8Str str(bstr);
415 if (str.count('.') == 0)
416 hrc = ptrMachine->GetGuestPropertyValue(Bstr("/VirtualBox/GuestAdd/Revision").raw(), bstr.asOutParam());
417 str = bstr;
418 if (str.count('.') != 2)
419 hrc = E_FAIL;
420 }
421
422 if (SUCCEEDED(hrc))
423 aAdditionsVersion = bstr;
424 else
425 {
426 /* Returning 1.4 is better than nothing. */
427 alock.acquire();
428 aAdditionsVersion = mData.mInterfaceVersion;
429 hrc = S_OK;
430 }
431 }
432 return hrc;
433}
434
435HRESULT Guest::getAdditionsRevision(ULONG *aAdditionsRevision)
436{
437 HRESULT hrc = S_OK;
438 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
439
440 /*
441 * Return the ReportGuestInfo2 version info if available.
442 */
443 if ( !mData.mAdditionsVersionNew.isEmpty()
444 || mData.mAdditionsRunLevel <= AdditionsRunLevelType_None)
445 *aAdditionsRevision = mData.mAdditionsRevision;
446 else
447 {
448 /*
449 * If we're running older guest additions (< 3.2.0) try get it from
450 * the guest properties. Detected switched around Version and
451 * Revision in early 3.1.x releases (see r57115).
452 */
453 ComPtr<IMachine> ptrMachine = mParent->i_machine();
454 alock.release(); /* No need to hold this during the IPC fun. */
455
456 Bstr bstr;
457 hrc = ptrMachine->GetGuestPropertyValue(Bstr("/VirtualBox/GuestAdd/Revision").raw(), bstr.asOutParam());
458 if (SUCCEEDED(hrc))
459 {
460 Utf8Str str(bstr);
461 uint32_t uRevision;
462 int vrc = RTStrToUInt32Full(str.c_str(), 0, &uRevision);
463 if (vrc != VINF_SUCCESS && str.count('.') == 2)
464 {
465 hrc = ptrMachine->GetGuestPropertyValue(Bstr("/VirtualBox/GuestAdd/Version").raw(), bstr.asOutParam());
466 if (SUCCEEDED(hrc))
467 {
468 str = bstr;
469 vrc = RTStrToUInt32Full(str.c_str(), 0, &uRevision);
470 }
471 }
472 if (vrc == VINF_SUCCESS)
473 *aAdditionsRevision = uRevision;
474 else
475 hrc = VBOX_E_IPRT_ERROR;
476 }
477 if (FAILED(hrc))
478 {
479 /* Return 0 if we don't know. */
480 *aAdditionsRevision = 0;
481 hrc = S_OK;
482 }
483 }
484 return hrc;
485}
486
487HRESULT Guest::getDnDSource(ComPtr<IGuestDnDSource> &aDnDSource)
488{
489#ifndef VBOX_WITH_DRAG_AND_DROP
490 ReturnComNotImplemented();
491#else
492 LogFlowThisFuncEnter();
493
494 /* No need to lock - lifetime constant. */
495 HRESULT hr = mDnDSource.queryInterfaceTo(aDnDSource.asOutParam());
496
497 LogFlowFuncLeaveRC(hr);
498 return hr;
499#endif /* VBOX_WITH_DRAG_AND_DROP */
500}
501
502HRESULT Guest::getDnDTarget(ComPtr<IGuestDnDTarget> &aDnDTarget)
503{
504#ifndef VBOX_WITH_DRAG_AND_DROP
505 ReturnComNotImplemented();
506#else
507 LogFlowThisFuncEnter();
508
509 /* No need to lock - lifetime constant. */
510 HRESULT hr = mDnDTarget.queryInterfaceTo(aDnDTarget.asOutParam());
511
512 LogFlowFuncLeaveRC(hr);
513 return hr;
514#endif /* VBOX_WITH_DRAG_AND_DROP */
515}
516
517HRESULT Guest::getEventSource(ComPtr<IEventSource> &aEventSource)
518{
519#ifndef VBOX_WITH_GUEST_CONTROL
520 ReturnComNotImplemented();
521#else
522 LogFlowThisFuncEnter();
523
524 /* No need to lock - lifetime constant. */
525 mEventSource.queryInterfaceTo(aEventSource.asOutParam());
526
527 LogFlowFuncLeaveRC(S_OK);
528 return S_OK;
529#endif /* VBOX_WITH_GUEST_CONTROL */
530}
531
532HRESULT Guest::getFacilities(std::vector<ComPtr<IAdditionsFacility> > &aFacilities)
533{
534 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
535
536 aFacilities.resize(mData.mFacilityMap.size());
537 size_t i = 0;
538 for (FacilityMapIter it = mData.mFacilityMap.begin(); it != mData.mFacilityMap.end(); ++it, ++i)
539 it->second.queryInterfaceTo(aFacilities[i].asOutParam());
540
541 return S_OK;
542}
543
544HRESULT Guest::getSessions(std::vector<ComPtr<IGuestSession> > &aSessions)
545{
546 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
547
548 aSessions.resize(mData.mGuestSessions.size());
549 size_t i = 0;
550 for (GuestSessions::iterator it = mData.mGuestSessions.begin(); it != mData.mGuestSessions.end(); ++it, ++i)
551 it->second.queryInterfaceTo(aSessions[i].asOutParam());
552
553 return S_OK;
554}
555
556BOOL Guest::i_isPageFusionEnabled()
557{
558 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
559
560 return mfPageFusionEnabled;
561}
562
563HRESULT Guest::getMemoryBalloonSize(ULONG *aMemoryBalloonSize)
564{
565 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
566
567 *aMemoryBalloonSize = mMemoryBalloonSize;
568
569 return S_OK;
570}
571
572HRESULT Guest::setMemoryBalloonSize(ULONG aMemoryBalloonSize)
573{
574 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
575
576 /* We must be 100% sure that IMachine::COMSETTER(MemoryBalloonSize)
577 * does not call us back in any way! */
578 HRESULT ret = mParent->i_machine()->COMSETTER(MemoryBalloonSize)(aMemoryBalloonSize);
579 if (ret == S_OK)
580 {
581 mMemoryBalloonSize = aMemoryBalloonSize;
582 /* forward the information to the VMM device */
583 VMMDev *pVMMDev = mParent->i_getVMMDev();
584 /* MUST release all locks before calling VMM device as its critsect
585 * has higher lock order than anything in Main. */
586 alock.release();
587 if (pVMMDev)
588 {
589 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
590 if (pVMMDevPort)
591 pVMMDevPort->pfnSetMemoryBalloon(pVMMDevPort, aMemoryBalloonSize);
592 }
593 }
594
595 return ret;
596}
597
598HRESULT Guest::getStatisticsUpdateInterval(ULONG *aStatisticsUpdateInterval)
599{
600 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
601
602 *aStatisticsUpdateInterval = mStatUpdateInterval;
603 return S_OK;
604}
605
606HRESULT Guest::setStatisticsUpdateInterval(ULONG aStatisticsUpdateInterval)
607{
608 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
609
610 if (mStatUpdateInterval)
611 if (aStatisticsUpdateInterval == 0)
612 RTTimerLRStop(mStatTimer);
613 else
614 RTTimerLRChangeInterval(mStatTimer, aStatisticsUpdateInterval);
615 else
616 if (aStatisticsUpdateInterval != 0)
617 {
618 RTTimerLRChangeInterval(mStatTimer, aStatisticsUpdateInterval);
619 RTTimerLRStart(mStatTimer, 0);
620 }
621 mStatUpdateInterval = aStatisticsUpdateInterval;
622 /* forward the information to the VMM device */
623 VMMDev *pVMMDev = mParent->i_getVMMDev();
624 /* MUST release all locks before calling VMM device as its critsect
625 * has higher lock order than anything in Main. */
626 alock.release();
627 if (pVMMDev)
628 {
629 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
630 if (pVMMDevPort)
631 pVMMDevPort->pfnSetStatisticsInterval(pVMMDevPort, aStatisticsUpdateInterval);
632 }
633
634 return S_OK;
635}
636
637
638HRESULT Guest::internalGetStatistics(ULONG *aCpuUser, ULONG *aCpuKernel, ULONG *aCpuIdle,
639 ULONG *aMemTotal, ULONG *aMemFree, ULONG *aMemBalloon,
640 ULONG *aMemShared, ULONG *aMemCache, ULONG *aPageTotal,
641 ULONG *aMemAllocTotal, ULONG *aMemFreeTotal,
642 ULONG *aMemBalloonTotal, ULONG *aMemSharedTotal)
643{
644 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
645
646 *aCpuUser = mCurrentGuestStat[GUESTSTATTYPE_CPUUSER];
647 *aCpuKernel = mCurrentGuestStat[GUESTSTATTYPE_CPUKERNEL];
648 *aCpuIdle = mCurrentGuestStat[GUESTSTATTYPE_CPUIDLE];
649 *aMemTotal = mCurrentGuestStat[GUESTSTATTYPE_MEMTOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
650 *aMemFree = mCurrentGuestStat[GUESTSTATTYPE_MEMFREE] * (_4K/_1K); /* page (4K) -> 1KB units */
651 *aMemBalloon = mCurrentGuestStat[GUESTSTATTYPE_MEMBALLOON] * (_4K/_1K); /* page (4K) -> 1KB units */
652 *aMemCache = mCurrentGuestStat[GUESTSTATTYPE_MEMCACHE] * (_4K/_1K); /* page (4K) -> 1KB units */
653 *aPageTotal = mCurrentGuestStat[GUESTSTATTYPE_PAGETOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
654
655 /* Play safe or smth? */
656 *aMemAllocTotal = 0;
657 *aMemFreeTotal = 0;
658 *aMemBalloonTotal = 0;
659 *aMemSharedTotal = 0;
660 *aMemShared = 0;
661
662 /* MUST release all locks before calling any PGM statistics queries,
663 * as they are executed by EMT and that might deadlock us by VMM device
664 * activity which waits for the Guest object lock. */
665 alock.release();
666 Console::SafeVMPtr ptrVM(mParent);
667 if (!ptrVM.isOk())
668 return E_FAIL;
669
670 uint64_t cbFreeTotal, cbAllocTotal, cbBalloonedTotal, cbSharedTotal;
671 int rc = PGMR3QueryGlobalMemoryStats(ptrVM.rawUVM(), &cbAllocTotal, &cbFreeTotal, &cbBalloonedTotal, &cbSharedTotal);
672 AssertRCReturn(rc, E_FAIL);
673
674 *aMemAllocTotal = (ULONG)(cbAllocTotal / _1K); /* bytes -> KB */
675 *aMemFreeTotal = (ULONG)(cbFreeTotal / _1K);
676 *aMemBalloonTotal = (ULONG)(cbBalloonedTotal / _1K);
677 *aMemSharedTotal = (ULONG)(cbSharedTotal / _1K);
678
679 /* Query the missing per-VM memory statistics. */
680 uint64_t cbTotalMemIgn, cbPrivateMemIgn, cbSharedMem, cbZeroMemIgn;
681 rc = PGMR3QueryMemoryStats(ptrVM.rawUVM(), &cbTotalMemIgn, &cbPrivateMemIgn, &cbSharedMem, &cbZeroMemIgn);
682 AssertRCReturn(rc, E_FAIL);
683 *aMemShared = (ULONG)(cbSharedMem / _1K);
684
685 return S_OK;
686}
687
688HRESULT Guest::i_setStatistic(ULONG aCpuId, GUESTSTATTYPE enmType, ULONG aVal)
689{
690 static ULONG indexToPerfMask[] =
691 {
692 pm::VMSTATMASK_GUEST_CPUUSER,
693 pm::VMSTATMASK_GUEST_CPUKERNEL,
694 pm::VMSTATMASK_GUEST_CPUIDLE,
695 pm::VMSTATMASK_GUEST_MEMTOTAL,
696 pm::VMSTATMASK_GUEST_MEMFREE,
697 pm::VMSTATMASK_GUEST_MEMBALLOON,
698 pm::VMSTATMASK_GUEST_MEMCACHE,
699 pm::VMSTATMASK_GUEST_PAGETOTAL,
700 pm::VMSTATMASK_NONE
701 };
702 AutoCaller autoCaller(this);
703 if (FAILED(autoCaller.rc())) return autoCaller.rc();
704
705 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
706
707 if (enmType >= GUESTSTATTYPE_MAX)
708 return E_INVALIDARG;
709
710 mCurrentGuestStat[enmType] = aVal;
711 mVmValidStats |= indexToPerfMask[enmType];
712 return S_OK;
713}
714
715/**
716 * Returns the status of a specified Guest Additions facility.
717 *
718 * @return aStatus Current status of specified facility.
719 * @param aType Facility to get the status from.
720 * @param aTimestamp Timestamp of last facility status update in ms (optional).
721 */
722HRESULT Guest::getFacilityStatus(AdditionsFacilityType_T aFacility, LONG64 *aTimestamp, AdditionsFacilityStatus_T *aStatus)
723{
724 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
725
726 /* Not checking for aTimestamp is intentional; it's optional. */
727 FacilityMapIterConst it = mData.mFacilityMap.find(aFacility);
728 if (it != mData.mFacilityMap.end())
729 {
730 AdditionsFacility *pFacility = it->second;
731 ComAssert(pFacility);
732 *aStatus = pFacility->i_getStatus();
733 if (aTimestamp)
734 *aTimestamp = pFacility->i_getLastUpdated();
735 }
736 else
737 {
738 /*
739 * Do not fail here -- could be that the facility never has been brought up (yet) but
740 * the host wants to have its status anyway. So just tell we don't know at this point.
741 */
742 *aStatus = AdditionsFacilityStatus_Unknown;
743 if (aTimestamp)
744 *aTimestamp = RTTimeMilliTS();
745 }
746 return S_OK;
747}
748
749HRESULT Guest::getAdditionsStatus(AdditionsRunLevelType_T aLevel, BOOL *aActive)
750{
751 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
752
753 HRESULT rc = S_OK;
754 switch (aLevel)
755 {
756 case AdditionsRunLevelType_System:
757 *aActive = (mData.mAdditionsRunLevel > AdditionsRunLevelType_None);
758 break;
759
760 case AdditionsRunLevelType_Userland:
761 *aActive = (mData.mAdditionsRunLevel >= AdditionsRunLevelType_Userland);
762 break;
763
764 case AdditionsRunLevelType_Desktop:
765 *aActive = (mData.mAdditionsRunLevel >= AdditionsRunLevelType_Desktop);
766 break;
767
768 default:
769 rc = setError(VBOX_E_NOT_SUPPORTED,
770 tr("Invalid status level defined: %u"), aLevel);
771 break;
772 }
773
774 return rc;
775}
776HRESULT Guest::setCredentials(const com::Utf8Str &aUserName, const com::Utf8Str &aPassword,
777 const com::Utf8Str &aDomain, BOOL aAllowInteractiveLogon)
778{
779 /* Check for magic domain names which are used to pass encryption keys to the disk. */
780 if (Utf8Str(aDomain) == "@@disk")
781 return mParent->i_setDiskEncryptionKeys(aPassword);
782 else if (Utf8Str(aDomain) == "@@mem")
783 {
784 /** @todo */
785 return E_NOTIMPL;
786 }
787 else
788 {
789 /* forward the information to the VMM device */
790 VMMDev *pVMMDev = mParent->i_getVMMDev();
791 if (pVMMDev)
792 {
793 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
794 if (pVMMDevPort)
795 {
796 uint32_t u32Flags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
797 if (!aAllowInteractiveLogon)
798 u32Flags = VMMDEV_SETCREDENTIALS_NOLOCALLOGON;
799
800 pVMMDevPort->pfnSetCredentials(pVMMDevPort,
801 aUserName.c_str(),
802 aPassword.c_str(),
803 aDomain.c_str(),
804 u32Flags);
805 return S_OK;
806 }
807 }
808 }
809
810 return setError(VBOX_E_VM_ERROR,
811 tr("VMM device is not available (is the VM running?)"));
812}
813
814// public methods only for internal purposes
815/////////////////////////////////////////////////////////////////////////////
816
817/**
818 * Sets the general Guest Additions information like
819 * API (interface) version and OS type. Gets called by
820 * vmmdevUpdateGuestInfo.
821 *
822 * @param aInterfaceVersion
823 * @param aOsType
824 */
825void Guest::i_setAdditionsInfo(com::Utf8Str aInterfaceVersion, VBOXOSTYPE aOsType)
826{
827 RTTIMESPEC TimeSpecTS;
828 RTTimeNow(&TimeSpecTS);
829
830 AutoCaller autoCaller(this);
831 AssertComRCReturnVoid(autoCaller.rc());
832
833 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
834
835
836 /*
837 * Note: The Guest Additions API (interface) version is deprecated
838 * and will not be used anymore! We might need it to at least report
839 * something as version number if *really* ancient Guest Additions are
840 * installed (without the guest version + revision properties having set).
841 */
842 mData.mInterfaceVersion = aInterfaceVersion;
843
844 /*
845 * Older Additions rely on the Additions API version whether they
846 * are assumed to be active or not. Since newer Additions do report
847 * the Additions version *before* calling this function (by calling
848 * VMMDevReportGuestInfo2, VMMDevReportGuestStatus, VMMDevReportGuestInfo,
849 * in that order) we can tell apart old and new Additions here. Old
850 * Additions never would set VMMDevReportGuestInfo2 (which set mData.mAdditionsVersion)
851 * so they just rely on the aInterfaceVersion string (which gets set by
852 * VMMDevReportGuestInfo).
853 *
854 * So only mark the Additions as being active (run level = system) when we
855 * don't have the Additions version set.
856 */
857 if (mData.mAdditionsVersionNew.isEmpty())
858 {
859 if (aInterfaceVersion.isEmpty())
860 mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
861 else
862 {
863 mData.mAdditionsRunLevel = AdditionsRunLevelType_System;
864
865 /*
866 * To keep it compatible with the old Guest Additions behavior we need to set the
867 * "graphics" (feature) facility to active as soon as we got the Guest Additions
868 * interface version.
869 */
870 i_facilityUpdate(VBoxGuestFacilityType_Graphics, VBoxGuestFacilityStatus_Active, 0 /*fFlags*/, &TimeSpecTS);
871 }
872 }
873
874 /*
875 * Older Additions didn't have this finer grained capability bit,
876 * so enable it by default. Newer Additions will not enable this here
877 * and use the setSupportedFeatures function instead.
878 */
879 /** @todo r=bird: I don't get the above comment nor the code below...
880 * One talks about capability bits, the one always does something to a facility.
881 * Then there is the comment below it all, which is placed like it addresses the
882 * mOSTypeId, but talks about something which doesn't remotely like mOSTypeId...
883 *
884 * Andy, could you please try clarify and make the comments shorter and more
885 * coherent! Also, explain why this is important and what depends on it.
886 *
887 * PS. There is the VMMDEV_GUEST_SUPPORTS_GRAPHICS capability* report... It
888 * should come in pretty quickly after this update, normally.
889 */
890 i_facilityUpdate(VBoxGuestFacilityType_Graphics,
891 i_facilityIsActive(VBoxGuestFacilityType_VBoxGuestDriver)
892 ? VBoxGuestFacilityStatus_Active : VBoxGuestFacilityStatus_Inactive,
893 0 /*fFlags*/, &TimeSpecTS); /** @todo the timestamp isn't gonna be right here on saved state restore. */
894
895 /*
896 * Note! There is a race going on between setting mAdditionsRunLevel and
897 * mSupportsGraphics here and disabling/enabling it later according to
898 * its real status when using new(er) Guest Additions.
899 */
900 mData.mOSTypeId = Global::OSTypeId(aOsType);
901}
902
903/**
904 * Sets the Guest Additions version information details.
905 *
906 * Gets called by vmmdevUpdateGuestInfo2 and vmmdevUpdateGuestInfo (to clear the
907 * state).
908 *
909 * @param a_uFullVersion VBoxGuestInfo2::additionsMajor,
910 * VBoxGuestInfo2::additionsMinor and
911 * VBoxGuestInfo2::additionsBuild combined into
912 * one value by VBOX_FULL_VERSION_MAKE.
913 *
914 * When this is 0, it's vmmdevUpdateGuestInfo
915 * calling to reset the state.
916 *
917 * @param a_pszName Build type tag and/or publisher tag, empty
918 * string if neiter of those are present.
919 * @param a_uRevision See VBoxGuestInfo2::additionsRevision.
920 * @param a_fFeatures See VBoxGuestInfo2::additionsFeatures.
921 */
922void Guest::i_setAdditionsInfo2(uint32_t a_uFullVersion, const char *a_pszName, uint32_t a_uRevision, uint32_t a_fFeatures)
923{
924 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
925
926 if (a_uFullVersion)
927 {
928 mData.mAdditionsVersionNew = Utf8StrFmt(*a_pszName ? "%u.%u.%u_%s" : "%u.%u.%u",
929 VBOX_FULL_VERSION_GET_MAJOR(a_uFullVersion),
930 VBOX_FULL_VERSION_GET_MINOR(a_uFullVersion),
931 VBOX_FULL_VERSION_GET_BUILD(a_uFullVersion),
932 a_pszName);
933 mData.mAdditionsVersionFull = a_uFullVersion;
934 mData.mAdditionsRevision = a_uRevision;
935 mData.mAdditionsFeatures = a_fFeatures;
936 }
937 else
938 {
939 Assert(!a_fFeatures && !a_uRevision && !*a_pszName);
940 mData.mAdditionsVersionNew.setNull();
941 mData.mAdditionsVersionFull = 0;
942 mData.mAdditionsRevision = 0;
943 mData.mAdditionsFeatures = 0;
944 }
945}
946
947bool Guest::i_facilityIsActive(VBoxGuestFacilityType enmFacility)
948{
949 Assert(enmFacility < INT32_MAX);
950 FacilityMapIterConst it = mData.mFacilityMap.find((AdditionsFacilityType_T)enmFacility);
951 if (it != mData.mFacilityMap.end())
952 {
953 AdditionsFacility *pFac = it->second;
954 return (pFac->i_getStatus() == AdditionsFacilityStatus_Active);
955 }
956 return false;
957}
958
959void Guest::i_facilityUpdate(VBoxGuestFacilityType a_enmFacility, VBoxGuestFacilityStatus a_enmStatus,
960 uint32_t a_fFlags, PCRTTIMESPEC a_pTimeSpecTS)
961{
962 AssertReturnVoid( a_enmFacility < VBoxGuestFacilityType_All
963 && a_enmFacility > VBoxGuestFacilityType_Unknown);
964
965 FacilityMapIter it = mData.mFacilityMap.find((AdditionsFacilityType_T)a_enmFacility);
966 if (it != mData.mFacilityMap.end())
967 {
968 AdditionsFacility *pFac = it->second;
969 pFac->i_update((AdditionsFacilityStatus_T)a_enmStatus, a_fFlags, a_pTimeSpecTS);
970 }
971 else
972 {
973 if (mData.mFacilityMap.size() > 64)
974 {
975 /* The easy way out for now. We could automatically destroy
976 inactive facilities like VMMDev does if we like... */
977 AssertFailedReturnVoid();
978 }
979
980 ComObjPtr<AdditionsFacility> ptrFac;
981 ptrFac.createObject();
982 AssertReturnVoid(!ptrFac.isNull());
983
984 HRESULT hrc = ptrFac->init(this, (AdditionsFacilityType_T)a_enmFacility, (AdditionsFacilityStatus_T)a_enmStatus,
985 a_fFlags, a_pTimeSpecTS);
986 if (SUCCEEDED(hrc))
987 mData.mFacilityMap.insert(std::make_pair((AdditionsFacilityType_T)a_enmFacility, ptrFac));
988 }
989}
990
991/**
992 * Issued by the guest when a guest user changed its state.
993 *
994 * @return IPRT status code.
995 * @param aUser Guest user name.
996 * @param aDomain Domain of guest user account. Optional.
997 * @param enmState New state to indicate.
998 * @param puDetails Pointer to state details. Optional.
999 * @param cbDetails Size (in bytes) of state details. Pass 0 if not used.
1000 */
1001void Guest::i_onUserStateChange(Bstr aUser, Bstr aDomain, VBoxGuestUserState enmState,
1002 const uint8_t *puDetails, uint32_t cbDetails)
1003{
1004 LogFlowThisFunc(("\n"));
1005
1006 AutoCaller autoCaller(this);
1007 AssertComRCReturnVoid(autoCaller.rc());
1008
1009 Bstr strDetails; /** @todo Implement state details here. */
1010
1011 fireGuestUserStateChangedEvent(mEventSource, aUser.raw(), aDomain.raw(),
1012 (GuestUserState_T)enmState, strDetails.raw());
1013 LogFlowFuncLeave();
1014}
1015
1016/**
1017 * Sets the status of a certain Guest Additions facility.
1018 *
1019 * Gets called by vmmdevUpdateGuestStatus, which just passes the report along.
1020 *
1021 * @param a_pInterface Pointer to this interface.
1022 * @param a_enmFacility The facility.
1023 * @param a_enmStatus The status.
1024 * @param a_fFlags Flags assoicated with the update. Currently
1025 * reserved and should be ignored.
1026 * @param a_pTimeSpecTS Pointer to the timestamp of this report.
1027 * @sa PDMIVMMDEVCONNECTOR::pfnUpdateGuestStatus, vmmdevUpdateGuestStatus
1028 * @thread The emulation thread.
1029 */
1030void Guest::i_setAdditionsStatus(VBoxGuestFacilityType a_enmFacility, VBoxGuestFacilityStatus a_enmStatus,
1031 uint32_t a_fFlags, PCRTTIMESPEC a_pTimeSpecTS)
1032{
1033 Assert( a_enmFacility > VBoxGuestFacilityType_Unknown
1034 && a_enmFacility <= VBoxGuestFacilityType_All); /* Paranoia, VMMDev checks for this. */
1035
1036 AutoCaller autoCaller(this);
1037 AssertComRCReturnVoid(autoCaller.rc());
1038
1039 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1040
1041 /*
1042 * Set a specific facility status.
1043 */
1044 if (a_enmFacility == VBoxGuestFacilityType_All)
1045 for (FacilityMapIter it = mData.mFacilityMap.begin(); it != mData.mFacilityMap.end(); ++it)
1046 i_facilityUpdate((VBoxGuestFacilityType)it->first, a_enmStatus, a_fFlags, a_pTimeSpecTS);
1047 else /* Update one facility only. */
1048 i_facilityUpdate(a_enmFacility, a_enmStatus, a_fFlags, a_pTimeSpecTS);
1049
1050 /*
1051 * Recalc the runlevel.
1052 */
1053 if (i_facilityIsActive(VBoxGuestFacilityType_VBoxTrayClient))
1054 mData.mAdditionsRunLevel = AdditionsRunLevelType_Desktop;
1055 else if (i_facilityIsActive(VBoxGuestFacilityType_VBoxService))
1056 mData.mAdditionsRunLevel = AdditionsRunLevelType_Userland;
1057 else if (i_facilityIsActive(VBoxGuestFacilityType_VBoxGuestDriver))
1058 mData.mAdditionsRunLevel = AdditionsRunLevelType_System;
1059 else
1060 mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
1061}
1062
1063/**
1064 * Sets the supported features (and whether they are active or not).
1065 *
1066 * @param fCaps Guest capability bit mask (VMMDEV_GUEST_SUPPORTS_XXX).
1067 */
1068void Guest::i_setSupportedFeatures(uint32_t aCaps)
1069{
1070 AutoCaller autoCaller(this);
1071 AssertComRCReturnVoid(autoCaller.rc());
1072
1073 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1074
1075 /** @todo A nit: The timestamp is wrong on saved state restore. Would be better
1076 * to move the graphics and seamless capability -> facility translation to
1077 * VMMDev so this could be saved. */
1078 RTTIMESPEC TimeSpecTS;
1079 RTTimeNow(&TimeSpecTS);
1080
1081 i_facilityUpdate(VBoxGuestFacilityType_Seamless,
1082 aCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS ? VBoxGuestFacilityStatus_Active : VBoxGuestFacilityStatus_Inactive,
1083 0 /*fFlags*/, &TimeSpecTS);
1084 /** @todo Add VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING */
1085 i_facilityUpdate(VBoxGuestFacilityType_Graphics,
1086 aCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS ? VBoxGuestFacilityStatus_Active : VBoxGuestFacilityStatus_Inactive,
1087 0 /*fFlags*/, &TimeSpecTS);
1088}
1089
Note: See TracBrowser for help on using the repository browser.

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