VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/ConsoleImpl2.cpp@ 48764

Last change on this file since 48764 was 48764, checked in by vboxsync, 11 years ago

ConsoleImpl2:SMC: (darwin build fix).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 217.9 KB
Line 
1/* $Id: ConsoleImpl2.cpp 48764 2013-09-30 05:57:41Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation - VM Configuration Bits.
4 *
5 * @remark We've split out the code that the 64-bit VC++ v8 compiler finds
6 * problematic to optimize so we can disable optimizations and later,
7 * perhaps, find a real solution for it (like rewriting the code and
8 * to stop resemble a tonne of spaghetti).
9 */
10
11/*
12 * Copyright (C) 2006-2013 Oracle Corporation
13 *
14 * This file is part of VirtualBox Open Source Edition (OSE), as
15 * available from http://www.virtualbox.org. This file is free software;
16 * you can redistribute it and/or modify it under the terms of the GNU
17 * General Public License (GPL) as published by the Free Software
18 * Foundation, in version 2 as it comes in the "COPYING" file of the
19 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
20 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
21 */
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26// for some reason Windows burns in sdk\...\winsock.h if this isn't included first
27#include "VBox/com/ptr.h"
28
29#include "ConsoleImpl.h"
30#include "DisplayImpl.h"
31#ifdef VBOX_WITH_GUEST_CONTROL
32# include "GuestImpl.h"
33#endif
34#ifdef VBOX_WITH_DRAG_AND_DROP
35# include "GuestDnDImpl.h"
36#endif
37#include "VMMDev.h"
38#include "Global.h"
39#ifdef VBOX_WITH_PCI_PASSTHROUGH
40# include "PCIRawDevImpl.h"
41#endif
42
43// generated header
44#include "SchemaDefs.h"
45
46#include "AutoCaller.h"
47#include "Logging.h"
48
49#include <iprt/base64.h>
50#include <iprt/buildconfig.h>
51#include <iprt/ctype.h>
52#include <iprt/dir.h>
53#include <iprt/file.h>
54#include <iprt/param.h>
55#include <iprt/path.h>
56#include <iprt/string.h>
57#include <iprt/system.h>
58#include <iprt/cpp/exception.h>
59#if 0 /* enable to play with lots of memory. */
60# include <iprt/env.h>
61#endif
62#include <iprt/stream.h>
63
64#include <VBox/vmm/vmapi.h>
65#include <VBox/err.h>
66#include <VBox/param.h>
67#include <VBox/vmm/pdmapi.h> /* For PDMR3DriverAttach/PDMR3DriverDetach */
68#include <VBox/version.h>
69#include <VBox/HostServices/VBoxClipboardSvc.h>
70#ifdef VBOX_WITH_CROGL
71# include <VBox/HostServices/VBoxCrOpenGLSvc.h>
72#include <VBox/VBoxOGLTest.h>
73#endif
74#ifdef VBOX_WITH_GUEST_PROPS
75# include <VBox/HostServices/GuestPropertySvc.h>
76# include <VBox/com/defs.h>
77# include <VBox/com/array.h>
78# include "HGCM.h" /** @todo it should be possible to register a service
79 * extension using a VMMDev callback. */
80# include <vector>
81#endif /* VBOX_WITH_GUEST_PROPS */
82#include <VBox/intnet.h>
83
84#include <VBox/com/com.h>
85#include <VBox/com/string.h>
86#include <VBox/com/array.h>
87
88#ifdef VBOX_WITH_NETFLT
89# if defined(RT_OS_SOLARIS)
90# include <zone.h>
91# elif defined(RT_OS_LINUX)
92# include <unistd.h>
93# include <sys/ioctl.h>
94# include <sys/socket.h>
95# include <linux/types.h>
96# include <linux/if.h>
97# include <linux/wireless.h>
98# elif defined(RT_OS_FREEBSD)
99# include <unistd.h>
100# include <sys/types.h>
101# include <sys/ioctl.h>
102# include <sys/socket.h>
103# include <net/if.h>
104# include <net80211/ieee80211_ioctl.h>
105# endif
106# if defined(RT_OS_WINDOWS)
107# include <VBox/VBoxNetCfg-win.h>
108# include <Ntddndis.h>
109# include <devguid.h>
110# else
111# include <HostNetworkInterfaceImpl.h>
112# include <netif.h>
113# include <stdlib.h>
114# endif
115#endif /* VBOX_WITH_NETFLT */
116
117#include "NetworkServiceRunner.h"
118#include "BusAssignmentManager.h"
119#ifdef VBOX_WITH_EXTPACK
120# include "ExtPackManagerImpl.h"
121#endif
122#if defined(RT_OS_DARWIN)
123# include "IOKit/IOKitLib.h"
124#endif
125
126
127/*******************************************************************************
128* Internal Functions *
129*******************************************************************************/
130static Utf8Str *GetExtraDataBoth(IVirtualBox *pVirtualBox, IMachine *pMachine, const char *pszName, Utf8Str *pStrValue);
131
132
133
134#if defined(RT_OS_DARWIN)
135
136static int DarwinSmcKey(char *pabKey, uint32_t cbKey)
137{
138 /*
139 * Method as described in Amit Singh's article:
140 * http://osxbook.com/book/bonus/chapter7/tpmdrmmyth/
141 */
142 typedef struct
143 {
144 uint32_t key;
145 uint8_t pad0[22];
146 uint32_t datasize;
147 uint8_t pad1[10];
148 uint8_t cmd;
149 uint32_t pad2;
150 uint8_t data[32];
151 } AppleSMCBuffer;
152
153 AssertReturn(cbKey >= 65, VERR_INTERNAL_ERROR);
154
155 io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault,
156 IOServiceMatching("AppleSMC"));
157 if (!service)
158 return VERR_NOT_FOUND;
159
160 io_connect_t port = (io_connect_t)0;
161 kern_return_t kr = IOServiceOpen(service, mach_task_self(), 0, &port);
162 IOObjectRelease(service);
163
164 if (kr != kIOReturnSuccess)
165 return RTErrConvertFromDarwin(kr);
166
167 AppleSMCBuffer inputStruct = { 0, {0}, 32, {0}, 5, };
168 AppleSMCBuffer outputStruct;
169 size_t cbOutputStruct = sizeof(outputStruct);
170
171 for (int i = 0; i < 2; i++)
172 {
173 inputStruct.key = (uint32_t)(i == 0 ? 'OSK0' : 'OSK1');
174 kr = IOConnectCallStructMethod((mach_port_t)port,
175 (uint32_t)2,
176 (const void *)&inputStruct,
177 sizeof(inputStruct),
178 (void *)&outputStruct,
179 &cbOutputStruct);
180 if (kr != kIOReturnSuccess)
181 {
182 IOServiceClose(port);
183 return RTErrConvertFromDarwin(kr);
184 }
185
186 for (int j = 0; j < 32; j++)
187 pabKey[j + i*32] = outputStruct.data[j];
188 }
189
190 IOServiceClose(port);
191
192 pabKey[64] = 0;
193
194 return VINF_SUCCESS;
195}
196
197#endif /* RT_OS_DARWIN */
198
199/* Darwin compile kludge */
200#undef PVM
201
202/* Comment out the following line to remove VMWare compatibility hack. */
203#define VMWARE_NET_IN_SLOT_11
204
205/**
206 * Translate IDE StorageControllerType_T to string representation.
207 */
208const char* controllerString(StorageControllerType_T enmType)
209{
210 switch (enmType)
211 {
212 case StorageControllerType_PIIX3:
213 return "PIIX3";
214 case StorageControllerType_PIIX4:
215 return "PIIX4";
216 case StorageControllerType_ICH6:
217 return "ICH6";
218 default:
219 return "Unknown";
220 }
221}
222
223/**
224 * Simple class for storing network boot information.
225 */
226struct BootNic
227{
228 ULONG mInstance;
229 PCIBusAddress mPCIAddress;
230
231 ULONG mBootPrio;
232 bool operator < (const BootNic &rhs) const
233 {
234 ULONG lval = mBootPrio - 1; /* 0 will wrap around and get the lowest priority. */
235 ULONG rval = rhs.mBootPrio - 1;
236 return lval < rval; /* Zero compares as highest number (lowest prio). */
237 }
238};
239
240static int findEfiRom(IVirtualBox* vbox, FirmwareType_T aFirmwareType, Utf8Str *pEfiRomFile)
241{
242 Bstr aFilePath, empty;
243 BOOL fPresent = FALSE;
244 HRESULT hrc = vbox->CheckFirmwarePresent(aFirmwareType, empty.raw(),
245 empty.asOutParam(), aFilePath.asOutParam(), &fPresent);
246 AssertComRCReturn(hrc, Global::vboxStatusCodeFromCOM(hrc));
247
248 if (!fPresent)
249 {
250 LogRel(("Failed to find an EFI ROM file.\n"));
251 return VERR_FILE_NOT_FOUND;
252 }
253
254 *pEfiRomFile = Utf8Str(aFilePath);
255
256 return VINF_SUCCESS;
257}
258
259/**
260 * @throws HRESULT on extra data retrival error.
261 */
262static int getSmcDeviceKey(IVirtualBox *pVirtualBox, IMachine *pMachine, Utf8Str *pStrKey, bool *pfGetKeyFromRealSMC)
263{
264 *pfGetKeyFromRealSMC = false;
265
266 /*
267 * The extra data takes precedence (if non-zero).
268 */
269 GetExtraDataBoth(pVirtualBox, pMachine, "VBoxInternal2/SmcDeviceKey", pStrKey);
270 if (pStrKey->isNotEmpty())
271 return VINF_SUCCESS;
272
273#ifdef RT_OS_DARWIN
274 /*
275 * Query it here and now.
276 */
277 char abKeyBuf[65];
278 int rc = DarwinSmcKey(abKeyBuf, sizeof(abKeyBuf));
279 if (SUCCEEDED(rc))
280 {
281 *pStrKey = abKeyBuf;
282 *pfGetKeyFromRealSMC = true;
283 return rc;
284 }
285 LogRel(("Warning: DarwinSmcKey failed with rc=%Rrc!\n", rc));
286
287#else
288 /*
289 * Is it apple hardware in bootcamp?
290 */
291 /** @todo implement + test RTSYSDMISTR_MANUFACTURER on all hosts.
292 * Currently falling back on the product name. */
293 char szManufacturer[256];
294 szManufacturer[0] = '\0';
295 RTSystemQueryDmiString(RTSYSDMISTR_MANUFACTURER, szManufacturer, sizeof(szManufacturer));
296 if (szManufacturer[0] != '\0')
297 {
298 if ( !strcmp(szManufacturer, "Apple Computer, Inc.")
299 || !strcmp(szManufacturer, "Apple Inc.")
300 )
301 *pfGetKeyFromRealSMC = true;
302 }
303 else
304 {
305 char szProdName[256];
306 szProdName[0] = '\0';
307 RTSystemQueryDmiString(RTSYSDMISTR_PRODUCT_NAME, szProdName, sizeof(szProdName));
308 if ( ( !strncmp(szProdName, RT_STR_TUPLE("Mac"))
309 || !strncmp(szProdName, RT_STR_TUPLE("iMac"))
310 || !strncmp(szProdName, RT_STR_TUPLE("iMac"))
311 || !strncmp(szProdName, RT_STR_TUPLE("Xserve"))
312 )
313 && !strchr(szProdName, ' ') /* no spaces */
314 && RT_C_IS_DIGIT(szProdName[strlen(szProdName) - 1]) /* version number */
315 )
316 *pfGetKeyFromRealSMC = true;
317 }
318
319 int rc = VINF_SUCCESS;
320#endif
321
322 return rc;
323}
324
325
326/*
327 * VC++ 8 / amd64 has some serious trouble with the next functions.
328 * As a temporary measure, we'll drop global optimizations.
329 */
330#if defined(_MSC_VER) && defined(RT_ARCH_AMD64)
331# pragma optimize("g", off)
332#endif
333
334static const char *const g_apszIDEDrives[4] =
335 { "PrimaryMaster", "PrimarySlave", "SecondaryMaster", "SecondarySlave" };
336
337class ConfigError : public RTCError
338{
339public:
340
341 ConfigError(const char *pcszFunction,
342 int vrc,
343 const char *pcszName)
344 : RTCError(Utf8StrFmt("%s failed: rc=%Rrc, pcszName=%s", pcszFunction, vrc, pcszName)),
345 m_vrc(vrc)
346 {
347 AssertMsgFailed(("%s\n", what())); // in strict mode, hit a breakpoint here
348 }
349
350 int m_vrc;
351};
352
353
354/**
355 * Helper that calls CFGMR3InsertString and throws an RTCError if that
356 * fails (C-string variant).
357 * @param pParent See CFGMR3InsertStringN.
358 * @param pcszNodeName See CFGMR3InsertStringN.
359 * @param pcszValue The string value.
360 */
361static void InsertConfigString(PCFGMNODE pNode,
362 const char *pcszName,
363 const char *pcszValue)
364{
365 int vrc = CFGMR3InsertString(pNode,
366 pcszName,
367 pcszValue);
368 if (RT_FAILURE(vrc))
369 throw ConfigError("CFGMR3InsertString", vrc, pcszName);
370}
371
372/**
373 * Helper that calls CFGMR3InsertString and throws an RTCError if that
374 * fails (Utf8Str variant).
375 * @param pParent See CFGMR3InsertStringN.
376 * @param pcszNodeName See CFGMR3InsertStringN.
377 * @param rStrValue The string value.
378 */
379static void InsertConfigString(PCFGMNODE pNode,
380 const char *pcszName,
381 const Utf8Str &rStrValue)
382{
383 int vrc = CFGMR3InsertStringN(pNode,
384 pcszName,
385 rStrValue.c_str(),
386 rStrValue.length());
387 if (RT_FAILURE(vrc))
388 throw ConfigError("CFGMR3InsertStringLengthKnown", vrc, pcszName);
389}
390
391/**
392 * Helper that calls CFGMR3InsertString and throws an RTCError if that
393 * fails (Bstr variant).
394 *
395 * @param pParent See CFGMR3InsertStringN.
396 * @param pcszNodeName See CFGMR3InsertStringN.
397 * @param rBstrValue The string value.
398 */
399static void InsertConfigString(PCFGMNODE pNode,
400 const char *pcszName,
401 const Bstr &rBstrValue)
402{
403 InsertConfigString(pNode, pcszName, Utf8Str(rBstrValue));
404}
405
406/**
407 * Helper that calls CFGMR3InsertBytes and throws an RTCError if that fails.
408 *
409 * @param pNode See CFGMR3InsertBytes.
410 * @param pcszName See CFGMR3InsertBytes.
411 * @param pvBytes See CFGMR3InsertBytes.
412 * @param cbBytes See CFGMR3InsertBytes.
413 */
414static void InsertConfigBytes(PCFGMNODE pNode,
415 const char *pcszName,
416 const void *pvBytes,
417 size_t cbBytes)
418{
419 int vrc = CFGMR3InsertBytes(pNode,
420 pcszName,
421 pvBytes,
422 cbBytes);
423 if (RT_FAILURE(vrc))
424 throw ConfigError("CFGMR3InsertBytes", vrc, pcszName);
425}
426
427/**
428 * Helper that calls CFGMR3InsertInteger and throws an RTCError if that
429 * fails.
430 *
431 * @param pNode See CFGMR3InsertInteger.
432 * @param pcszName See CFGMR3InsertInteger.
433 * @param u64Integer See CFGMR3InsertInteger.
434 */
435static void InsertConfigInteger(PCFGMNODE pNode,
436 const char *pcszName,
437 uint64_t u64Integer)
438{
439 int vrc = CFGMR3InsertInteger(pNode,
440 pcszName,
441 u64Integer);
442 if (RT_FAILURE(vrc))
443 throw ConfigError("CFGMR3InsertInteger", vrc, pcszName);
444}
445
446/**
447 * Helper that calls CFGMR3InsertNode and throws an RTCError if that fails.
448 *
449 * @param pNode See CFGMR3InsertNode.
450 * @param pcszName See CFGMR3InsertNode.
451 * @param ppChild See CFGMR3InsertNode.
452 */
453static void InsertConfigNode(PCFGMNODE pNode,
454 const char *pcszName,
455 PCFGMNODE *ppChild)
456{
457 int vrc = CFGMR3InsertNode(pNode, pcszName, ppChild);
458 if (RT_FAILURE(vrc))
459 throw ConfigError("CFGMR3InsertNode", vrc, pcszName);
460}
461
462/**
463 * Helper that calls CFGMR3RemoveValue and throws an RTCError if that fails.
464 *
465 * @param pNode See CFGMR3RemoveValue.
466 * @param pcszName See CFGMR3RemoveValue.
467 */
468static void RemoveConfigValue(PCFGMNODE pNode,
469 const char *pcszName)
470{
471 int vrc = CFGMR3RemoveValue(pNode, pcszName);
472 if (RT_FAILURE(vrc))
473 throw ConfigError("CFGMR3RemoveValue", vrc, pcszName);
474}
475
476/**
477 * Gets an extra data value, consulting both machine and global extra data.
478 *
479 * @throws HRESULT on failure
480 * @returns pStrValue for the callers convenience.
481 * @param pVirtualBox Pointer to the IVirtualBox interface.
482 * @param pMachine Pointer to the IMachine interface.
483 * @param pszName The value to get.
484 * @param pStrValue Where to return it's value (empty string if not
485 * found).
486 */
487static Utf8Str *GetExtraDataBoth(IVirtualBox *pVirtualBox, IMachine *pMachine, const char *pszName, Utf8Str *pStrValue)
488{
489 pStrValue->setNull();
490
491 Bstr bstrName(pszName);
492 Bstr bstrValue;
493 HRESULT hrc = pMachine->GetExtraData(bstrName.raw(), bstrValue.asOutParam());
494 if (FAILED(hrc))
495 throw hrc;
496 if (bstrValue.isEmpty())
497 {
498 hrc = pVirtualBox->GetExtraData(bstrName.raw(), bstrValue.asOutParam());
499 if (FAILED(hrc))
500 throw hrc;
501 }
502
503 if (bstrValue.isNotEmpty())
504 *pStrValue = bstrValue;
505 return pStrValue;
506}
507
508
509/** Helper that finds out the next SATA port used
510 */
511static LONG GetNextUsedSataPort(LONG aSataPortUsed[30], LONG lBaseVal, uint32_t u32Size)
512{
513 LONG lNextPortUsed = 30;
514 for (size_t j = 0; j < u32Size; ++j)
515 {
516 if ( aSataPortUsed[j] > lBaseVal
517 && aSataPortUsed[j] <= lNextPortUsed)
518 lNextPortUsed = aSataPortUsed[j];
519 }
520 return lNextPortUsed;
521}
522
523#ifdef VBOX_WITH_PCI_PASSTHROUGH
524HRESULT Console::attachRawPCIDevices(PUVM pUVM, BusAssignmentManager *pBusMgr, PCFGMNODE pDevices)
525{
526 HRESULT hrc = S_OK;
527 PCFGMNODE pInst, pCfg, pLunL0, pLunL1;
528
529 SafeIfaceArray<IPCIDeviceAttachment> assignments;
530 ComPtr<IMachine> aMachine = machine();
531
532 hrc = aMachine->COMGETTER(PCIDeviceAssignments)(ComSafeArrayAsOutParam(assignments));
533 if ( hrc != S_OK
534 || assignments.size() < 1)
535 return hrc;
536
537 /*
538 * PCI passthrough is only available if the proper ExtPack is installed.
539 *
540 * Note. Configuring PCI passthrough here and providing messages about
541 * the missing extpack isn't exactly clean, but it is a necessary evil
542 * to patch over legacy compatability issues introduced by the new
543 * distribution model.
544 */
545# ifdef VBOX_WITH_EXTPACK
546 static const char *s_pszPCIRawExtPackName = "Oracle VM VirtualBox Extension Pack";
547 if (!mptrExtPackManager->isExtPackUsable(s_pszPCIRawExtPackName))
548 /* Always fatal! */
549 return VMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
550 N_("Implementation of the PCI passthrough framework not found!\n"
551 "The VM cannot be started. To fix this problem, either "
552 "install the '%s' or disable PCI passthrough via VBoxManage"),
553 s_pszPCIRawExtPackName);
554# endif
555
556 PCFGMNODE pBridges = CFGMR3GetChild(pDevices, "ich9pcibridge");
557 Assert(pBridges);
558
559 /* Find required bridges, and add missing ones */
560 for (size_t iDev = 0; iDev < assignments.size(); iDev++)
561 {
562 ComPtr<IPCIDeviceAttachment> assignment = assignments[iDev];
563 LONG guest = 0;
564 PCIBusAddress GuestPCIAddress;
565
566 assignment->COMGETTER(GuestAddress)(&guest);
567 GuestPCIAddress.fromLong(guest);
568 Assert(GuestPCIAddress.valid());
569
570 if (GuestPCIAddress.miBus > 0)
571 {
572 int iBridgesMissed = 0;
573 int iBase = GuestPCIAddress.miBus - 1;
574
575 while (!pBusMgr->hasPCIDevice("ich9pcibridge", iBase) && iBase > 0)
576 {
577 iBridgesMissed++; iBase--;
578 }
579 iBase++;
580
581 for (int iBridge = 0; iBridge < iBridgesMissed; iBridge++)
582 {
583 InsertConfigNode(pBridges, Utf8StrFmt("%d", iBase + iBridge).c_str(), &pInst);
584 InsertConfigInteger(pInst, "Trusted", 1);
585 hrc = pBusMgr->assignPCIDevice("ich9pcibridge", pInst);
586 }
587 }
588 }
589
590 /* Now actually add devices */
591 PCFGMNODE pPCIDevs = NULL;
592
593 if (assignments.size() > 0)
594 {
595 InsertConfigNode(pDevices, "pciraw", &pPCIDevs);
596
597 PCFGMNODE pRoot = CFGMR3GetParent(pDevices); Assert(pRoot);
598
599 /* Tell PGM to tell GPCIRaw about guest mappings. */
600 CFGMR3InsertNode(pRoot, "PGM", NULL);
601 InsertConfigInteger(CFGMR3GetChild(pRoot, "PGM"), "PciPassThrough", 1);
602
603 /*
604 * Currently, using IOMMU needed for PCI passthrough
605 * requires RAM preallocation.
606 */
607 /** @todo: check if we can lift this requirement */
608 CFGMR3RemoveValue(pRoot, "RamPreAlloc");
609 InsertConfigInteger(pRoot, "RamPreAlloc", 1);
610 }
611
612 for (size_t iDev = 0; iDev < assignments.size(); iDev++)
613 {
614 PCIBusAddress HostPCIAddress, GuestPCIAddress;
615 ComPtr<IPCIDeviceAttachment> assignment = assignments[iDev];
616 LONG host, guest;
617 Bstr aDevName;
618
619 assignment->COMGETTER(HostAddress)(&host);
620 assignment->COMGETTER(GuestAddress)(&guest);
621 assignment->COMGETTER(Name)(aDevName.asOutParam());
622
623 InsertConfigNode(pPCIDevs, Utf8StrFmt("%d", iDev).c_str(), &pInst);
624 InsertConfigInteger(pInst, "Trusted", 1);
625
626 HostPCIAddress.fromLong(host);
627 Assert(HostPCIAddress.valid());
628 InsertConfigNode(pInst, "Config", &pCfg);
629 InsertConfigString(pCfg, "DeviceName", aDevName);
630
631 InsertConfigInteger(pCfg, "DetachHostDriver", 1);
632 InsertConfigInteger(pCfg, "HostPCIBusNo", HostPCIAddress.miBus);
633 InsertConfigInteger(pCfg, "HostPCIDeviceNo", HostPCIAddress.miDevice);
634 InsertConfigInteger(pCfg, "HostPCIFunctionNo", HostPCIAddress.miFn);
635
636 GuestPCIAddress.fromLong(guest);
637 Assert(GuestPCIAddress.valid());
638 hrc = pBusMgr->assignHostPCIDevice("pciraw", pInst, HostPCIAddress, GuestPCIAddress, true);
639 if (hrc != S_OK)
640 return hrc;
641
642 InsertConfigInteger(pCfg, "GuestPCIBusNo", GuestPCIAddress.miBus);
643 InsertConfigInteger(pCfg, "GuestPCIDeviceNo", GuestPCIAddress.miDevice);
644 InsertConfigInteger(pCfg, "GuestPCIFunctionNo", GuestPCIAddress.miFn);
645
646 /* the driver */
647 InsertConfigNode(pInst, "LUN#0", &pLunL0);
648 InsertConfigString(pLunL0, "Driver", "pciraw");
649 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
650
651 /* the Main driver */
652 InsertConfigString(pLunL1, "Driver", "MainPciRaw");
653 InsertConfigNode(pLunL1, "Config", &pCfg);
654 PCIRawDev* pMainDev = new PCIRawDev(this);
655 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMainDev);
656 }
657
658 return hrc;
659}
660#endif
661
662
663void Console::attachStatusDriver(PCFGMNODE pCtlInst, PPDMLED *papLeds,
664 uint64_t uFirst, uint64_t uLast,
665 Console::MediumAttachmentMap *pmapMediumAttachments,
666 const char *pcszDevice, unsigned uInstance)
667{
668 PCFGMNODE pLunL0, pCfg;
669 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
670 InsertConfigString(pLunL0, "Driver", "MainStatus");
671 InsertConfigNode(pLunL0, "Config", &pCfg);
672 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)papLeds);
673 if (pmapMediumAttachments)
674 {
675 InsertConfigInteger(pCfg, "pmapMediumAttachments", (uintptr_t)pmapMediumAttachments);
676 InsertConfigInteger(pCfg, "pConsole", (uintptr_t)this);
677 AssertPtr(pcszDevice);
678 Utf8Str deviceInstance = Utf8StrFmt("%s/%u", pcszDevice, uInstance);
679 InsertConfigString(pCfg, "DeviceInstance", deviceInstance.c_str());
680 }
681 InsertConfigInteger(pCfg, "First", uFirst);
682 InsertConfigInteger(pCfg, "Last", uLast);
683}
684
685
686/**
687 * Construct the VM configuration tree (CFGM).
688 *
689 * This is a callback for VMR3Create() call. It is called from CFGMR3Init()
690 * in the emulation thread (EMT). Any per thread COM/XPCOM initialization
691 * is done here.
692 *
693 * @param pUVM The user mode VM handle.
694 * @param pVM The cross context VM handle.
695 * @param pvConsole Pointer to the VMPowerUpTask object.
696 * @return VBox status code.
697 *
698 * @note Locks the Console object for writing.
699 */
700DECLCALLBACK(int) Console::configConstructor(PUVM pUVM, PVM pVM, void *pvConsole)
701{
702 LogFlowFuncEnter();
703
704 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
705 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
706
707 AutoCaller autoCaller(pConsole);
708 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
709
710 /* lock the console because we widely use internal fields and methods */
711 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
712
713 /*
714 * Set the VM handle and do the rest of the job in an worker method so we
715 * can easily reset the VM handle on failure.
716 */
717 pConsole->mpUVM = pUVM;
718 VMR3RetainUVM(pUVM);
719 int vrc;
720 try
721 {
722 vrc = pConsole->configConstructorInner(pUVM, pVM, &alock);
723 }
724 catch (...)
725 {
726 vrc = VERR_UNEXPECTED_EXCEPTION;
727 }
728 if (RT_FAILURE(vrc))
729 {
730 pConsole->mpUVM = NULL;
731 VMR3ReleaseUVM(pUVM);
732 }
733
734 return vrc;
735}
736
737
738/**
739 * Worker for configConstructor.
740 *
741 * @return VBox status code.
742 * @param pUVM The user mode VM handle.
743 * @param pVM The cross context VM handle.
744 * @param pAlock The automatic lock instance. This is for when we have
745 * to leave it in order to avoid deadlocks (ext packs and
746 * more).
747 */
748int Console::configConstructorInner(PUVM pUVM, PVM pVM, AutoWriteLock *pAlock)
749{
750 VMMDev *pVMMDev = m_pVMMDev; Assert(pVMMDev);
751 ComPtr<IMachine> pMachine = machine();
752
753 int rc;
754 HRESULT hrc;
755 Utf8Str strTmp;
756 Bstr bstr;
757
758#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
759
760 /*
761 * Get necessary objects and frequently used parameters.
762 */
763 ComPtr<IVirtualBox> virtualBox;
764 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
765
766 ComPtr<IHost> host;
767 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
768
769 ComPtr<ISystemProperties> systemProperties;
770 hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam()); H();
771
772 ComPtr<IBIOSSettings> biosSettings;
773 hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam()); H();
774
775 hrc = pMachine->COMGETTER(HardwareUUID)(bstr.asOutParam()); H();
776 RTUUID HardwareUuid;
777 rc = RTUuidFromUtf16(&HardwareUuid, bstr.raw());
778 AssertRCReturn(rc, rc);
779
780 ULONG cRamMBs;
781 hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs); H();
782#if 0 /* enable to play with lots of memory. */
783 if (RTEnvExist("VBOX_RAM_SIZE"))
784 cRamMBs = RTStrToUInt64(RTEnvGet("VBOX_RAM_SIZE"));
785#endif
786 uint64_t const cbRam = cRamMBs * (uint64_t)_1M;
787 uint32_t cbRamHole = MM_RAM_HOLE_SIZE_DEFAULT;
788 uint64_t uMcfgBase = 0;
789 uint32_t cbMcfgLength = 0;
790
791 ChipsetType_T chipsetType;
792 hrc = pMachine->COMGETTER(ChipsetType)(&chipsetType); H();
793 if (chipsetType == ChipsetType_ICH9)
794 {
795 /* We'd better have 0x10000000 region, to cover 256 buses
796 but this put too much load on hypervisor heap */
797 cbMcfgLength = 0x4000000; //0x10000000;
798 cbRamHole += cbMcfgLength;
799 uMcfgBase = _4G - cbRamHole;
800 }
801
802 BusAssignmentManager *pBusMgr = mBusMgr = BusAssignmentManager::createInstance(chipsetType);
803
804 ULONG cCpus = 1;
805 hrc = pMachine->COMGETTER(CPUCount)(&cCpus); H();
806
807 ULONG ulCpuExecutionCap = 100;
808 hrc = pMachine->COMGETTER(CPUExecutionCap)(&ulCpuExecutionCap); H();
809
810 Bstr osTypeId;
811 hrc = pMachine->COMGETTER(OSTypeId)(osTypeId.asOutParam()); H();
812 LogRel(("Guest OS type: '%s'\n", Utf8Str(osTypeId).c_str()));
813
814 BOOL fIOAPIC;
815 hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC); H();
816
817 ComPtr<IGuestOSType> guestOSType;
818 hrc = virtualBox->GetGuestOSType(osTypeId.raw(), guestOSType.asOutParam()); H();
819
820 Bstr guestTypeFamilyId;
821 hrc = guestOSType->COMGETTER(FamilyId)(guestTypeFamilyId.asOutParam()); H();
822 BOOL fOsXGuest = guestTypeFamilyId == Bstr("MacOS");
823
824 ULONG maxNetworkAdapters;
825 hrc = systemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters); H();
826 /*
827 * Get root node first.
828 * This is the only node in the tree.
829 */
830 PCFGMNODE pRoot = CFGMR3GetRootU(pUVM);
831 Assert(pRoot);
832
833 // InsertConfigString throws
834 try
835 {
836
837 /*
838 * Set the root (and VMM) level values.
839 */
840 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
841 InsertConfigString(pRoot, "Name", bstr);
842 InsertConfigBytes(pRoot, "UUID", &HardwareUuid, sizeof(HardwareUuid));
843 InsertConfigInteger(pRoot, "RamSize", cbRam);
844 InsertConfigInteger(pRoot, "RamHoleSize", cbRamHole);
845 InsertConfigInteger(pRoot, "NumCPUs", cCpus);
846 InsertConfigInteger(pRoot, "CpuExecutionCap", ulCpuExecutionCap);
847 InsertConfigInteger(pRoot, "TimerMillies", 10);
848#ifdef VBOX_WITH_RAW_MODE
849 InsertConfigInteger(pRoot, "RawR3Enabled", 1); /* boolean */
850 InsertConfigInteger(pRoot, "RawR0Enabled", 1); /* boolean */
851 /** @todo Config: RawR0, PATMEnabled and CSAMEnabled needs attention later. */
852 InsertConfigInteger(pRoot, "PATMEnabled", 1); /* boolean */
853 InsertConfigInteger(pRoot, "CSAMEnabled", 1); /* boolean */
854#endif
855
856#ifdef VBOX_WITH_RAW_RING1
857 if (osTypeId == "QNX")
858 {
859 /* QNX needs special treatment in raw mode due to its use of ring-1. */
860 InsertConfigInteger(pRoot, "RawR1Enabled", 1); /* boolean */
861 }
862#endif
863
864 /* Not necessary, but to make sure these two settings end up in the release log. */
865 BOOL fPageFusion = FALSE;
866 hrc = pMachine->COMGETTER(PageFusionEnabled)(&fPageFusion); H();
867 InsertConfigInteger(pRoot, "PageFusion", fPageFusion); /* boolean */
868 ULONG ulBalloonSize = 0;
869 hrc = pMachine->COMGETTER(MemoryBalloonSize)(&ulBalloonSize); H();
870 InsertConfigInteger(pRoot, "MemBalloonSize", ulBalloonSize);
871
872 /*
873 * CPUM values.
874 */
875 PCFGMNODE pCPUM;
876 InsertConfigNode(pRoot, "CPUM", &pCPUM);
877
878 /* cpuid leaf overrides. */
879 static uint32_t const s_auCpuIdRanges[] =
880 {
881 UINT32_C(0x00000000), UINT32_C(0x0000000a),
882 UINT32_C(0x80000000), UINT32_C(0x8000000a)
883 };
884 for (unsigned i = 0; i < RT_ELEMENTS(s_auCpuIdRanges); i += 2)
885 for (uint32_t uLeaf = s_auCpuIdRanges[i]; uLeaf < s_auCpuIdRanges[i + 1]; uLeaf++)
886 {
887 ULONG ulEax, ulEbx, ulEcx, ulEdx;
888 hrc = pMachine->GetCPUIDLeaf(uLeaf, &ulEax, &ulEbx, &ulEcx, &ulEdx);
889 if (SUCCEEDED(hrc))
890 {
891 PCFGMNODE pLeaf;
892 InsertConfigNode(pCPUM, Utf8StrFmt("HostCPUID/%RX32", uLeaf).c_str(), &pLeaf);
893
894 InsertConfigInteger(pLeaf, "eax", ulEax);
895 InsertConfigInteger(pLeaf, "ebx", ulEbx);
896 InsertConfigInteger(pLeaf, "ecx", ulEcx);
897 InsertConfigInteger(pLeaf, "edx", ulEdx);
898 }
899 else if (hrc != E_INVALIDARG) H();
900 }
901
902 /* We must limit CPUID count for Windows NT 4, as otherwise it stops
903 with error 0x3e (MULTIPROCESSOR_CONFIGURATION_NOT_SUPPORTED). */
904 if (osTypeId == "WindowsNT4")
905 {
906 LogRel(("Limiting CPUID leaf count for NT4 guests\n"));
907 InsertConfigInteger(pCPUM, "NT4LeafLimit", true);
908 }
909
910 /* Expose CMPXCHG16B. Currently a hack. */
911 if ( osTypeId == "Windows81_64"
912 || osTypeId == "Windows2012_64")
913 {
914 LogRel(("Enabling CMPXCHG16B for Windows 8.1 / 2k12 guests\n"));
915 InsertConfigInteger(pCPUM, "CMPXCHG16B", true);
916 }
917
918 /* Expose extended MWAIT features to Mac OS X guests. */
919 if (fOsXGuest)
920 {
921 LogRel(("Using MWAIT extensions\n"));
922 InsertConfigInteger(pCPUM, "MWaitExtensions", true);
923 }
924
925 if (fOsXGuest)
926 {
927 if ( osTypeId == "MacOS"
928 || osTypeId == "MacOS_x64"
929 || osTypeId >= "MacOS107_x64")
930 InsertConfigInteger(pCPUM, "EnableHVP", 1);
931
932 /* Fake the CPU family/model so the guest works. This is partly
933 because older mac releases really doesn't work on newer cpus,
934 and partly because mac os x expects more from systems with newer
935 cpus (MSRs, power features, whatever). */
936 uint32_t uMaxIntelFamilyModelStep = UINT32_MAX;
937 if ( osTypeId == "MacOS"
938 || osTypeId == "MacOS_x64")
939 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482. */
940 else if ( osTypeId == "MacOS106"
941 || osTypeId == "MacOS106_x64")
942 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */
943 else if ( osTypeId == "MacOS107"
944 || osTypeId == "MacOS107_x64")
945 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */ /** @todo figure out what is required here. */
946 else if ( osTypeId == "MacOS108"
947 || osTypeId == "MacOS108_x64")
948 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */ /** @todo figure out what is required here. */
949 else if ( osTypeId == "MacOS109"
950 || osTypeId == "MacOS109_x64")
951 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */ /** @todo figure out what is required here. */
952 if (uMaxIntelFamilyModelStep != UINT32_MAX)
953 InsertConfigInteger(pCPUM, "MaxIntelFamilyModelStep", uMaxIntelFamilyModelStep);
954 }
955
956
957 /* Synthetic CPU */
958 BOOL fSyntheticCpu = false;
959 hrc = pMachine->GetCPUProperty(CPUPropertyType_Synthetic, &fSyntheticCpu); H();
960 InsertConfigInteger(pCPUM, "SyntheticCpu", fSyntheticCpu);
961
962 /* Physical Address Extension (PAE) */
963 BOOL fEnablePAE = false;
964 hrc = pMachine->GetCPUProperty(CPUPropertyType_PAE, &fEnablePAE); H();
965 InsertConfigInteger(pRoot, "EnablePAE", fEnablePAE);
966
967
968 /*
969 * Hardware virtualization extensions.
970 */
971 BOOL fIsGuest64Bit;
972 hrc = pMachine->GetCPUProperty(CPUPropertyType_LongMode, &fIsGuest64Bit); H();
973 BOOL fSupportsLongMode;
974 hrc = host->GetProcessorFeature(ProcessorFeature_LongMode, &fSupportsLongMode); H();
975 if (!fSupportsLongMode && fIsGuest64Bit)
976 {
977 LogRel(("WARNING! 64-bit guest type selected but the host CPU does NOT support 64-bit.\n"));
978 fIsGuest64Bit = FALSE;
979 }
980
981 BOOL fHMEnabled;
982 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Enabled, &fHMEnabled); H();
983 if (cCpus > 1 && !fHMEnabled)
984 {
985 LogRel(("Forced fHMEnabled to TRUE by SMP guest.\n"));
986 fHMEnabled = TRUE;
987 }
988 if (!fHMEnabled && fIsGuest64Bit)
989 {
990 LogRel(("WARNING! 64-bit guest type selected on host without hardware virtualization (VT-x or AMD-V).\n"));
991 fIsGuest64Bit = FALSE;
992 }
993
994 BOOL fHMForced;
995#ifdef VBOX_WITH_RAW_MODE
996 /* - With more than 4GB PGM will use different RAMRANGE sizes for raw
997 mode and hv mode to optimize lookup times.
998 - With more than one virtual CPU, raw-mode isn't a fallback option.
999 - With a 64-bit guest, raw-mode isn't a fallback option either. */
1000 fHMForced = fHMEnabled
1001 && ( cbRam + cbRamHole > _4G
1002 || cCpus > 1
1003 || fIsGuest64Bit);
1004# ifdef RT_OS_DARWIN
1005 fHMForced = fHMEnabled;
1006# endif
1007 if (fHMForced)
1008 {
1009 if (cbRam + cbRamHole > _4G)
1010 LogRel(("fHMForced=true - Lots of RAM\n"));
1011 if (cCpus > 1)
1012 LogRel(("fHMForced=true - SMP\n"));
1013 if (fIsGuest64Bit)
1014 LogRel(("fHMForced=true - 64-bit guest\n"));
1015# ifdef RT_OS_DARWIN
1016 LogRel(("fHMForced=true - Darwin host\n"));
1017# endif
1018 }
1019#else /* !VBOX_WITH_RAW_MODE */
1020 fHMEnabled = fHMForced = TRUE;
1021 LogRel(("fHMForced=true - No raw-mode support in this build!\n"));
1022#endif /* !VBOX_WITH_RAW_MODE */
1023 if (!fHMForced) /* No need to query if already forced above. */
1024 {
1025 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Force, &fHMForced); H();
1026 if (fHMForced)
1027 LogRel(("fHMForced=true - HWVirtExPropertyType_Force\n"));
1028 }
1029 InsertConfigInteger(pRoot, "HMEnabled", fHMEnabled);
1030
1031 /* /HM/xzy */
1032 PCFGMNODE pHM;
1033 InsertConfigNode(pRoot, "HM", &pHM);
1034 InsertConfigInteger(pRoot, "HMForced", fHMForced);
1035 if (fHMEnabled)
1036 {
1037 /* Indicate whether 64-bit guests are supported or not. */
1038 InsertConfigInteger(pHM, "64bitEnabled", fIsGuest64Bit);
1039#if ARCH_BITS == 32 /* The recompiler must use VBoxREM64 (32-bit host only). */
1040 PCFGMNODE pREM;
1041 InsertConfigNode(pRoot, "REM", &pREM);
1042 InsertConfigInteger(pREM, "64bitEnabled", 1);
1043#endif
1044
1045 /** @todo Not exactly pretty to check strings; VBOXOSTYPE would be better, but that requires quite a bit of API change in Main. */
1046 if ( !fIsGuest64Bit
1047 && fIOAPIC
1048 && ( osTypeId == "WindowsNT4"
1049 || osTypeId == "Windows2000"
1050 || osTypeId == "WindowsXP"
1051 || osTypeId == "Windows2003"))
1052 {
1053 /* Only allow TPR patching for NT, Win2k, XP and Windows Server 2003. (32 bits mode)
1054 * We may want to consider adding more guest OSes (Solaris) later on.
1055 */
1056 InsertConfigInteger(pHM, "TPRPatchingEnabled", 1);
1057 }
1058 }
1059
1060 /* HWVirtEx exclusive mode */
1061 BOOL fHMExclusive = true;
1062 hrc = systemProperties->COMGETTER(ExclusiveHwVirt)(&fHMExclusive); H();
1063 InsertConfigInteger(pHM, "Exclusive", fHMExclusive);
1064
1065 /* Nested paging (VT-x/AMD-V) */
1066 BOOL fEnableNestedPaging = false;
1067 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_NestedPaging, &fEnableNestedPaging); H();
1068 InsertConfigInteger(pHM, "EnableNestedPaging", fEnableNestedPaging);
1069
1070 /* Large pages; requires nested paging */
1071 BOOL fEnableLargePages = false;
1072 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_LargePages, &fEnableLargePages); H();
1073 InsertConfigInteger(pHM, "EnableLargePages", fEnableLargePages);
1074
1075 /* VPID (VT-x) */
1076 BOOL fEnableVPID = false;
1077 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_VPID, &fEnableVPID); H();
1078 InsertConfigInteger(pHM, "EnableVPID", fEnableVPID);
1079
1080 /* Unrestricted execution aka UX (VT-x) */
1081 BOOL fEnableUX = false;
1082 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_UnrestrictedExecution, &fEnableUX); H();
1083 InsertConfigInteger(pHM, "EnableUX", fEnableUX);
1084
1085 /* Reset overwrite. */
1086 if (isResetTurnedIntoPowerOff())
1087 InsertConfigInteger(pRoot, "PowerOffInsteadOfReset", 1);
1088
1089
1090 /*
1091 * MM values.
1092 */
1093 PCFGMNODE pMM;
1094 InsertConfigNode(pRoot, "MM", &pMM);
1095 InsertConfigInteger(pMM, "CanUseLargerHeap", chipsetType == ChipsetType_ICH9);
1096
1097 /*
1098 * PDM config.
1099 * Load drivers in VBoxC.[so|dll]
1100 */
1101 PCFGMNODE pPDM;
1102 PCFGMNODE pNode;
1103 PCFGMNODE pMod;
1104 InsertConfigNode(pRoot, "PDM", &pPDM);
1105 InsertConfigNode(pPDM, "Devices", &pNode);
1106 InsertConfigNode(pPDM, "Drivers", &pNode);
1107 InsertConfigNode(pNode, "VBoxC", &pMod);
1108#ifdef VBOX_WITH_XPCOM
1109 // VBoxC is located in the components subdirectory
1110 char szPathVBoxC[RTPATH_MAX];
1111 rc = RTPathAppPrivateArch(szPathVBoxC, RTPATH_MAX - sizeof("/components/VBoxC")); AssertRC(rc);
1112 strcat(szPathVBoxC, "/components/VBoxC");
1113 InsertConfigString(pMod, "Path", szPathVBoxC);
1114#else
1115 InsertConfigString(pMod, "Path", "VBoxC");
1116#endif
1117
1118
1119 /*
1120 * Block cache settings.
1121 */
1122 PCFGMNODE pPDMBlkCache;
1123 InsertConfigNode(pPDM, "BlkCache", &pPDMBlkCache);
1124
1125 /* I/O cache size */
1126 ULONG ioCacheSize = 5;
1127 hrc = pMachine->COMGETTER(IOCacheSize)(&ioCacheSize); H();
1128 InsertConfigInteger(pPDMBlkCache, "CacheSize", ioCacheSize * _1M);
1129
1130 /*
1131 * Bandwidth groups.
1132 */
1133 PCFGMNODE pAc;
1134 PCFGMNODE pAcFile;
1135 PCFGMNODE pAcFileBwGroups;
1136 ComPtr<IBandwidthControl> bwCtrl;
1137 com::SafeIfaceArray<IBandwidthGroup> bwGroups;
1138
1139 hrc = pMachine->COMGETTER(BandwidthControl)(bwCtrl.asOutParam()); H();
1140
1141 hrc = bwCtrl->GetAllBandwidthGroups(ComSafeArrayAsOutParam(bwGroups)); H();
1142
1143 InsertConfigNode(pPDM, "AsyncCompletion", &pAc);
1144 InsertConfigNode(pAc, "File", &pAcFile);
1145 InsertConfigNode(pAcFile, "BwGroups", &pAcFileBwGroups);
1146#ifdef VBOX_WITH_NETSHAPER
1147 PCFGMNODE pNetworkShaper;
1148 PCFGMNODE pNetworkBwGroups;
1149
1150 InsertConfigNode(pPDM, "NetworkShaper", &pNetworkShaper);
1151 InsertConfigNode(pNetworkShaper, "BwGroups", &pNetworkBwGroups);
1152#endif /* VBOX_WITH_NETSHAPER */
1153
1154 for (size_t i = 0; i < bwGroups.size(); i++)
1155 {
1156 Bstr strName;
1157 LONG64 cMaxBytesPerSec;
1158 BandwidthGroupType_T enmType;
1159
1160 hrc = bwGroups[i]->COMGETTER(Name)(strName.asOutParam()); H();
1161 hrc = bwGroups[i]->COMGETTER(Type)(&enmType); H();
1162 hrc = bwGroups[i]->COMGETTER(MaxBytesPerSec)(&cMaxBytesPerSec); H();
1163
1164 if (enmType == BandwidthGroupType_Disk)
1165 {
1166 PCFGMNODE pBwGroup;
1167 InsertConfigNode(pAcFileBwGroups, Utf8Str(strName).c_str(), &pBwGroup);
1168 InsertConfigInteger(pBwGroup, "Max", cMaxBytesPerSec);
1169 InsertConfigInteger(pBwGroup, "Start", cMaxBytesPerSec);
1170 InsertConfigInteger(pBwGroup, "Step", 0);
1171 }
1172#ifdef VBOX_WITH_NETSHAPER
1173 else if (enmType == BandwidthGroupType_Network)
1174 {
1175 /* Network bandwidth groups. */
1176 PCFGMNODE pBwGroup;
1177 InsertConfigNode(pNetworkBwGroups, Utf8Str(strName).c_str(), &pBwGroup);
1178 InsertConfigInteger(pBwGroup, "Max", cMaxBytesPerSec);
1179 }
1180#endif /* VBOX_WITH_NETSHAPER */
1181 }
1182
1183 /*
1184 * Devices
1185 */
1186 PCFGMNODE pDevices = NULL; /* /Devices */
1187 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
1188 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
1189 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
1190 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
1191 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
1192 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/Config/ */
1193 PCFGMNODE pBiosCfg = NULL; /* /Devices/pcbios/0/Config/ */
1194 PCFGMNODE pNetBootCfg = NULL; /* /Devices/pcbios/0/Config/NetBoot/ */
1195
1196 InsertConfigNode(pRoot, "Devices", &pDevices);
1197
1198 /*
1199 * PC Arch.
1200 */
1201 InsertConfigNode(pDevices, "pcarch", &pDev);
1202 InsertConfigNode(pDev, "0", &pInst);
1203 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1204 InsertConfigNode(pInst, "Config", &pCfg);
1205
1206 /*
1207 * The time offset
1208 */
1209 LONG64 timeOffset;
1210 hrc = biosSettings->COMGETTER(TimeOffset)(&timeOffset); H();
1211 PCFGMNODE pTMNode;
1212 InsertConfigNode(pRoot, "TM", &pTMNode);
1213 InsertConfigInteger(pTMNode, "UTCOffset", timeOffset * 1000000);
1214
1215 /*
1216 * DMA
1217 */
1218 InsertConfigNode(pDevices, "8237A", &pDev);
1219 InsertConfigNode(pDev, "0", &pInst);
1220 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1221
1222 /*
1223 * PCI buses.
1224 */
1225 uint32_t uIocPCIAddress, uHbcPCIAddress;
1226 switch (chipsetType)
1227 {
1228 default:
1229 Assert(false);
1230 case ChipsetType_PIIX3:
1231 InsertConfigNode(pDevices, "pci", &pDev);
1232 uHbcPCIAddress = (0x0 << 16) | 0;
1233 uIocPCIAddress = (0x1 << 16) | 0; // ISA controller
1234 break;
1235 case ChipsetType_ICH9:
1236 InsertConfigNode(pDevices, "ich9pci", &pDev);
1237 uHbcPCIAddress = (0x1e << 16) | 0;
1238 uIocPCIAddress = (0x1f << 16) | 0; // LPC controller
1239 break;
1240 }
1241 InsertConfigNode(pDev, "0", &pInst);
1242 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1243 InsertConfigNode(pInst, "Config", &pCfg);
1244 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1245 if (chipsetType == ChipsetType_ICH9)
1246 {
1247 /* Provide MCFG info */
1248 InsertConfigInteger(pCfg, "McfgBase", uMcfgBase);
1249 InsertConfigInteger(pCfg, "McfgLength", cbMcfgLength);
1250
1251
1252 /* And register 2 bridges */
1253 InsertConfigNode(pDevices, "ich9pcibridge", &pDev);
1254 InsertConfigNode(pDev, "0", &pInst);
1255 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1256 hrc = pBusMgr->assignPCIDevice("ich9pcibridge", pInst); H();
1257
1258 InsertConfigNode(pDev, "1", &pInst);
1259 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1260 hrc = pBusMgr->assignPCIDevice("ich9pcibridge", pInst); H();
1261
1262#ifdef VBOX_WITH_PCI_PASSTHROUGH
1263 /* Add PCI passthrough devices */
1264 hrc = attachRawPCIDevices(pUVM, pBusMgr, pDevices); H();
1265#endif
1266 }
1267
1268 /*
1269 * Enable the following devices: HPET, SMC and LPC on MacOS X guests or on ICH9 chipset
1270 */
1271
1272 /*
1273 * High Precision Event Timer (HPET)
1274 */
1275 BOOL fHPETEnabled;
1276 /* Other guests may wish to use HPET too, but MacOS X not functional without it */
1277 hrc = pMachine->COMGETTER(HPETEnabled)(&fHPETEnabled); H();
1278 /* so always enable HPET in extended profile */
1279 fHPETEnabled |= fOsXGuest;
1280 /* HPET is always present on ICH9 */
1281 fHPETEnabled |= (chipsetType == ChipsetType_ICH9);
1282 if (fHPETEnabled)
1283 {
1284 InsertConfigNode(pDevices, "hpet", &pDev);
1285 InsertConfigNode(pDev, "0", &pInst);
1286 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1287 InsertConfigNode(pInst, "Config", &pCfg);
1288 InsertConfigInteger(pCfg, "ICH9", (chipsetType == ChipsetType_ICH9) ? 1 : 0); /* boolean */
1289 }
1290
1291 /*
1292 * System Management Controller (SMC)
1293 */
1294 BOOL fSmcEnabled;
1295 fSmcEnabled = fOsXGuest;
1296 if (fSmcEnabled)
1297 {
1298 InsertConfigNode(pDevices, "smc", &pDev);
1299 InsertConfigNode(pDev, "0", &pInst);
1300 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1301 InsertConfigNode(pInst, "Config", &pCfg);
1302
1303 bool fGetKeyFromRealSMC;
1304 Utf8Str strKey;
1305 rc = getSmcDeviceKey(virtualBox, pMachine, &strKey, &fGetKeyFromRealSMC);
1306 AssertRCReturn(rc, rc);
1307
1308 InsertConfigString(pCfg, "DeviceKey", strKey);
1309 InsertConfigInteger(pCfg, "GetKeyFromRealSMC", fGetKeyFromRealSMC);
1310 }
1311
1312 /*
1313 * Low Pin Count (LPC) bus
1314 */
1315 BOOL fLpcEnabled;
1316 /** @todo: implement appropriate getter */
1317 fLpcEnabled = fOsXGuest || (chipsetType == ChipsetType_ICH9);
1318 if (fLpcEnabled)
1319 {
1320 InsertConfigNode(pDevices, "lpc", &pDev);
1321 InsertConfigNode(pDev, "0", &pInst);
1322 hrc = pBusMgr->assignPCIDevice("lpc", pInst); H();
1323 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1324 }
1325
1326 BOOL fShowRtc;
1327 fShowRtc = fOsXGuest || (chipsetType == ChipsetType_ICH9);
1328
1329 /*
1330 * PS/2 keyboard & mouse.
1331 */
1332 InsertConfigNode(pDevices, "pckbd", &pDev);
1333 InsertConfigNode(pDev, "0", &pInst);
1334 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1335 InsertConfigNode(pInst, "Config", &pCfg);
1336
1337 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1338 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
1339 InsertConfigNode(pLunL0, "Config", &pCfg);
1340 InsertConfigInteger(pCfg, "QueueSize", 64);
1341
1342 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1343 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
1344 InsertConfigNode(pLunL1, "Config", &pCfg);
1345 Keyboard *pKeyboard = mKeyboard;
1346 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
1347
1348 Mouse *pMouse = mMouse;
1349 PointingHIDType_T aPointingHID;
1350 hrc = pMachine->COMGETTER(PointingHIDType)(&aPointingHID); H();
1351 InsertConfigNode(pInst, "LUN#1", &pLunL0);
1352 InsertConfigString(pLunL0, "Driver", "MouseQueue");
1353 InsertConfigNode(pLunL0, "Config", &pCfg);
1354 InsertConfigInteger(pCfg, "QueueSize", 128);
1355
1356 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1357 InsertConfigString(pLunL1, "Driver", "MainMouse");
1358 InsertConfigNode(pLunL1, "Config", &pCfg);
1359 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
1360
1361 /*
1362 * i8254 Programmable Interval Timer And Dummy Speaker
1363 */
1364 InsertConfigNode(pDevices, "i8254", &pDev);
1365 InsertConfigNode(pDev, "0", &pInst);
1366 InsertConfigNode(pInst, "Config", &pCfg);
1367#ifdef DEBUG
1368 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1369#endif
1370
1371 /*
1372 * i8259 Programmable Interrupt Controller.
1373 */
1374 InsertConfigNode(pDevices, "i8259", &pDev);
1375 InsertConfigNode(pDev, "0", &pInst);
1376 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1377 InsertConfigNode(pInst, "Config", &pCfg);
1378
1379 /*
1380 * Advanced Programmable Interrupt Controller.
1381 * SMP: Each CPU has a LAPIC, but we have a single device representing all LAPICs states,
1382 * thus only single insert
1383 */
1384 InsertConfigNode(pDevices, "apic", &pDev);
1385 InsertConfigNode(pDev, "0", &pInst);
1386 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1387 InsertConfigNode(pInst, "Config", &pCfg);
1388 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1389 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1390
1391 if (fIOAPIC)
1392 {
1393 /*
1394 * I/O Advanced Programmable Interrupt Controller.
1395 */
1396 InsertConfigNode(pDevices, "ioapic", &pDev);
1397 InsertConfigNode(pDev, "0", &pInst);
1398 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1399 InsertConfigNode(pInst, "Config", &pCfg);
1400 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1401 }
1402
1403 /*
1404 * RTC MC146818.
1405 */
1406 InsertConfigNode(pDevices, "mc146818", &pDev);
1407 InsertConfigNode(pDev, "0", &pInst);
1408 InsertConfigNode(pInst, "Config", &pCfg);
1409 BOOL fRTCUseUTC;
1410 hrc = pMachine->COMGETTER(RTCUseUTC)(&fRTCUseUTC); H();
1411 InsertConfigInteger(pCfg, "UseUTC", fRTCUseUTC ? 1 : 0);
1412
1413 /*
1414 * VGA.
1415 */
1416 GraphicsControllerType_T graphicsController;
1417 hrc = pMachine->COMGETTER(GraphicsControllerType)(&graphicsController); H();
1418 switch (graphicsController)
1419 {
1420 case GraphicsControllerType_Null:
1421 break;
1422 case GraphicsControllerType_VBoxVGA:
1423 rc = configGraphicsController(pDevices, "vga", pBusMgr, pMachine, biosSettings,
1424 RT_BOOL(fHMEnabled));
1425 if (FAILED(rc))
1426 return rc;
1427 break;
1428 default:
1429 AssertMsgFailed(("Invalid graphicsController=%d\n", graphicsController));
1430 return VMR3SetError(pUVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1431 N_("Invalid graphics controller type '%d'"), graphicsController);
1432 }
1433
1434 /*
1435 * Firmware.
1436 */
1437 FirmwareType_T eFwType = FirmwareType_BIOS;
1438 hrc = pMachine->COMGETTER(FirmwareType)(&eFwType); H();
1439
1440#ifdef VBOX_WITH_EFI
1441 BOOL fEfiEnabled = (eFwType >= FirmwareType_EFI) && (eFwType <= FirmwareType_EFIDUAL);
1442#else
1443 BOOL fEfiEnabled = false;
1444#endif
1445 if (!fEfiEnabled)
1446 {
1447 /*
1448 * PC Bios.
1449 */
1450 InsertConfigNode(pDevices, "pcbios", &pDev);
1451 InsertConfigNode(pDev, "0", &pInst);
1452 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1453 InsertConfigNode(pInst, "Config", &pBiosCfg);
1454 InsertConfigInteger(pBiosCfg, "RamSize", cbRam);
1455 InsertConfigInteger(pBiosCfg, "RamHoleSize", cbRamHole);
1456 InsertConfigInteger(pBiosCfg, "NumCPUs", cCpus);
1457 InsertConfigString(pBiosCfg, "HardDiskDevice", "piix3ide");
1458 InsertConfigString(pBiosCfg, "FloppyDevice", "i82078");
1459 InsertConfigInteger(pBiosCfg, "IOAPIC", fIOAPIC);
1460 BOOL fPXEDebug;
1461 hrc = biosSettings->COMGETTER(PXEDebugEnabled)(&fPXEDebug); H();
1462 InsertConfigInteger(pBiosCfg, "PXEDebug", fPXEDebug);
1463 InsertConfigBytes(pBiosCfg, "UUID", &HardwareUuid,sizeof(HardwareUuid));
1464 InsertConfigNode(pBiosCfg, "NetBoot", &pNetBootCfg);
1465 InsertConfigInteger(pBiosCfg, "McfgBase", uMcfgBase);
1466 InsertConfigInteger(pBiosCfg, "McfgLength", cbMcfgLength);
1467
1468 DeviceType_T bootDevice;
1469 AssertMsgReturn(SchemaDefs::MaxBootPosition <= 9, ("Too many boot devices %d\n", SchemaDefs::MaxBootPosition),
1470 VERR_INVALID_PARAMETER);
1471
1472 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; ++pos)
1473 {
1474 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
1475
1476 char szParamName[] = "BootDeviceX";
1477 szParamName[sizeof(szParamName) - 2] = ((char (pos - 1)) + '0');
1478
1479 const char *pszBootDevice;
1480 switch (bootDevice)
1481 {
1482 case DeviceType_Null:
1483 pszBootDevice = "NONE";
1484 break;
1485 case DeviceType_HardDisk:
1486 pszBootDevice = "IDE";
1487 break;
1488 case DeviceType_DVD:
1489 pszBootDevice = "DVD";
1490 break;
1491 case DeviceType_Floppy:
1492 pszBootDevice = "FLOPPY";
1493 break;
1494 case DeviceType_Network:
1495 pszBootDevice = "LAN";
1496 break;
1497 default:
1498 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
1499 return VMR3SetError(pUVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1500 N_("Invalid boot device '%d'"), bootDevice);
1501 }
1502 InsertConfigString(pBiosCfg, szParamName, pszBootDevice);
1503 }
1504 }
1505 else
1506 {
1507 /* Autodetect firmware type, basing on guest type */
1508 if (eFwType == FirmwareType_EFI)
1509 {
1510 eFwType = fIsGuest64Bit
1511 ? (FirmwareType_T)FirmwareType_EFI64
1512 : (FirmwareType_T)FirmwareType_EFI32;
1513 }
1514 bool const f64BitEntry = eFwType == FirmwareType_EFI64;
1515
1516 Utf8Str efiRomFile;
1517 rc = findEfiRom(virtualBox, eFwType, &efiRomFile);
1518 AssertRCReturn(rc, rc);
1519
1520 /* Get boot args */
1521 Utf8Str bootArgs;
1522 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiBootArgs", &bootArgs);
1523
1524 /* Get device props */
1525 Utf8Str deviceProps;
1526 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiDeviceProps", &deviceProps);
1527
1528 /* Get GOP mode settings */
1529 uint32_t u32GopMode = UINT32_MAX;
1530 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiGopMode", &strTmp);
1531 if (!strTmp.isEmpty())
1532 u32GopMode = strTmp.toUInt32();
1533
1534 /* UGA mode settings */
1535 uint32_t u32UgaHorisontal = 0;
1536 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiUgaHorizontalResolution", &strTmp);
1537 if (!strTmp.isEmpty())
1538 u32UgaHorisontal = strTmp.toUInt32();
1539
1540 uint32_t u32UgaVertical = 0;
1541 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiUgaVerticalResolution", &strTmp);
1542 if (!strTmp.isEmpty())
1543 u32UgaVertical = strTmp.toUInt32();
1544
1545 /*
1546 * EFI subtree.
1547 */
1548 InsertConfigNode(pDevices, "efi", &pDev);
1549 InsertConfigNode(pDev, "0", &pInst);
1550 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1551 InsertConfigNode(pInst, "Config", &pCfg);
1552 InsertConfigInteger(pCfg, "RamSize", cbRam);
1553 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
1554 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1555 InsertConfigString(pCfg, "EfiRom", efiRomFile);
1556 InsertConfigString(pCfg, "BootArgs", bootArgs);
1557 InsertConfigString(pCfg, "DeviceProps", deviceProps);
1558 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1559 InsertConfigBytes(pCfg, "UUID", &HardwareUuid,sizeof(HardwareUuid));
1560 InsertConfigInteger(pCfg, "64BitEntry", f64BitEntry); /* boolean */
1561 InsertConfigInteger(pCfg, "GopMode", u32GopMode);
1562 InsertConfigInteger(pCfg, "UgaHorizontalResolution", u32UgaHorisontal);
1563 InsertConfigInteger(pCfg, "UgaVerticalResolution", u32UgaVertical);
1564
1565 /* For OS X guests we'll force passing host's DMI info to the guest */
1566 if (fOsXGuest)
1567 {
1568 InsertConfigInteger(pCfg, "DmiUseHostInfo", 1);
1569 InsertConfigInteger(pCfg, "DmiExposeMemoryTable", 1);
1570 }
1571 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1572 InsertConfigString(pLunL0, "Driver", "NvramStorage");
1573 InsertConfigNode(pLunL0, "Config", &pCfg);
1574 InsertConfigInteger(pCfg, "Object", (uintptr_t)mNvram);
1575#ifdef DEBUG_vvl
1576 InsertConfigInteger(pCfg, "PermanentSave", 1);
1577#endif
1578 }
1579
1580 /*
1581 * Storage controllers.
1582 */
1583 com::SafeIfaceArray<IStorageController> ctrls;
1584 PCFGMNODE aCtrlNodes[StorageControllerType_LsiLogicSas + 1] = {};
1585 hrc = pMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls)); H();
1586
1587 bool fFdcEnabled = false;
1588 for (size_t i = 0; i < ctrls.size(); ++i)
1589 {
1590 DeviceType_T *paLedDevType = NULL;
1591
1592 StorageControllerType_T enmCtrlType;
1593 rc = ctrls[i]->COMGETTER(ControllerType)(&enmCtrlType); H();
1594 AssertRelease((unsigned)enmCtrlType < RT_ELEMENTS(aCtrlNodes));
1595
1596 StorageBus_T enmBus;
1597 rc = ctrls[i]->COMGETTER(Bus)(&enmBus); H();
1598
1599 Bstr controllerName;
1600 rc = ctrls[i]->COMGETTER(Name)(controllerName.asOutParam()); H();
1601
1602 ULONG ulInstance = 999;
1603 rc = ctrls[i]->COMGETTER(Instance)(&ulInstance); H();
1604
1605 BOOL fUseHostIOCache;
1606 rc = ctrls[i]->COMGETTER(UseHostIOCache)(&fUseHostIOCache); H();
1607
1608 BOOL fBootable;
1609 rc = ctrls[i]->COMGETTER(Bootable)(&fBootable); H();
1610
1611 /* /Devices/<ctrldev>/ */
1612 const char *pszCtrlDev = convertControllerTypeToDev(enmCtrlType);
1613 pDev = aCtrlNodes[enmCtrlType];
1614 if (!pDev)
1615 {
1616 InsertConfigNode(pDevices, pszCtrlDev, &pDev);
1617 aCtrlNodes[enmCtrlType] = pDev; /* IDE variants are handled in the switch */
1618 }
1619
1620 /* /Devices/<ctrldev>/<instance>/ */
1621 PCFGMNODE pCtlInst = NULL;
1622 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pCtlInst);
1623
1624 /* Device config: /Devices/<ctrldev>/<instance>/<values> & /ditto/Config/<values> */
1625 InsertConfigInteger(pCtlInst, "Trusted", 1);
1626 InsertConfigNode(pCtlInst, "Config", &pCfg);
1627
1628 switch (enmCtrlType)
1629 {
1630 case StorageControllerType_LsiLogic:
1631 {
1632 hrc = pBusMgr->assignPCIDevice("lsilogic", pCtlInst); H();
1633
1634 InsertConfigInteger(pCfg, "Bootable", fBootable);
1635
1636 /* Attach the status driver */
1637 Assert(cLedScsi >= 16);
1638 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedScsi], 0, 15,
1639 &mapMediumAttachments, pszCtrlDev, ulInstance);
1640 paLedDevType = &maStorageDevType[iLedScsi];
1641 break;
1642 }
1643
1644 case StorageControllerType_BusLogic:
1645 {
1646 hrc = pBusMgr->assignPCIDevice("buslogic", pCtlInst); H();
1647
1648 InsertConfigInteger(pCfg, "Bootable", fBootable);
1649
1650 /* Attach the status driver */
1651 Assert(cLedScsi >= 16);
1652 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedScsi], 0, 15,
1653 &mapMediumAttachments, pszCtrlDev, ulInstance);
1654 paLedDevType = &maStorageDevType[iLedScsi];
1655 break;
1656 }
1657
1658 case StorageControllerType_IntelAhci:
1659 {
1660 hrc = pBusMgr->assignPCIDevice("ahci", pCtlInst); H();
1661
1662 ULONG cPorts = 0;
1663 hrc = ctrls[i]->COMGETTER(PortCount)(&cPorts); H();
1664 InsertConfigInteger(pCfg, "PortCount", cPorts);
1665 InsertConfigInteger(pCfg, "Bootable", fBootable);
1666
1667 /* Needed configuration values for the bios, only first controller. */
1668 if (!pBusMgr->hasPCIDevice("ahci", 1))
1669 {
1670#define MAX_SATA_LUN_COUNT 4
1671#define MAX_SATA_PORTS 30
1672
1673 static const char * const s_apszBiosConfig[4] =
1674 { "SataLUN1", "SataLUN2", "SataLUN3", "SataLUN4" };
1675
1676 LONG lPortLUN[MAX_SATA_LUN_COUNT];
1677 LONG lPortUsed[MAX_SATA_PORTS];
1678 uint32_t u32HDSataPortCount = 0;
1679
1680 /* init to max value */
1681 lPortLUN[0] = MAX_SATA_PORTS;
1682
1683 if (pBiosCfg)
1684 {
1685 InsertConfigString(pBiosCfg, "SataHardDiskDevice", "ahci");
1686 }
1687
1688 com::SafeIfaceArray<IMediumAttachment> atts;
1689 hrc = pMachine->GetMediumAttachmentsOfController(controllerName.raw(),
1690 ComSafeArrayAsOutParam(atts)); H();
1691 size_t uNumAttachments = atts.size();
1692 if (uNumAttachments > MAX_SATA_PORTS)
1693 {
1694 LogRel(("Number of Sata Port Attachments > Max=%d.\n", uNumAttachments));
1695 uNumAttachments = MAX_SATA_PORTS;
1696 }
1697
1698 /* find the relavant ports i.e Sata ports to which
1699 * HD is attached.
1700 */
1701 for (size_t j = 0; j < uNumAttachments; ++j)
1702 {
1703 IMediumAttachment *pMediumAtt = atts[j];
1704 LONG lPortNum = 0;
1705 hrc = pMediumAtt->COMGETTER(Port)(&lPortNum); H();
1706 if (SUCCEEDED(hrc))
1707 {
1708 DeviceType_T lType;
1709 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
1710 if (SUCCEEDED(hrc) && lType == DeviceType_HardDisk)
1711 {
1712 /* find min port number used for HD */
1713 if (lPortNum < lPortLUN[0])
1714 lPortLUN[0] = lPortNum;
1715 lPortUsed[u32HDSataPortCount++] = lPortNum;
1716 LogFlowFunc(("HD Sata port Count=%d\n", u32HDSataPortCount));
1717 }
1718 }
1719 }
1720
1721
1722 /* Pick only the top 4 used HD Sata Ports as CMOS doesn't have space
1723 * to save details for every 30 ports
1724 */
1725 uint32_t u32MaxPortCount = MAX_SATA_LUN_COUNT;
1726 if (u32HDSataPortCount < MAX_SATA_LUN_COUNT)
1727 u32MaxPortCount = u32HDSataPortCount;
1728 for (size_t j = 1; j < u32MaxPortCount; j++)
1729 lPortLUN[j] = GetNextUsedSataPort(lPortUsed,
1730 lPortLUN[j-1],
1731 u32HDSataPortCount);
1732 if (pBiosCfg)
1733 {
1734 for (size_t j = 0; j < u32MaxPortCount; j++)
1735 {
1736 InsertConfigInteger(pBiosCfg, s_apszBiosConfig[j], lPortLUN[j]);
1737 LogFlowFunc(("Top %d ports = %s, %d\n", j, s_apszBiosConfig[j], lPortLUN[j]));
1738 }
1739 }
1740 }
1741
1742 /* Attach the status driver */
1743 AssertRelease(cPorts <= cLedSata);
1744 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedSata], 0, cPorts - 1,
1745 &mapMediumAttachments, pszCtrlDev, ulInstance);
1746 paLedDevType = &maStorageDevType[iLedSata];
1747 break;
1748 }
1749
1750 case StorageControllerType_PIIX3:
1751 case StorageControllerType_PIIX4:
1752 case StorageControllerType_ICH6:
1753 {
1754 /*
1755 * IDE (update this when the main interface changes)
1756 */
1757 hrc = pBusMgr->assignPCIDevice("piix3ide", pCtlInst); H();
1758 InsertConfigString(pCfg, "Type", controllerString(enmCtrlType));
1759 /* Attach the status driver */
1760 Assert(cLedIde >= 4);
1761 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedIde], 0, 3,
1762 &mapMediumAttachments, pszCtrlDev, ulInstance);
1763 paLedDevType = &maStorageDevType[iLedIde];
1764
1765 /* IDE flavors */
1766 aCtrlNodes[StorageControllerType_PIIX3] = pDev;
1767 aCtrlNodes[StorageControllerType_PIIX4] = pDev;
1768 aCtrlNodes[StorageControllerType_ICH6] = pDev;
1769 break;
1770 }
1771
1772 case StorageControllerType_I82078:
1773 {
1774 /*
1775 * i82078 Floppy drive controller
1776 */
1777 fFdcEnabled = true;
1778 InsertConfigInteger(pCfg, "IRQ", 6);
1779 InsertConfigInteger(pCfg, "DMA", 2);
1780 InsertConfigInteger(pCfg, "MemMapped", 0 );
1781 InsertConfigInteger(pCfg, "IOBase", 0x3f0);
1782
1783 /* Attach the status driver */
1784 Assert(cLedFloppy >= 2);
1785 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedFloppy], 0, 1,
1786 &mapMediumAttachments, pszCtrlDev, ulInstance);
1787 paLedDevType = &maStorageDevType[iLedFloppy];
1788 break;
1789 }
1790
1791 case StorageControllerType_LsiLogicSas:
1792 {
1793 hrc = pBusMgr->assignPCIDevice("lsilogicsas", pCtlInst); H();
1794
1795 InsertConfigString(pCfg, "ControllerType", "SAS1068");
1796 InsertConfigInteger(pCfg, "Bootable", fBootable);
1797
1798 /* Attach the status driver */
1799 Assert(cLedSas >= 8);
1800 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedSas], 0, 7,
1801 &mapMediumAttachments, pszCtrlDev, ulInstance);
1802 paLedDevType = &maStorageDevType[iLedSas];
1803 break;
1804 }
1805
1806 default:
1807 AssertMsgFailedReturn(("invalid storage controller type: %d\n", enmCtrlType), VERR_GENERAL_FAILURE);
1808 }
1809
1810 /* Attach the media to the storage controllers. */
1811 com::SafeIfaceArray<IMediumAttachment> atts;
1812 hrc = pMachine->GetMediumAttachmentsOfController(controllerName.raw(),
1813 ComSafeArrayAsOutParam(atts)); H();
1814
1815 /* Builtin I/O cache - per device setting. */
1816 BOOL fBuiltinIOCache = true;
1817 hrc = pMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache); H();
1818
1819
1820 for (size_t j = 0; j < atts.size(); ++j)
1821 {
1822 IMediumAttachment *pMediumAtt = atts[j];
1823 rc = configMediumAttachment(pCtlInst,
1824 pszCtrlDev,
1825 ulInstance,
1826 enmBus,
1827 !!fUseHostIOCache,
1828 !!fBuiltinIOCache,
1829 false /* fSetupMerge */,
1830 0 /* uMergeSource */,
1831 0 /* uMergeTarget */,
1832 pMediumAtt,
1833 mMachineState,
1834 NULL /* phrc */,
1835 false /* fAttachDetach */,
1836 false /* fForceUnmount */,
1837 false /* fHotplug */,
1838 pUVM,
1839 paLedDevType);
1840 if (RT_FAILURE(rc))
1841 return rc;
1842 }
1843 H();
1844 }
1845 H();
1846
1847 /*
1848 * Network adapters
1849 */
1850#ifdef VMWARE_NET_IN_SLOT_11
1851 bool fSwapSlots3and11 = false;
1852#endif
1853 PCFGMNODE pDevPCNet = NULL; /* PCNet-type devices */
1854 InsertConfigNode(pDevices, "pcnet", &pDevPCNet);
1855#ifdef VBOX_WITH_E1000
1856 PCFGMNODE pDevE1000 = NULL; /* E1000-type devices */
1857 InsertConfigNode(pDevices, "e1000", &pDevE1000);
1858#endif
1859#ifdef VBOX_WITH_VIRTIO
1860 PCFGMNODE pDevVirtioNet = NULL; /* Virtio network devices */
1861 InsertConfigNode(pDevices, "virtio-net", &pDevVirtioNet);
1862#endif /* VBOX_WITH_VIRTIO */
1863 std::list<BootNic> llBootNics;
1864 for (ULONG ulInstance = 0; ulInstance < maxNetworkAdapters; ++ulInstance)
1865 {
1866 ComPtr<INetworkAdapter> networkAdapter;
1867 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
1868 BOOL fEnabledNetAdapter = FALSE;
1869 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabledNetAdapter); H();
1870 if (!fEnabledNetAdapter)
1871 continue;
1872
1873 /*
1874 * The virtual hardware type. Create appropriate device first.
1875 */
1876 const char *pszAdapterName = "pcnet";
1877 NetworkAdapterType_T adapterType;
1878 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
1879 switch (adapterType)
1880 {
1881 case NetworkAdapterType_Am79C970A:
1882 case NetworkAdapterType_Am79C973:
1883 pDev = pDevPCNet;
1884 break;
1885#ifdef VBOX_WITH_E1000
1886 case NetworkAdapterType_I82540EM:
1887 case NetworkAdapterType_I82543GC:
1888 case NetworkAdapterType_I82545EM:
1889 pDev = pDevE1000;
1890 pszAdapterName = "e1000";
1891 break;
1892#endif
1893#ifdef VBOX_WITH_VIRTIO
1894 case NetworkAdapterType_Virtio:
1895 pDev = pDevVirtioNet;
1896 pszAdapterName = "virtio-net";
1897 break;
1898#endif /* VBOX_WITH_VIRTIO */
1899 default:
1900 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
1901 adapterType, ulInstance));
1902 return VMR3SetError(pUVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1903 N_("Invalid network adapter type '%d' for slot '%d'"),
1904 adapterType, ulInstance);
1905 }
1906
1907 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1908 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1909 /* the first network card gets the PCI ID 3, the next 3 gets 8..10,
1910 * next 4 get 16..19. */
1911 int iPCIDeviceNo;
1912 switch (ulInstance)
1913 {
1914 case 0:
1915 iPCIDeviceNo = 3;
1916 break;
1917 case 1: case 2: case 3:
1918 iPCIDeviceNo = ulInstance - 1 + 8;
1919 break;
1920 case 4: case 5: case 6: case 7:
1921 iPCIDeviceNo = ulInstance - 4 + 16;
1922 break;
1923 default:
1924 /* auto assignment */
1925 iPCIDeviceNo = -1;
1926 break;
1927 }
1928#ifdef VMWARE_NET_IN_SLOT_11
1929 /*
1930 * Dirty hack for PCI slot compatibility with VMWare,
1931 * it assigns slot 0x11 to the first network controller.
1932 */
1933 if (iPCIDeviceNo == 3 && adapterType == NetworkAdapterType_I82545EM)
1934 {
1935 iPCIDeviceNo = 0x11;
1936 fSwapSlots3and11 = true;
1937 }
1938 else if (iPCIDeviceNo == 0x11 && fSwapSlots3and11)
1939 iPCIDeviceNo = 3;
1940#endif
1941 PCIBusAddress PCIAddr = PCIBusAddress(0, iPCIDeviceNo, 0);
1942 hrc = pBusMgr->assignPCIDevice(pszAdapterName, pInst, PCIAddr); H();
1943
1944 InsertConfigNode(pInst, "Config", &pCfg);
1945#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE /* not safe here yet. */ /** @todo Make PCNet ring-0 safe on 32-bit mac kernels! */
1946 if (pDev == pDevPCNet)
1947 {
1948 InsertConfigInteger(pCfg, "R0Enabled", false);
1949 }
1950#endif
1951 /*
1952 * Collect information needed for network booting and add it to the list.
1953 */
1954 BootNic nic;
1955
1956 nic.mInstance = ulInstance;
1957 /* Could be updated by reference, if auto assigned */
1958 nic.mPCIAddress = PCIAddr;
1959
1960 hrc = networkAdapter->COMGETTER(BootPriority)(&nic.mBootPrio); H();
1961
1962 llBootNics.push_back(nic);
1963
1964 /*
1965 * The virtual hardware type. PCNet supports two types.
1966 */
1967 switch (adapterType)
1968 {
1969 case NetworkAdapterType_Am79C970A:
1970 InsertConfigInteger(pCfg, "Am79C973", 0);
1971 break;
1972 case NetworkAdapterType_Am79C973:
1973 InsertConfigInteger(pCfg, "Am79C973", 1);
1974 break;
1975 case NetworkAdapterType_I82540EM:
1976 InsertConfigInteger(pCfg, "AdapterType", 0);
1977 break;
1978 case NetworkAdapterType_I82543GC:
1979 InsertConfigInteger(pCfg, "AdapterType", 1);
1980 break;
1981 case NetworkAdapterType_I82545EM:
1982 InsertConfigInteger(pCfg, "AdapterType", 2);
1983 break;
1984 }
1985
1986 /*
1987 * Get the MAC address and convert it to binary representation
1988 */
1989 Bstr macAddr;
1990 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
1991 Assert(!macAddr.isEmpty());
1992 Utf8Str macAddrUtf8 = macAddr;
1993 char *macStr = (char*)macAddrUtf8.c_str();
1994 Assert(strlen(macStr) == 12);
1995 RTMAC Mac;
1996 RT_ZERO(Mac);
1997 char *pMac = (char*)&Mac;
1998 for (uint32_t i = 0; i < 6; ++i)
1999 {
2000 char c1 = *macStr++ - '0';
2001 if (c1 > 9)
2002 c1 -= 7;
2003 char c2 = *macStr++ - '0';
2004 if (c2 > 9)
2005 c2 -= 7;
2006 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
2007 }
2008 InsertConfigBytes(pCfg, "MAC", &Mac, sizeof(Mac));
2009
2010 /*
2011 * Check if the cable is supposed to be unplugged
2012 */
2013 BOOL fCableConnected;
2014 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
2015 InsertConfigInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0);
2016
2017 /*
2018 * Line speed to report from custom drivers
2019 */
2020 ULONG ulLineSpeed;
2021 hrc = networkAdapter->COMGETTER(LineSpeed)(&ulLineSpeed); H();
2022 InsertConfigInteger(pCfg, "LineSpeed", ulLineSpeed);
2023
2024 /*
2025 * Attach the status driver.
2026 */
2027 attachStatusDriver(pInst, &mapNetworkLeds[ulInstance], 0, 0, NULL, NULL, 0);
2028
2029 /*
2030 * Configure the network card now
2031 */
2032 bool fIgnoreConnectFailure = mMachineState == MachineState_Restoring;
2033 rc = configNetwork(pszAdapterName,
2034 ulInstance,
2035 0,
2036 networkAdapter,
2037 pCfg,
2038 pLunL0,
2039 pInst,
2040 false /*fAttachDetach*/,
2041 fIgnoreConnectFailure);
2042 if (RT_FAILURE(rc))
2043 return rc;
2044 }
2045
2046 /*
2047 * Build network boot information and transfer it to the BIOS.
2048 */
2049 if (pNetBootCfg && !llBootNics.empty()) /* NetBoot node doesn't exist for EFI! */
2050 {
2051 llBootNics.sort(); /* Sort the list by boot priority. */
2052
2053 char achBootIdx[] = "0";
2054 unsigned uBootIdx = 0;
2055
2056 for (std::list<BootNic>::iterator it = llBootNics.begin(); it != llBootNics.end(); ++it)
2057 {
2058 /* A NIC with priority 0 is only used if it's first in the list. */
2059 if (it->mBootPrio == 0 && uBootIdx != 0)
2060 break;
2061
2062 PCFGMNODE pNetBtDevCfg;
2063 achBootIdx[0] = '0' + uBootIdx++; /* Boot device order. */
2064 InsertConfigNode(pNetBootCfg, achBootIdx, &pNetBtDevCfg);
2065 InsertConfigInteger(pNetBtDevCfg, "NIC", it->mInstance);
2066 InsertConfigInteger(pNetBtDevCfg, "PCIBusNo", it->mPCIAddress.miBus);
2067 InsertConfigInteger(pNetBtDevCfg, "PCIDeviceNo", it->mPCIAddress.miDevice);
2068 InsertConfigInteger(pNetBtDevCfg, "PCIFunctionNo", it->mPCIAddress.miFn);
2069 }
2070 }
2071
2072 /*
2073 * Serial (UART) Ports
2074 */
2075 /* serial enabled mask to be passed to dev ACPI */
2076 uint16_t auSerialIoPortBase[SchemaDefs::SerialPortCount] = {0};
2077 uint8_t auSerialIrq[SchemaDefs::SerialPortCount] = {0};
2078 InsertConfigNode(pDevices, "serial", &pDev);
2079 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ++ulInstance)
2080 {
2081 ComPtr<ISerialPort> serialPort;
2082 hrc = pMachine->GetSerialPort(ulInstance, serialPort.asOutParam()); H();
2083 BOOL fEnabledSerPort = FALSE;
2084 if (serialPort)
2085 hrc = serialPort->COMGETTER(Enabled)(&fEnabledSerPort); H();
2086 if (!fEnabledSerPort)
2087 continue;
2088
2089 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
2090 InsertConfigNode(pInst, "Config", &pCfg);
2091
2092 ULONG ulIRQ;
2093 hrc = serialPort->COMGETTER(IRQ)(&ulIRQ); H();
2094 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
2095 auSerialIrq[ulInstance] = (uint8_t)ulIRQ;
2096
2097 ULONG ulIOBase;
2098 hrc = serialPort->COMGETTER(IOBase)(&ulIOBase); H();
2099 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
2100 auSerialIoPortBase[ulInstance] = (uint16_t)ulIOBase;
2101
2102 BOOL fServer;
2103 hrc = serialPort->COMGETTER(Server)(&fServer); H();
2104 hrc = serialPort->COMGETTER(Path)(bstr.asOutParam()); H();
2105 PortMode_T eHostMode;
2106 hrc = serialPort->COMGETTER(HostMode)(&eHostMode); H();
2107 if (eHostMode != PortMode_Disconnected)
2108 {
2109 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2110 if (eHostMode == PortMode_HostPipe)
2111 {
2112 InsertConfigString(pLunL0, "Driver", "Char");
2113 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2114 InsertConfigString(pLunL1, "Driver", "NamedPipe");
2115 InsertConfigNode(pLunL1, "Config", &pLunL2);
2116 InsertConfigString(pLunL2, "Location", bstr);
2117 InsertConfigInteger(pLunL2, "IsServer", fServer);
2118 }
2119 else if (eHostMode == PortMode_HostDevice)
2120 {
2121 InsertConfigString(pLunL0, "Driver", "Host Serial");
2122 InsertConfigNode(pLunL0, "Config", &pLunL1);
2123 InsertConfigString(pLunL1, "DevicePath", bstr);
2124 }
2125 else if (eHostMode == PortMode_RawFile)
2126 {
2127 InsertConfigString(pLunL0, "Driver", "Char");
2128 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2129 InsertConfigString(pLunL1, "Driver", "RawFile");
2130 InsertConfigNode(pLunL1, "Config", &pLunL2);
2131 InsertConfigString(pLunL2, "Location", bstr);
2132 }
2133 }
2134 }
2135
2136 /*
2137 * Parallel (LPT) Ports
2138 */
2139 InsertConfigNode(pDevices, "parallel", &pDev);
2140 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ++ulInstance)
2141 {
2142 ComPtr<IParallelPort> parallelPort;
2143 hrc = pMachine->GetParallelPort(ulInstance, parallelPort.asOutParam()); H();
2144 BOOL fEnabledParPort = FALSE;
2145 if (parallelPort)
2146 {
2147 hrc = parallelPort->COMGETTER(Enabled)(&fEnabledParPort); H();
2148 }
2149 if (!fEnabledParPort)
2150 continue;
2151
2152 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
2153 InsertConfigNode(pInst, "Config", &pCfg);
2154
2155 ULONG ulIRQ;
2156 hrc = parallelPort->COMGETTER(IRQ)(&ulIRQ); H();
2157 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
2158 ULONG ulIOBase;
2159 hrc = parallelPort->COMGETTER(IOBase)(&ulIOBase); H();
2160 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
2161 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2162 InsertConfigString(pLunL0, "Driver", "HostParallel");
2163 InsertConfigNode(pLunL0, "Config", &pLunL1);
2164 hrc = parallelPort->COMGETTER(Path)(bstr.asOutParam()); H();
2165 InsertConfigString(pLunL1, "DevicePath", bstr);
2166 }
2167
2168 /*
2169 * VMM Device
2170 */
2171 InsertConfigNode(pDevices, "VMMDev", &pDev);
2172 InsertConfigNode(pDev, "0", &pInst);
2173 InsertConfigNode(pInst, "Config", &pCfg);
2174 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2175 hrc = pBusMgr->assignPCIDevice("VMMDev", pInst); H();
2176
2177 Bstr hwVersion;
2178 hrc = pMachine->COMGETTER(HardwareVersion)(hwVersion.asOutParam()); H();
2179 InsertConfigInteger(pCfg, "RamSize", cbRam);
2180 if (hwVersion.compare(Bstr("1").raw()) == 0) /* <= 2.0.x */
2181 InsertConfigInteger(pCfg, "HeapEnabled", 0);
2182 Bstr snapshotFolder;
2183 hrc = pMachine->COMGETTER(SnapshotFolder)(snapshotFolder.asOutParam()); H();
2184 InsertConfigString(pCfg, "GuestCoreDumpDir", snapshotFolder);
2185
2186 /* the VMM device's Main driver */
2187 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2188 InsertConfigString(pLunL0, "Driver", "HGCM");
2189 InsertConfigNode(pLunL0, "Config", &pCfg);
2190 InsertConfigInteger(pCfg, "Object", (uintptr_t)pVMMDev);
2191
2192 /*
2193 * Attach the status driver.
2194 */
2195 attachStatusDriver(pInst, &mapSharedFolderLed, 0, 0, NULL, NULL, 0);
2196
2197 /*
2198 * Audio Sniffer Device
2199 */
2200 InsertConfigNode(pDevices, "AudioSniffer", &pDev);
2201 InsertConfigNode(pDev, "0", &pInst);
2202 InsertConfigNode(pInst, "Config", &pCfg);
2203
2204 /* the Audio Sniffer device's Main driver */
2205 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2206 InsertConfigString(pLunL0, "Driver", "MainAudioSniffer");
2207 InsertConfigNode(pLunL0, "Config", &pCfg);
2208 AudioSniffer *pAudioSniffer = mAudioSniffer;
2209 InsertConfigInteger(pCfg, "Object", (uintptr_t)pAudioSniffer);
2210
2211 /*
2212 * AC'97 ICH / SoundBlaster16 audio / Intel HD Audio
2213 */
2214 BOOL fAudioEnabled = FALSE;
2215 ComPtr<IAudioAdapter> audioAdapter;
2216 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
2217 if (audioAdapter)
2218 hrc = audioAdapter->COMGETTER(Enabled)(&fAudioEnabled); H();
2219
2220 if (fAudioEnabled)
2221 {
2222 AudioControllerType_T audioController;
2223 hrc = audioAdapter->COMGETTER(AudioController)(&audioController); H();
2224 switch (audioController)
2225 {
2226 case AudioControllerType_AC97:
2227 {
2228 /* default: ICH AC97 */
2229 InsertConfigNode(pDevices, "ichac97", &pDev);
2230 InsertConfigNode(pDev, "0", &pInst);
2231 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2232 hrc = pBusMgr->assignPCIDevice("ichac97", pInst); H();
2233 InsertConfigNode(pInst, "Config", &pCfg);
2234 break;
2235 }
2236 case AudioControllerType_SB16:
2237 {
2238 /* legacy SoundBlaster16 */
2239 InsertConfigNode(pDevices, "sb16", &pDev);
2240 InsertConfigNode(pDev, "0", &pInst);
2241 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2242 InsertConfigNode(pInst, "Config", &pCfg);
2243 InsertConfigInteger(pCfg, "IRQ", 5);
2244 InsertConfigInteger(pCfg, "DMA", 1);
2245 InsertConfigInteger(pCfg, "DMA16", 5);
2246 InsertConfigInteger(pCfg, "Port", 0x220);
2247 InsertConfigInteger(pCfg, "Version", 0x0405);
2248 break;
2249 }
2250 case AudioControllerType_HDA:
2251 {
2252 /* Intel HD Audio */
2253 InsertConfigNode(pDevices, "hda", &pDev);
2254 InsertConfigNode(pDev, "0", &pInst);
2255 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2256 hrc = pBusMgr->assignPCIDevice("hda", pInst); H();
2257 InsertConfigNode(pInst, "Config", &pCfg);
2258 }
2259 }
2260
2261 /* the Audio driver */
2262 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2263 InsertConfigString(pLunL0, "Driver", "AUDIO");
2264 InsertConfigNode(pLunL0, "Config", &pCfg);
2265
2266 AudioDriverType_T audioDriver;
2267 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
2268 switch (audioDriver)
2269 {
2270 case AudioDriverType_Null:
2271 {
2272 InsertConfigString(pCfg, "AudioDriver", "null");
2273 break;
2274 }
2275#ifdef RT_OS_WINDOWS
2276#ifdef VBOX_WITH_WINMM
2277 case AudioDriverType_WinMM:
2278 {
2279 InsertConfigString(pCfg, "AudioDriver", "winmm");
2280 break;
2281 }
2282#endif
2283 case AudioDriverType_DirectSound:
2284 {
2285 InsertConfigString(pCfg, "AudioDriver", "dsound");
2286 break;
2287 }
2288#endif /* RT_OS_WINDOWS */
2289#ifdef RT_OS_SOLARIS
2290 case AudioDriverType_SolAudio:
2291 {
2292 InsertConfigString(pCfg, "AudioDriver", "solaudio");
2293 break;
2294 }
2295#endif
2296#ifdef RT_OS_LINUX
2297# ifdef VBOX_WITH_ALSA
2298 case AudioDriverType_ALSA:
2299 {
2300 InsertConfigString(pCfg, "AudioDriver", "alsa");
2301 break;
2302 }
2303# endif
2304# ifdef VBOX_WITH_PULSE
2305 case AudioDriverType_Pulse:
2306 {
2307 InsertConfigString(pCfg, "AudioDriver", "pulse");
2308 break;
2309 }
2310# endif
2311#endif /* RT_OS_LINUX */
2312#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
2313 case AudioDriverType_OSS:
2314 {
2315 InsertConfigString(pCfg, "AudioDriver", "oss");
2316 break;
2317 }
2318#endif
2319#ifdef RT_OS_FREEBSD
2320# ifdef VBOX_WITH_PULSE
2321 case AudioDriverType_Pulse:
2322 {
2323 InsertConfigString(pCfg, "AudioDriver", "pulse");
2324 break;
2325 }
2326# endif
2327#endif
2328#ifdef RT_OS_DARWIN
2329 case AudioDriverType_CoreAudio:
2330 {
2331 InsertConfigString(pCfg, "AudioDriver", "coreaudio");
2332 break;
2333 }
2334#endif
2335 }
2336 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
2337 InsertConfigString(pCfg, "StreamName", bstr);
2338 }
2339
2340 /*
2341 * The USB Controllers.
2342 */
2343 com::SafeIfaceArray<IUSBController> usbCtrls;
2344 hrc = pMachine->COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbCtrls)); H();
2345 bool fOhciPresent = false; /**< Flag whether at least one OHCI controller is presnet. */
2346
2347 for (size_t i = 0; i < usbCtrls.size(); ++i)
2348 {
2349 USBControllerType_T enmCtrlType;
2350 rc = usbCtrls[i]->COMGETTER(Type)(&enmCtrlType); H();
2351 if (enmCtrlType == USBControllerType_OHCI)
2352 {
2353 fOhciPresent = true;
2354 break;
2355 }
2356 }
2357
2358 /*
2359 * Currently EHCI is only enabled when a OHCI controller is present too.
2360 * This might change when XHCI is supported.
2361 */
2362 if (fOhciPresent)
2363 mfVMHasUsbController = true;
2364
2365 if (mfVMHasUsbController)
2366 {
2367 for (size_t i = 0; i < usbCtrls.size(); ++i)
2368 {
2369 USBControllerType_T enmCtrlType;
2370 rc = usbCtrls[i]->COMGETTER(Type)(&enmCtrlType); H();
2371
2372 if (enmCtrlType == USBControllerType_OHCI)
2373 {
2374 InsertConfigNode(pDevices, "usb-ohci", &pDev);
2375 InsertConfigNode(pDev, "0", &pInst);
2376 InsertConfigNode(pInst, "Config", &pCfg);
2377 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2378 hrc = pBusMgr->assignPCIDevice("usb-ohci", pInst); H();
2379 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2380 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2381 InsertConfigNode(pLunL0, "Config", &pCfg);
2382
2383 /*
2384 * Attach the status driver.
2385 */
2386 attachStatusDriver(pInst, &mapUSBLed[0], 0, 0, NULL, NULL, 0);
2387 }
2388#ifdef VBOX_WITH_EHCI
2389 else if (enmCtrlType == USBControllerType_EHCI)
2390 {
2391 /*
2392 * USB 2.0 is only available if the proper ExtPack is installed.
2393 *
2394 * Note. Configuring EHCI here and providing messages about
2395 * the missing extpack isn't exactly clean, but it is a
2396 * necessary evil to patch over legacy compatability issues
2397 * introduced by the new distribution model.
2398 */
2399 static const char *s_pszUsbExtPackName = "Oracle VM VirtualBox Extension Pack";
2400# ifdef VBOX_WITH_EXTPACK
2401 if (mptrExtPackManager->isExtPackUsable(s_pszUsbExtPackName))
2402# endif
2403 {
2404 InsertConfigNode(pDevices, "usb-ehci", &pDev);
2405 InsertConfigNode(pDev, "0", &pInst);
2406 InsertConfigNode(pInst, "Config", &pCfg);
2407 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2408 hrc = pBusMgr->assignPCIDevice("usb-ehci", pInst); H();
2409
2410 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2411 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2412 InsertConfigNode(pLunL0, "Config", &pCfg);
2413
2414 /*
2415 * Attach the status driver.
2416 */
2417 attachStatusDriver(pInst, &mapUSBLed[1], 0, 0, NULL, NULL, 0);
2418 }
2419# ifdef VBOX_WITH_EXTPACK
2420 else
2421 {
2422 /* Always fatal! Up to VBox 4.0.4 we allowed to start the VM anyway
2423 * but this induced problems when the user saved + restored the VM! */
2424 return VMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
2425 N_("Implementation of the USB 2.0 controller not found!\n"
2426 "Because the USB 2.0 controller state is part of the saved "
2427 "VM state, the VM cannot be started. To fix "
2428 "this problem, either install the '%s' or disable USB 2.0 "
2429 "support in the VM settings"),
2430 s_pszUsbExtPackName);
2431 }
2432# endif
2433 }
2434#endif
2435 } /* for every USB controller. */
2436
2437
2438 /*
2439 * Virtual USB Devices.
2440 */
2441 PCFGMNODE pUsbDevices = NULL;
2442 InsertConfigNode(pRoot, "USB", &pUsbDevices);
2443
2444#ifdef VBOX_WITH_USB
2445 {
2446 /*
2447 * Global USB options, currently unused as we'll apply the 2.0 -> 1.1 morphing
2448 * on a per device level now.
2449 */
2450 InsertConfigNode(pUsbDevices, "USBProxy", &pCfg);
2451 InsertConfigNode(pCfg, "GlobalConfig", &pCfg);
2452 // This globally enables the 2.0 -> 1.1 device morphing of proxied devices to keep windows quiet.
2453 //InsertConfigInteger(pCfg, "Force11Device", true);
2454 // The following breaks stuff, but it makes MSDs work in vista. (I include it here so
2455 // that it's documented somewhere.) Users needing it can use:
2456 // VBoxManage setextradata "myvm" "VBoxInternal/USB/USBProxy/GlobalConfig/Force11PacketSize" 1
2457 //InsertConfigInteger(pCfg, "Force11PacketSize", true);
2458 }
2459#endif
2460
2461#ifdef VBOX_WITH_USB_CARDREADER
2462 BOOL aEmulatedUSBCardReaderEnabled = FALSE;
2463 hrc = pMachine->COMGETTER(EmulatedUSBCardReaderEnabled)(&aEmulatedUSBCardReaderEnabled); H();
2464 if (aEmulatedUSBCardReaderEnabled)
2465 {
2466 InsertConfigNode(pUsbDevices, "CardReader", &pDev);
2467 InsertConfigNode(pDev, "0", &pInst);
2468 InsertConfigNode(pInst, "Config", &pCfg);
2469
2470 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2471# ifdef VBOX_WITH_USB_CARDREADER_TEST
2472 InsertConfigString(pLunL0, "Driver", "DrvDirectCardReader");
2473 InsertConfigNode(pLunL0, "Config", &pCfg);
2474# else
2475 InsertConfigString(pLunL0, "Driver", "UsbCardReader");
2476 InsertConfigNode(pLunL0, "Config", &pCfg);
2477 InsertConfigInteger(pCfg, "Object", (uintptr_t)mUsbCardReader);
2478# endif
2479 }
2480#endif
2481
2482# if 0 /* Virtual MSD*/
2483 InsertConfigNode(pUsbDevices, "Msd", &pDev);
2484 InsertConfigNode(pDev, "0", &pInst);
2485 InsertConfigNode(pInst, "Config", &pCfg);
2486 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2487
2488 InsertConfigString(pLunL0, "Driver", "SCSI");
2489 InsertConfigNode(pLunL0, "Config", &pCfg);
2490
2491 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2492 InsertConfigString(pLunL1, "Driver", "Block");
2493 InsertConfigNode(pLunL1, "Config", &pCfg);
2494 InsertConfigString(pCfg, "Type", "HardDisk");
2495 InsertConfigInteger(pCfg, "Mountable", 0);
2496
2497 InsertConfigNode(pLunL1, "AttachedDriver", &pLunL2);
2498 InsertConfigString(pLunL2, "Driver", "VD");
2499 InsertConfigNode(pLunL2, "Config", &pCfg);
2500 InsertConfigString(pCfg, "Path", "/Volumes/DataHFS/bird/VDIs/linux.vdi");
2501 InsertConfigString(pCfg, "Format", "VDI");
2502# endif
2503
2504 /* Virtual USB Mouse/Tablet */
2505 if ( aPointingHID == PointingHIDType_USBMouse
2506 || aPointingHID == PointingHIDType_ComboMouse
2507 || aPointingHID == PointingHIDType_USBTablet
2508 || aPointingHID == PointingHIDType_USBMultiTouch)
2509 InsertConfigNode(pUsbDevices, "HidMouse", &pDev);
2510 if (aPointingHID == PointingHIDType_USBMouse)
2511 {
2512 InsertConfigNode(pDev, "0", &pInst);
2513 InsertConfigNode(pInst, "Config", &pCfg);
2514
2515 InsertConfigString(pCfg, "Mode", "relative");
2516 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2517 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2518 InsertConfigNode(pLunL0, "Config", &pCfg);
2519 InsertConfigInteger(pCfg, "QueueSize", 128);
2520
2521 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2522 InsertConfigString(pLunL1, "Driver", "MainMouse");
2523 InsertConfigNode(pLunL1, "Config", &pCfg);
2524 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2525 }
2526 if ( aPointingHID == PointingHIDType_USBTablet
2527 || aPointingHID == PointingHIDType_USBMultiTouch)
2528 {
2529 InsertConfigNode(pDev, "1", &pInst);
2530 InsertConfigNode(pInst, "Config", &pCfg);
2531
2532 InsertConfigString(pCfg, "Mode", "absolute");
2533 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2534 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2535 InsertConfigNode(pLunL0, "Config", &pCfg);
2536 InsertConfigInteger(pCfg, "QueueSize", 128);
2537
2538 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2539 InsertConfigString(pLunL1, "Driver", "MainMouse");
2540 InsertConfigNode(pLunL1, "Config", &pCfg);
2541 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2542 }
2543 if (aPointingHID == PointingHIDType_USBMultiTouch)
2544 {
2545 InsertConfigNode(pDev, "2", &pInst);
2546 InsertConfigNode(pInst, "Config", &pCfg);
2547
2548 InsertConfigString(pCfg, "Mode", "multitouch");
2549 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2550 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2551 InsertConfigNode(pLunL0, "Config", &pCfg);
2552 InsertConfigInteger(pCfg, "QueueSize", 128);
2553
2554 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2555 InsertConfigString(pLunL1, "Driver", "MainMouse");
2556 InsertConfigNode(pLunL1, "Config", &pCfg);
2557 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2558 }
2559
2560 /* Virtual USB Keyboard */
2561 KeyboardHIDType_T aKbdHID;
2562 hrc = pMachine->COMGETTER(KeyboardHIDType)(&aKbdHID); H();
2563 if (aKbdHID == KeyboardHIDType_USBKeyboard)
2564 {
2565 InsertConfigNode(pUsbDevices, "HidKeyboard", &pDev);
2566 InsertConfigNode(pDev, "0", &pInst);
2567 InsertConfigNode(pInst, "Config", &pCfg);
2568
2569 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2570 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
2571 InsertConfigNode(pLunL0, "Config", &pCfg);
2572 InsertConfigInteger(pCfg, "QueueSize", 64);
2573
2574 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2575 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
2576 InsertConfigNode(pLunL1, "Config", &pCfg);
2577 pKeyboard = mKeyboard;
2578 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
2579 }
2580 }
2581
2582 /*
2583 * Clipboard
2584 */
2585 {
2586 ClipboardMode_T mode = ClipboardMode_Disabled;
2587 hrc = pMachine->COMGETTER(ClipboardMode)(&mode); H();
2588
2589 if (/* mode != ClipboardMode_Disabled */ true)
2590 {
2591 /* Load the service */
2592 rc = pVMMDev->hgcmLoadService("VBoxSharedClipboard", "VBoxSharedClipboard");
2593
2594 if (RT_FAILURE(rc))
2595 {
2596 LogRel(("VBoxSharedClipboard is not available. rc = %Rrc\n", rc));
2597 /* That is not a fatal failure. */
2598 rc = VINF_SUCCESS;
2599 }
2600 else
2601 {
2602 changeClipboardMode(mode);
2603
2604 /* Setup the service. */
2605 VBOXHGCMSVCPARM parm;
2606 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
2607 parm.setUInt32(!useHostClipboard());
2608 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS, 1, &parm);
2609
2610 Log(("Set VBoxSharedClipboard mode\n"));
2611 }
2612 }
2613 }
2614
2615 /*
2616 * HGCM HostChannel
2617 */
2618 {
2619 Bstr value;
2620 hrc = pMachine->GetExtraData(Bstr("HGCM/HostChannel").raw(),
2621 value.asOutParam());
2622
2623 if ( hrc == S_OK
2624 && value == "1")
2625 {
2626 rc = pVMMDev->hgcmLoadService("VBoxHostChannel", "VBoxHostChannel");
2627
2628 if (RT_FAILURE(rc))
2629 {
2630 LogRel(("VBoxHostChannel is not available. rc = %Rrc\n", rc));
2631 /* That is not a fatal failure. */
2632 rc = VINF_SUCCESS;
2633 }
2634 }
2635 }
2636
2637#ifdef VBOX_WITH_DRAG_AND_DROP
2638 /*
2639 * Drag & Drop
2640 */
2641 {
2642 DragAndDropMode_T mode = DragAndDropMode_Disabled;
2643 hrc = pMachine->COMGETTER(DragAndDropMode)(&mode); H();
2644
2645 /* Load the service */
2646 rc = pVMMDev->hgcmLoadService("VBoxDragAndDropSvc", "VBoxDragAndDropSvc");
2647
2648 if (RT_FAILURE(rc))
2649 {
2650 LogRel(("VBoxDragAndDropService is not available. rc = %Rrc\n", rc));
2651 /* That is not a fatal failure. */
2652 rc = VINF_SUCCESS;
2653 }
2654 else
2655 {
2656 HGCMSVCEXTHANDLE hDummy;
2657 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxDragAndDropSvc",
2658 &GuestDnD::notifyGuestDragAndDropEvent,
2659 getGuest());
2660 if (RT_FAILURE(rc))
2661 Log(("Cannot register VBoxDragAndDropSvc extension!\n"));
2662 else
2663 {
2664 changeDragAndDropMode(mode);
2665 Log(("VBoxDragAndDropSvc loaded\n"));
2666 }
2667 }
2668 }
2669#endif /* VBOX_WITH_DRAG_AND_DROP */
2670
2671#ifdef VBOX_WITH_CROGL
2672 /*
2673 * crOpenGL
2674 */
2675 {
2676 BOOL fEnabled3D = false;
2677 hrc = pMachine->COMGETTER(Accelerate3DEnabled)(&fEnabled3D); H();
2678
2679 if (fEnabled3D)
2680 {
2681 BOOL fSupports3D = VBoxOglIs3DAccelerationSupported();
2682 if (!fSupports3D)
2683 return VMR3SetError(pUVM, VERR_NOT_AVAILABLE, RT_SRC_POS,
2684 N_("This VM was configured to use 3D acceleration. However, the "
2685 "3D support of the host is not working properly and the "
2686 "VM cannot be started. To fix this problem, either "
2687 "fix the host 3D support (update the host graphics driver?) "
2688 "or disable 3D acceleration in the VM settings"));
2689
2690 /* Load the service */
2691 rc = pVMMDev->hgcmLoadService("VBoxSharedCrOpenGL", "VBoxSharedCrOpenGL");
2692 if (RT_FAILURE(rc))
2693 {
2694 LogRel(("Failed to load Shared OpenGL service %Rrc\n", rc));
2695 /* That is not a fatal failure. */
2696 rc = VINF_SUCCESS;
2697 }
2698 else
2699 {
2700 LogRel(("Shared crOpenGL service loaded.\n"));
2701
2702 /* Setup the service. */
2703 VBOXHGCMSVCPARM parm;
2704 parm.type = VBOX_HGCM_SVC_PARM_PTR;
2705
2706 parm.u.pointer.addr = (IConsole *)(Console *)this;
2707 parm.u.pointer.size = sizeof(IConsole *);
2708
2709 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_CONSOLE, SHCRGL_CPARMS_SET_CONSOLE, &parm);
2710 if (!RT_SUCCESS(rc))
2711 AssertMsgFailed(("SHCRGL_HOST_FN_SET_CONSOLE failed with %Rrc\n", rc));
2712
2713 parm.u.pointer.addr = pVM;
2714 parm.u.pointer.size = sizeof(pVM);
2715 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_VM, SHCRGL_CPARMS_SET_VM, &parm);
2716 if (!RT_SUCCESS(rc))
2717 AssertMsgFailed(("SHCRGL_HOST_FN_SET_VM failed with %Rrc\n", rc));
2718 }
2719
2720 }
2721 }
2722#endif
2723
2724#ifdef VBOX_WITH_GUEST_PROPS
2725 /*
2726 * Guest property service
2727 */
2728
2729 rc = configGuestProperties(this, pUVM);
2730#endif /* VBOX_WITH_GUEST_PROPS defined */
2731
2732#ifdef VBOX_WITH_GUEST_CONTROL
2733 /*
2734 * Guest control service
2735 */
2736
2737 rc = configGuestControl(this);
2738#endif /* VBOX_WITH_GUEST_CONTROL defined */
2739
2740 /*
2741 * ACPI
2742 */
2743 BOOL fACPI;
2744 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
2745 if (fACPI)
2746 {
2747 /* Always show the CPU leafs when we have multiple VCPUs or when the IO-APIC is enabled.
2748 * The Windows SMP kernel needs a CPU leaf or else its idle loop will burn cpu cycles; the
2749 * intelppm driver refuses to register an idle state handler.
2750 * Always show CPU leafs for OS X guests. */
2751 BOOL fShowCpu = fOsXGuest;
2752 if (cCpus > 1 || fIOAPIC)
2753 fShowCpu = true;
2754
2755 BOOL fCpuHotPlug;
2756 hrc = pMachine->COMGETTER(CPUHotPlugEnabled)(&fCpuHotPlug); H();
2757
2758 InsertConfigNode(pDevices, "acpi", &pDev);
2759 InsertConfigNode(pDev, "0", &pInst);
2760 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2761 InsertConfigNode(pInst, "Config", &pCfg);
2762 hrc = pBusMgr->assignPCIDevice("acpi", pInst); H();
2763
2764 InsertConfigInteger(pCfg, "RamSize", cbRam);
2765 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
2766 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
2767
2768 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
2769 InsertConfigInteger(pCfg, "FdcEnabled", fFdcEnabled);
2770 InsertConfigInteger(pCfg, "HpetEnabled", fHPETEnabled);
2771 InsertConfigInteger(pCfg, "SmcEnabled", fSmcEnabled);
2772 InsertConfigInteger(pCfg, "ShowRtc", fShowRtc);
2773 if (fOsXGuest && !llBootNics.empty())
2774 {
2775 BootNic aNic = llBootNics.front();
2776 uint32_t u32NicPCIAddr = (aNic.mPCIAddress.miDevice << 16) | aNic.mPCIAddress.miFn;
2777 InsertConfigInteger(pCfg, "NicPciAddress", u32NicPCIAddr);
2778 }
2779 if (fOsXGuest && fAudioEnabled)
2780 {
2781 PCIBusAddress Address;
2782 if (pBusMgr->findPCIAddress("hda", 0, Address))
2783 {
2784 uint32_t u32AudioPCIAddr = (Address.miDevice << 16) | Address.miFn;
2785 InsertConfigInteger(pCfg, "AudioPciAddress", u32AudioPCIAddr);
2786 }
2787 }
2788 InsertConfigInteger(pCfg, "IocPciAddress", uIocPCIAddress);
2789 if (chipsetType == ChipsetType_ICH9)
2790 {
2791 InsertConfigInteger(pCfg, "McfgBase", uMcfgBase);
2792 InsertConfigInteger(pCfg, "McfgLength", cbMcfgLength);
2793 }
2794 InsertConfigInteger(pCfg, "HostBusPciAddress", uHbcPCIAddress);
2795 InsertConfigInteger(pCfg, "ShowCpu", fShowCpu);
2796 InsertConfigInteger(pCfg, "CpuHotPlug", fCpuHotPlug);
2797
2798 InsertConfigInteger(pCfg, "Serial0IoPortBase", auSerialIoPortBase[0]);
2799 InsertConfigInteger(pCfg, "Serial0Irq", auSerialIrq[0]);
2800
2801 InsertConfigInteger(pCfg, "Serial1IoPortBase", auSerialIoPortBase[1]);
2802 InsertConfigInteger(pCfg, "Serial1Irq", auSerialIrq[1]);
2803
2804 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2805 InsertConfigString(pLunL0, "Driver", "ACPIHost");
2806 InsertConfigNode(pLunL0, "Config", &pCfg);
2807
2808 /* Attach the dummy CPU drivers */
2809 for (ULONG iCpuCurr = 1; iCpuCurr < cCpus; iCpuCurr++)
2810 {
2811 BOOL fCpuAttached = true;
2812
2813 if (fCpuHotPlug)
2814 {
2815 hrc = pMachine->GetCPUStatus(iCpuCurr, &fCpuAttached); H();
2816 }
2817
2818 if (fCpuAttached)
2819 {
2820 InsertConfigNode(pInst, Utf8StrFmt("LUN#%u", iCpuCurr).c_str(), &pLunL0);
2821 InsertConfigString(pLunL0, "Driver", "ACPICpu");
2822 InsertConfigNode(pLunL0, "Config", &pCfg);
2823 }
2824 }
2825 }
2826
2827 /*
2828 * Configure DBGF (Debug(ger) Facility).
2829 */
2830 {
2831 PCFGMNODE pDbgf;
2832 InsertConfigNode(pRoot, "DBGF", &pDbgf);
2833
2834 /* Paths to search for debug info and such things. */
2835 hrc = pMachine->COMGETTER(SettingsFilePath)(bstr.asOutParam()); H();
2836 Utf8Str strSettingsPath(bstr);
2837 bstr.setNull();
2838 strSettingsPath.stripFilename();
2839
2840 char szHomeDir[RTPATH_MAX];
2841 rc = RTPathUserHome(szHomeDir, sizeof(szHomeDir));
2842 if (RT_FAILURE(rc))
2843 szHomeDir[0] = '\0';
2844
2845 Utf8Str strPath;
2846 strPath.append(strSettingsPath).append("/debug/;");
2847 strPath.append(strSettingsPath).append("/;");
2848 strPath.append(szHomeDir).append("/");
2849
2850 InsertConfigString(pDbgf, "Path", strPath.c_str());
2851
2852 /* Tracing configuration. */
2853 BOOL fTracingEnabled;
2854 hrc = pMachine->COMGETTER(TracingEnabled)(&fTracingEnabled); H();
2855 if (fTracingEnabled)
2856 InsertConfigInteger(pDbgf, "TracingEnabled", 1);
2857
2858 hrc = pMachine->COMGETTER(TracingConfig)(bstr.asOutParam()); H();
2859 if (fTracingEnabled)
2860 InsertConfigString(pDbgf, "TracingConfig", bstr);
2861
2862 BOOL fAllowTracingToAccessVM;
2863 hrc = pMachine->COMGETTER(AllowTracingToAccessVM)(&fAllowTracingToAccessVM); H();
2864 if (fAllowTracingToAccessVM)
2865 InsertConfigInteger(pPDM, "AllowTracingToAccessVM", 1);
2866 }
2867 }
2868 catch (ConfigError &x)
2869 {
2870 // InsertConfig threw something:
2871 return x.m_vrc;
2872 }
2873 catch (HRESULT hrcXcpt)
2874 {
2875 AssertMsgFailedReturn(("hrc=%Rhrc\n", hrcXcpt), VERR_GENERAL_FAILURE);
2876 }
2877
2878#ifdef VBOX_WITH_EXTPACK
2879 /*
2880 * Call the extension pack hooks if everything went well thus far.
2881 */
2882 if (RT_SUCCESS(rc))
2883 {
2884 pAlock->release();
2885 rc = mptrExtPackManager->callAllVmConfigureVmmHooks(this, pVM);
2886 pAlock->acquire();
2887 }
2888#endif
2889
2890 /*
2891 * Apply the CFGM overlay.
2892 */
2893 if (RT_SUCCESS(rc))
2894 rc = configCfgmOverlay(pRoot, virtualBox, pMachine);
2895
2896 /*
2897 * Dump all extradata API settings tweaks, both global and per VM.
2898 */
2899 if (RT_SUCCESS(rc))
2900 rc = configDumpAPISettingsTweaks(virtualBox, pMachine);
2901
2902#undef H
2903
2904 pAlock->release(); /* Avoid triggering the lock order inversion check. */
2905
2906 /*
2907 * Register VM state change handler.
2908 */
2909 int rc2 = VMR3AtStateRegister(pUVM, Console::vmstateChangeCallback, this);
2910 AssertRC(rc2);
2911 if (RT_SUCCESS(rc))
2912 rc = rc2;
2913
2914 /*
2915 * Register VM runtime error handler.
2916 */
2917 rc2 = VMR3AtRuntimeErrorRegister(pUVM, Console::setVMRuntimeErrorCallback, this);
2918 AssertRC(rc2);
2919 if (RT_SUCCESS(rc))
2920 rc = rc2;
2921
2922 pAlock->acquire();
2923
2924 LogFlowFunc(("vrc = %Rrc\n", rc));
2925 LogFlowFuncLeave();
2926
2927 return rc;
2928}
2929
2930/**
2931 * Applies the CFGM overlay as specified by VBoxInternal/XXX extra data
2932 * values.
2933 *
2934 * @returns VBox status code.
2935 * @param pRoot The root of the configuration tree.
2936 * @param pVirtualBox Pointer to the IVirtualBox interface.
2937 * @param pMachine Pointer to the IMachine interface.
2938 */
2939/* static */
2940int Console::configCfgmOverlay(PCFGMNODE pRoot, IVirtualBox *pVirtualBox, IMachine *pMachine)
2941{
2942 /*
2943 * CFGM overlay handling.
2944 *
2945 * Here we check the extra data entries for CFGM values
2946 * and create the nodes and insert the values on the fly. Existing
2947 * values will be removed and reinserted. CFGM is typed, so by default
2948 * we will guess whether it's a string or an integer (byte arrays are
2949 * not currently supported). It's possible to override this autodetection
2950 * by adding "string:", "integer:" or "bytes:" (future).
2951 *
2952 * We first perform a run on global extra data, then on the machine
2953 * extra data to support global settings with local overrides.
2954 */
2955 int rc = VINF_SUCCESS;
2956 try
2957 {
2958 /** @todo add support for removing nodes and byte blobs. */
2959 /*
2960 * Get the next key
2961 */
2962 SafeArray<BSTR> aGlobalExtraDataKeys;
2963 SafeArray<BSTR> aMachineExtraDataKeys;
2964 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
2965 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2966
2967 // remember the no. of global values so we can call the correct method below
2968 size_t cGlobalValues = aGlobalExtraDataKeys.size();
2969
2970 hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
2971 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
2972
2973 // build a combined list from global keys...
2974 std::list<Utf8Str> llExtraDataKeys;
2975
2976 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); ++i)
2977 llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
2978 // ... and machine keys
2979 for (size_t i = 0; i < aMachineExtraDataKeys.size(); ++i)
2980 llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));
2981
2982 size_t i2 = 0;
2983 for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
2984 it != llExtraDataKeys.end();
2985 ++it, ++i2)
2986 {
2987 const Utf8Str &strKey = *it;
2988
2989 /*
2990 * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
2991 */
2992 if (!strKey.startsWith("VBoxInternal/"))
2993 continue;
2994
2995 const char *pszExtraDataKey = strKey.c_str() + sizeof("VBoxInternal/") - 1;
2996
2997 // get the value
2998 Bstr bstrExtraDataValue;
2999 if (i2 < cGlobalValues)
3000 // this is still one of the global values:
3001 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
3002 bstrExtraDataValue.asOutParam());
3003 else
3004 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
3005 bstrExtraDataValue.asOutParam());
3006 if (FAILED(hrc))
3007 LogRel(("Warning: Cannot get extra data key %s, rc = %Rhrc\n", strKey.c_str(), hrc));
3008
3009 /*
3010 * The key will be in the format "Node1/Node2/Value" or simply "Value".
3011 * Split the two and get the node, delete the value and create the node
3012 * if necessary.
3013 */
3014 PCFGMNODE pNode;
3015 const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
3016 if (pszCFGMValueName)
3017 {
3018 /* terminate the node and advance to the value (Utf8Str might not
3019 offically like this but wtf) */
3020 *(char*)pszCFGMValueName = '\0';
3021 ++pszCFGMValueName;
3022
3023 /* does the node already exist? */
3024 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
3025 if (pNode)
3026 CFGMR3RemoveValue(pNode, pszCFGMValueName);
3027 else
3028 {
3029 /* create the node */
3030 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
3031 if (RT_FAILURE(rc))
3032 {
3033 AssertLogRelMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
3034 continue;
3035 }
3036 Assert(pNode);
3037 }
3038 }
3039 else
3040 {
3041 /* root value (no node path). */
3042 pNode = pRoot;
3043 pszCFGMValueName = pszExtraDataKey;
3044 pszExtraDataKey--;
3045 CFGMR3RemoveValue(pNode, pszCFGMValueName);
3046 }
3047
3048 /*
3049 * Now let's have a look at the value.
3050 * Empty strings means that we should remove the value, which we've
3051 * already done above.
3052 */
3053 Utf8Str strCFGMValueUtf8(bstrExtraDataValue);
3054 if (!strCFGMValueUtf8.isEmpty())
3055 {
3056 uint64_t u64Value;
3057
3058 /* check for type prefix first. */
3059 if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("string:")))
3060 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str() + sizeof("string:") - 1);
3061 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("integer:")))
3062 {
3063 rc = RTStrToUInt64Full(strCFGMValueUtf8.c_str() + sizeof("integer:") - 1, 0, &u64Value);
3064 if (RT_SUCCESS(rc))
3065 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
3066 }
3067 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("bytes:")))
3068 {
3069 char const *pszBase64 = strCFGMValueUtf8.c_str() + sizeof("bytes:") - 1;
3070 ssize_t cbValue = RTBase64DecodedSize(pszBase64, NULL);
3071 if (cbValue > 0)
3072 {
3073 void *pvBytes = RTMemTmpAlloc(cbValue);
3074 if (pvBytes)
3075 {
3076 rc = RTBase64Decode(pszBase64, pvBytes, cbValue, NULL, NULL);
3077 if (RT_SUCCESS(rc))
3078 rc = CFGMR3InsertBytes(pNode, pszCFGMValueName, pvBytes, cbValue);
3079 RTMemTmpFree(pvBytes);
3080 }
3081 else
3082 rc = VERR_NO_TMP_MEMORY;
3083 }
3084 else if (cbValue == 0)
3085 rc = CFGMR3InsertBytes(pNode, pszCFGMValueName, NULL, 0);
3086 else
3087 rc = VERR_INVALID_BASE64_ENCODING;
3088 }
3089 /* auto detect type. */
3090 else if (RT_SUCCESS(RTStrToUInt64Full(strCFGMValueUtf8.c_str(), 0, &u64Value)))
3091 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
3092 else
3093 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8);
3094 AssertLogRelMsgRCBreak(rc, ("failed to insert CFGM value '%s' to key '%s'\n", strCFGMValueUtf8.c_str(), pszExtraDataKey));
3095 }
3096 }
3097 }
3098 catch (ConfigError &x)
3099 {
3100 // InsertConfig threw something:
3101 return x.m_vrc;
3102 }
3103 return rc;
3104}
3105
3106/**
3107 * Dumps the API settings tweaks as specified by VBoxInternal2/XXX extra data
3108 * values.
3109 *
3110 * @returns VBox status code.
3111 * @param pVirtualBox Pointer to the IVirtualBox interface.
3112 * @param pMachine Pointer to the IMachine interface.
3113 */
3114/* static */
3115int Console::configDumpAPISettingsTweaks(IVirtualBox *pVirtualBox, IMachine *pMachine)
3116{
3117 {
3118 SafeArray<BSTR> aGlobalExtraDataKeys;
3119 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
3120 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
3121 bool hasKey = false;
3122 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); i++)
3123 {
3124 Utf8Str strKey(aGlobalExtraDataKeys[i]);
3125 if (!strKey.startsWith("VBoxInternal2/"))
3126 continue;
3127
3128 Bstr bstrValue;
3129 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
3130 bstrValue.asOutParam());
3131 if (FAILED(hrc))
3132 continue;
3133 if (!hasKey)
3134 LogRel(("Global extradata API settings:\n"));
3135 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
3136 hasKey = true;
3137 }
3138 }
3139
3140 {
3141 SafeArray<BSTR> aMachineExtraDataKeys;
3142 HRESULT hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
3143 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
3144 bool hasKey = false;
3145 for (size_t i = 0; i < aMachineExtraDataKeys.size(); i++)
3146 {
3147 Utf8Str strKey(aMachineExtraDataKeys[i]);
3148 if (!strKey.startsWith("VBoxInternal2/"))
3149 continue;
3150
3151 Bstr bstrValue;
3152 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
3153 bstrValue.asOutParam());
3154 if (FAILED(hrc))
3155 continue;
3156 if (!hasKey)
3157 LogRel(("Per-VM extradata API settings:\n"));
3158 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
3159 hasKey = true;
3160 }
3161 }
3162
3163 return VINF_SUCCESS;
3164}
3165
3166int Console::configGraphicsController(PCFGMNODE pDevices,
3167 const char *pcszDevice,
3168 BusAssignmentManager *pBusMgr,
3169 const ComPtr<IMachine> &pMachine,
3170 const ComPtr<IBIOSSettings> &biosSettings,
3171 bool fHMEnabled)
3172{
3173 // InsertConfig* throws
3174 try
3175 {
3176 PCFGMNODE pDev, pInst, pCfg, pLunL0;
3177 HRESULT hrc;
3178 Bstr bstr;
3179
3180#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3181 InsertConfigNode(pDevices, pcszDevice, &pDev);
3182 InsertConfigNode(pDev, "0", &pInst);
3183 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
3184
3185 hrc = pBusMgr->assignPCIDevice(pcszDevice, pInst); H();
3186 InsertConfigNode(pInst, "Config", &pCfg);
3187 ULONG cVRamMBs;
3188 hrc = pMachine->COMGETTER(VRAMSize)(&cVRamMBs); H();
3189 InsertConfigInteger(pCfg, "VRamSize", cVRamMBs * _1M);
3190 ULONG cMonitorCount;
3191 hrc = pMachine->COMGETTER(MonitorCount)(&cMonitorCount); H();
3192 InsertConfigInteger(pCfg, "MonitorCount", cMonitorCount);
3193#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3194 InsertConfigInteger(pCfg, "R0Enabled", fHMEnabled);
3195#else
3196 NOREF(fHMEnabled);
3197#endif
3198
3199 /* Custom VESA mode list */
3200 unsigned cModes = 0;
3201 for (unsigned iMode = 1; iMode <= 16; ++iMode)
3202 {
3203 char szExtraDataKey[sizeof("CustomVideoModeXX")];
3204 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%u", iMode);
3205 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey).raw(), bstr.asOutParam()); H();
3206 if (bstr.isEmpty())
3207 break;
3208 InsertConfigString(pCfg, szExtraDataKey, bstr);
3209 ++cModes;
3210 }
3211 InsertConfigInteger(pCfg, "CustomVideoModes", cModes);
3212
3213 /* VESA height reduction */
3214 ULONG ulHeightReduction;
3215 IFramebuffer *pFramebuffer = getDisplay()->getFramebuffer();
3216 if (pFramebuffer)
3217 {
3218 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
3219 }
3220 else
3221 {
3222 /* If framebuffer is not available, there is no height reduction. */
3223 ulHeightReduction = 0;
3224 }
3225 InsertConfigInteger(pCfg, "HeightReduction", ulHeightReduction);
3226
3227 /*
3228 * BIOS logo
3229 */
3230 BOOL fFadeIn;
3231 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
3232 InsertConfigInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0);
3233 BOOL fFadeOut;
3234 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
3235 InsertConfigInteger(pCfg, "FadeOut", fFadeOut ? 1: 0);
3236 ULONG logoDisplayTime;
3237 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
3238 InsertConfigInteger(pCfg, "LogoTime", logoDisplayTime);
3239 Bstr logoImagePath;
3240 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
3241 InsertConfigString(pCfg, "LogoFile", Utf8Str(!logoImagePath.isEmpty() ? logoImagePath : "") );
3242
3243 /*
3244 * Boot menu
3245 */
3246 BIOSBootMenuMode_T eBootMenuMode;
3247 int iShowBootMenu;
3248 biosSettings->COMGETTER(BootMenuMode)(&eBootMenuMode);
3249 switch (eBootMenuMode)
3250 {
3251 case BIOSBootMenuMode_Disabled: iShowBootMenu = 0; break;
3252 case BIOSBootMenuMode_MenuOnly: iShowBootMenu = 1; break;
3253 default: iShowBootMenu = 2; break;
3254 }
3255 InsertConfigInteger(pCfg, "ShowBootMenu", iShowBootMenu);
3256
3257 /* Attach the display. */
3258 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3259 InsertConfigString(pLunL0, "Driver", "MainDisplay");
3260 InsertConfigNode(pLunL0, "Config", &pCfg);
3261 Display *pDisplay = mDisplay;
3262 InsertConfigInteger(pCfg, "Object", (uintptr_t)pDisplay);
3263 }
3264 catch (ConfigError &x)
3265 {
3266 // InsertConfig threw something:
3267 return x.m_vrc;
3268 }
3269
3270#undef H
3271
3272 return VINF_SUCCESS;
3273}
3274
3275
3276/**
3277 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
3278 */
3279void Console::setVMRuntimeErrorCallbackF(uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3280{
3281 va_list va;
3282 va_start(va, pszFormat);
3283 setVMRuntimeErrorCallback(NULL, this, fFlags, pszErrorId, pszFormat, va);
3284 va_end(va);
3285}
3286
3287/* XXX introduce RT format specifier */
3288static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
3289{
3290 if (u64Size > INT64_C(5000)*_1G)
3291 {
3292 *pszUnit = "TB";
3293 return u64Size / _1T;
3294 }
3295 else if (u64Size > INT64_C(5000)*_1M)
3296 {
3297 *pszUnit = "GB";
3298 return u64Size / _1G;
3299 }
3300 else
3301 {
3302 *pszUnit = "MB";
3303 return u64Size / _1M;
3304 }
3305}
3306
3307int Console::configMediumAttachment(PCFGMNODE pCtlInst,
3308 const char *pcszDevice,
3309 unsigned uInstance,
3310 StorageBus_T enmBus,
3311 bool fUseHostIOCache,
3312 bool fBuiltinIOCache,
3313 bool fSetupMerge,
3314 unsigned uMergeSource,
3315 unsigned uMergeTarget,
3316 IMediumAttachment *pMediumAtt,
3317 MachineState_T aMachineState,
3318 HRESULT *phrc,
3319 bool fAttachDetach,
3320 bool fForceUnmount,
3321 bool fHotplug,
3322 PUVM pUVM,
3323 DeviceType_T *paLedDevType)
3324{
3325 // InsertConfig* throws
3326 try
3327 {
3328 int rc = VINF_SUCCESS;
3329 HRESULT hrc;
3330 Bstr bstr;
3331
3332// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc)
3333#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3334
3335 LONG lDev;
3336 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
3337 LONG lPort;
3338 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
3339 DeviceType_T lType;
3340 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
3341 BOOL fNonRotational;
3342 hrc = pMediumAtt->COMGETTER(NonRotational)(&fNonRotational); H();
3343 BOOL fDiscard;
3344 hrc = pMediumAtt->COMGETTER(Discard)(&fDiscard); H();
3345
3346 unsigned uLUN;
3347 PCFGMNODE pLunL0 = NULL;
3348 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
3349
3350 /* First check if the LUN already exists. */
3351 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
3352 if (pLunL0)
3353 {
3354 if (fAttachDetach)
3355 {
3356 if (lType != DeviceType_HardDisk)
3357 {
3358 /* Unmount existing media only for floppy and DVD drives. */
3359 PPDMIBASE pBase;
3360 rc = PDMR3QueryLun(pUVM, pcszDevice, uInstance, uLUN, &pBase);
3361 if (RT_FAILURE(rc))
3362 {
3363 if (rc == VERR_PDM_LUN_NOT_FOUND || rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3364 rc = VINF_SUCCESS;
3365 AssertRC(rc);
3366 }
3367 else
3368 {
3369 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
3370 AssertReturn(pIMount, VERR_INVALID_POINTER);
3371
3372 /* Unmount the media (but do not eject the medium!) */
3373 rc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
3374 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
3375 rc = VINF_SUCCESS;
3376 /* for example if the medium is locked */
3377 else if (RT_FAILURE(rc))
3378 return rc;
3379 }
3380 }
3381
3382 rc = PDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG);
3383 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3384 rc = VINF_SUCCESS;
3385 AssertRCReturn(rc, rc);
3386
3387 CFGMR3RemoveNode(pLunL0);
3388 }
3389 else
3390 AssertFailedReturn(VERR_INTERNAL_ERROR);
3391 }
3392
3393 InsertConfigNode(pCtlInst, Utf8StrFmt("LUN#%u", uLUN).c_str(), &pLunL0);
3394
3395 PCFGMNODE pCfg = CFGMR3GetChild(pCtlInst, "Config");
3396 if (pCfg)
3397 {
3398 if (!strcmp(pcszDevice, "piix3ide"))
3399 {
3400 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, g_apszIDEDrives[uLUN]);
3401 if (!pDrive)
3402 InsertConfigNode(pCfg, g_apszIDEDrives[uLUN], &pDrive);
3403 /* Don't use the RemoveConfigValue wrapper above, as we don't
3404 * know if the leaf is present or not. */
3405 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3406 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3407 }
3408 else if (!strcmp(pcszDevice, "ahci"))
3409 {
3410 Utf8Str strPort = Utf8StrFmt("Port%u", uLUN);
3411 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, strPort.c_str());
3412 if (!pDrive)
3413 InsertConfigNode(pCfg, strPort.c_str(), &pDrive);
3414 /* Don't use the RemoveConfigValue wrapper above, as we don't
3415 * know if the leaf is present or not. */
3416 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3417 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3418 }
3419 }
3420
3421 Utf8Str devicePath = Utf8StrFmt("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
3422 mapMediumAttachments[devicePath] = pMediumAtt;
3423
3424 /* SCSI has a another driver between device and block. */
3425 if (enmBus == StorageBus_SCSI || enmBus == StorageBus_SAS)
3426 {
3427 InsertConfigString(pLunL0, "Driver", "SCSI");
3428 PCFGMNODE pL1Cfg = NULL;
3429 InsertConfigNode(pLunL0, "Config", &pL1Cfg);
3430 InsertConfigInteger(pL1Cfg, "NonRotationalMedium", !!fNonRotational);
3431
3432 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3433 }
3434
3435 ComPtr<IMedium> pMedium;
3436 hrc = pMediumAtt->COMGETTER(Medium)(pMedium.asOutParam()); H();
3437
3438 /*
3439 * 1. Only check this for hard disk images.
3440 * 2. Only check during VM creation and not later, especially not during
3441 * taking an online snapshot!
3442 */
3443 if ( lType == DeviceType_HardDisk
3444 && ( aMachineState == MachineState_Starting
3445 || aMachineState == MachineState_Restoring))
3446 {
3447 /*
3448 * Some sanity checks.
3449 */
3450 ComPtr<IMediumFormat> pMediumFormat;
3451 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3452 ULONG uCaps = 0;
3453 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
3454 hrc = pMediumFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap)); H();
3455
3456 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
3457 uCaps |= mediumFormatCap[j];
3458
3459 if (uCaps & MediumFormatCapabilities_File)
3460 {
3461 Bstr strFile;
3462 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3463 Utf8Str utfFile = Utf8Str(strFile);
3464 Bstr strSnap;
3465 ComPtr<IMachine> pMachine = machine();
3466 hrc = pMachine->COMGETTER(SnapshotFolder)(strSnap.asOutParam()); H();
3467 Utf8Str utfSnap = Utf8Str(strSnap);
3468 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3469 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
3470 int rc2 = RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3471 AssertMsgRCReturn(rc2, ("Querying the file type of '%s' failed!\n", utfFile.c_str()), rc2);
3472 /* Ignore the error code. On error, the file system type is still 'unknown' so
3473 * none of the following paths are taken. This can happen for new VMs which
3474 * still don't have a snapshot folder. */
3475 (void)RTFsQueryType(utfSnap.c_str(), &enmFsTypeSnap);
3476 if (!mfSnapshotFolderDiskTypeShown)
3477 {
3478 LogRel(("File system of '%s' (snapshots) is %s\n",
3479 utfSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
3480 mfSnapshotFolderDiskTypeShown = true;
3481 }
3482 LogRel(("File system of '%s' is %s\n", utfFile.c_str(), RTFsTypeName(enmFsTypeFile)));
3483 LONG64 i64Size;
3484 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
3485#ifdef RT_OS_WINDOWS
3486 if ( enmFsTypeFile == RTFSTYPE_FAT
3487 && i64Size >= _4G)
3488 {
3489 const char *pszUnit;
3490 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
3491 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
3492 N_("The medium '%ls' has a logical size of %RU64%s "
3493 "but the file system the medium is located on seems "
3494 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
3495 "We strongly recommend to put all your virtual disk images and "
3496 "the snapshot folder onto an NTFS partition"),
3497 strFile.raw(), u64Print, pszUnit);
3498 }
3499#else /* !RT_OS_WINDOWS */
3500 if ( enmFsTypeFile == RTFSTYPE_FAT
3501 || enmFsTypeFile == RTFSTYPE_EXT
3502 || enmFsTypeFile == RTFSTYPE_EXT2
3503 || enmFsTypeFile == RTFSTYPE_EXT3
3504 || enmFsTypeFile == RTFSTYPE_EXT4)
3505 {
3506 RTFILE file;
3507 rc = RTFileOpen(&file, utfFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3508 if (RT_SUCCESS(rc))
3509 {
3510 RTFOFF maxSize;
3511 /* Careful: This function will work only on selected local file systems! */
3512 rc = RTFileGetMaxSizeEx(file, &maxSize);
3513 RTFileClose(file);
3514 if ( RT_SUCCESS(rc)
3515 && maxSize > 0
3516 && i64Size > (LONG64)maxSize)
3517 {
3518 const char *pszUnitSiz;
3519 const char *pszUnitMax;
3520 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
3521 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
3522 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected", /* <= not exact but ... */
3523 N_("The medium '%ls' has a logical size of %RU64%s "
3524 "but the file system the medium is located on can "
3525 "only handle files up to %RU64%s in theory.\n"
3526 "We strongly recommend to put all your virtual disk "
3527 "images and the snapshot folder onto a proper "
3528 "file system (e.g. ext3) with a sufficient size"),
3529 strFile.raw(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
3530 }
3531 }
3532 }
3533#endif /* !RT_OS_WINDOWS */
3534
3535 /*
3536 * Snapshot folder:
3537 * Here we test only for a FAT partition as we had to create a dummy file otherwise
3538 */
3539 if ( enmFsTypeSnap == RTFSTYPE_FAT
3540 && i64Size >= _4G
3541 && !mfSnapshotFolderSizeWarningShown)
3542 {
3543 const char *pszUnit;
3544 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
3545 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
3546#ifdef RT_OS_WINDOWS
3547 N_("The snapshot folder of this VM '%ls' seems to be located on "
3548 "a FAT(32) file system. The logical size of the medium '%ls' "
3549 "(%RU64%s) is bigger than the maximum file size this file "
3550 "system can handle (4GB).\n"
3551 "We strongly recommend to put all your virtual disk images and "
3552 "the snapshot folder onto an NTFS partition"),
3553#else
3554 N_("The snapshot folder of this VM '%ls' seems to be located on "
3555 "a FAT(32) file system. The logical size of the medium '%ls' "
3556 "(%RU64%s) is bigger than the maximum file size this file "
3557 "system can handle (4GB).\n"
3558 "We strongly recommend to put all your virtual disk images and "
3559 "the snapshot folder onto a proper file system (e.g. ext3)"),
3560#endif
3561 strSnap.raw(), strFile.raw(), u64Print, pszUnit);
3562 /* Show this particular warning only once */
3563 mfSnapshotFolderSizeWarningShown = true;
3564 }
3565
3566#ifdef RT_OS_LINUX
3567 /*
3568 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
3569 * on an ext4 partition. Later we have to check the Linux kernel version!
3570 * This bug apparently applies to the XFS file system as well.
3571 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
3572 */
3573
3574 char szOsRelease[128];
3575 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
3576 bool fKernelHasODirectBug = RT_FAILURE(rc)
3577 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
3578
3579 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
3580 && !fUseHostIOCache
3581 && fKernelHasODirectBug)
3582 {
3583 if ( enmFsTypeFile == RTFSTYPE_EXT4
3584 || enmFsTypeFile == RTFSTYPE_XFS)
3585 {
3586 setVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
3587 N_("The host I/O cache for at least one controller is disabled "
3588 "and the medium '%ls' for this VM "
3589 "is located on an %s partition. There is a known Linux "
3590 "kernel bug which can lead to the corruption of the virtual "
3591 "disk image under these conditions.\n"
3592 "Either enable the host I/O cache permanently in the VM "
3593 "settings or put the disk image and the snapshot folder "
3594 "onto a different file system.\n"
3595 "The host I/O cache will now be enabled for this medium"),
3596 strFile.raw(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3597 fUseHostIOCache = true;
3598 }
3599 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
3600 || enmFsTypeSnap == RTFSTYPE_XFS)
3601 && !mfSnapshotFolderExt4WarningShown)
3602 {
3603 setVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
3604 N_("The host I/O cache for at least one controller is disabled "
3605 "and the snapshot folder for this VM "
3606 "is located on an %s partition. There is a known Linux "
3607 "kernel bug which can lead to the corruption of the virtual "
3608 "disk image under these conditions.\n"
3609 "Either enable the host I/O cache permanently in the VM "
3610 "settings or put the disk image and the snapshot folder "
3611 "onto a different file system.\n"
3612 "The host I/O cache will now be enabled for this medium"),
3613 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3614 fUseHostIOCache = true;
3615 mfSnapshotFolderExt4WarningShown = true;
3616 }
3617 }
3618#endif
3619 }
3620 }
3621
3622 if (pMedium)
3623 {
3624 BOOL fHostDrive;
3625 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3626 if ( ( lType == DeviceType_DVD
3627 || lType == DeviceType_Floppy)
3628 && !fHostDrive)
3629 {
3630 /*
3631 * Informative logging.
3632 */
3633 Bstr strFile;
3634 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3635 Utf8Str utfFile = Utf8Str(strFile);
3636 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3637 (void)RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3638 LogRel(("File system of '%s' (%s) is %s\n",
3639 utfFile.c_str(), lType == DeviceType_DVD ? "DVD" : "Floppy",
3640 RTFsTypeName(enmFsTypeFile)));
3641 }
3642 }
3643
3644 BOOL fPassthrough;
3645 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
3646
3647 ComObjPtr<IBandwidthGroup> pBwGroup;
3648 Bstr strBwGroup;
3649 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3650
3651 if (!pBwGroup.isNull())
3652 {
3653 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3654 }
3655
3656 rc = configMedium(pLunL0,
3657 !!fPassthrough,
3658 lType,
3659 fUseHostIOCache,
3660 fBuiltinIOCache,
3661 fSetupMerge,
3662 uMergeSource,
3663 uMergeTarget,
3664 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3665 !!fDiscard,
3666 pMedium,
3667 aMachineState,
3668 phrc);
3669 if (RT_FAILURE(rc))
3670 return rc;
3671
3672 if (fAttachDetach)
3673 {
3674 /* Attach the new driver. */
3675 rc = PDMR3DeviceAttach(pUVM, pcszDevice, uInstance, uLUN,
3676 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3677 AssertRCReturn(rc, rc);
3678
3679 /* There is no need to handle removable medium mounting, as we
3680 * unconditionally replace everthing including the block driver level.
3681 * This means the new medium will be picked up automatically. */
3682 }
3683
3684 if (paLedDevType)
3685 paLedDevType[uLUN] = lType;
3686 }
3687 catch (ConfigError &x)
3688 {
3689 // InsertConfig threw something:
3690 return x.m_vrc;
3691 }
3692
3693#undef H
3694
3695 return VINF_SUCCESS;
3696}
3697
3698int Console::configMedium(PCFGMNODE pLunL0,
3699 bool fPassthrough,
3700 DeviceType_T enmType,
3701 bool fUseHostIOCache,
3702 bool fBuiltinIOCache,
3703 bool fSetupMerge,
3704 unsigned uMergeSource,
3705 unsigned uMergeTarget,
3706 const char *pcszBwGroup,
3707 bool fDiscard,
3708 IMedium *pMedium,
3709 MachineState_T aMachineState,
3710 HRESULT *phrc)
3711{
3712 // InsertConfig* throws
3713 try
3714 {
3715 int rc = VINF_SUCCESS;
3716 HRESULT hrc;
3717 Bstr bstr;
3718 PCFGMNODE pLunL1 = NULL;
3719 PCFGMNODE pCfg = NULL;
3720
3721#define H() \
3722 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
3723
3724
3725 BOOL fHostDrive = FALSE;
3726 MediumType_T mediumType = MediumType_Normal;
3727 if (pMedium)
3728 {
3729 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3730 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3731 }
3732
3733 if (fHostDrive)
3734 {
3735 Assert(pMedium);
3736 if (enmType == DeviceType_DVD)
3737 {
3738 InsertConfigString(pLunL0, "Driver", "HostDVD");
3739 InsertConfigNode(pLunL0, "Config", &pCfg);
3740
3741 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3742 InsertConfigString(pCfg, "Path", bstr);
3743
3744 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3745 }
3746 else if (enmType == DeviceType_Floppy)
3747 {
3748 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3749 InsertConfigNode(pLunL0, "Config", &pCfg);
3750
3751 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3752 InsertConfigString(pCfg, "Path", bstr);
3753 }
3754 }
3755 else
3756 {
3757 InsertConfigString(pLunL0, "Driver", "Block");
3758 InsertConfigNode(pLunL0, "Config", &pCfg);
3759 switch (enmType)
3760 {
3761 case DeviceType_DVD:
3762 InsertConfigString(pCfg, "Type", "DVD");
3763 InsertConfigInteger(pCfg, "Mountable", 1);
3764 break;
3765 case DeviceType_Floppy:
3766 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3767 InsertConfigInteger(pCfg, "Mountable", 1);
3768 break;
3769 case DeviceType_HardDisk:
3770 default:
3771 InsertConfigString(pCfg, "Type", "HardDisk");
3772 InsertConfigInteger(pCfg, "Mountable", 0);
3773 }
3774
3775 if ( pMedium
3776 && ( enmType == DeviceType_DVD
3777 || enmType == DeviceType_Floppy)
3778 )
3779 {
3780 // if this medium represents an ISO image and this image is inaccessible,
3781 // the ignore it instead of causing a failure; this can happen when we
3782 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3783 // Additions were mounted and the user upgraded VirtualBox. Previously
3784 // we failed on startup, but that's not good because the only way out then
3785 // would be to discard the VM state...
3786 MediumState_T mediumState;
3787 hrc = pMedium->RefreshState(&mediumState); H();
3788 if (mediumState == MediumState_Inaccessible)
3789 {
3790 Bstr loc;
3791 hrc = pMedium->COMGETTER(Location)(loc.asOutParam()); H();
3792 setVMRuntimeErrorCallbackF(0, "DvdOrFloppyImageInaccessible",
3793 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3794 loc.raw(),
3795 enmType == DeviceType_DVD ? "DVD" : "floppy");
3796 pMedium = NULL;
3797 }
3798 }
3799
3800 if (pMedium)
3801 {
3802 /* Start with length of parent chain, as the list is reversed */
3803 unsigned uImage = 0;
3804 IMedium *pTmp = pMedium;
3805 while (pTmp)
3806 {
3807 uImage++;
3808 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3809 }
3810 /* Index of last image */
3811 uImage--;
3812
3813#if 0 /* Enable for I/O debugging */
3814 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3815 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3816 InsertConfigNode(pLunL0, "Config", &pCfg);
3817 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3818 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3819#endif
3820
3821 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3822 InsertConfigString(pLunL1, "Driver", "VD");
3823 InsertConfigNode(pLunL1, "Config", &pCfg);
3824
3825 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3826 InsertConfigString(pCfg, "Path", bstr);
3827
3828 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3829 InsertConfigString(pCfg, "Format", bstr);
3830
3831 if (mediumType == MediumType_Readonly)
3832 InsertConfigInteger(pCfg, "ReadOnly", 1);
3833 else if (enmType == DeviceType_Floppy)
3834 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3835
3836 /* Start without exclusive write access to the images. */
3837 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3838 * we're resuming the VM if some 3rd dude have any of the VDIs open
3839 * with write sharing denied. However, if the two VMs are sharing a
3840 * image it really is necessary....
3841 *
3842 * So, on the "lock-media" command, the target teleporter should also
3843 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3844 * that. Grumble. */
3845 if ( enmType == DeviceType_HardDisk
3846 && ( aMachineState == MachineState_TeleportingIn
3847 || aMachineState == MachineState_FaultTolerantSyncing))
3848 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3849
3850 /* Flag for opening the medium for sharing between VMs. This
3851 * is done at the moment only for the first (and only) medium
3852 * in the chain, as shared media can have no diffs. */
3853 if (mediumType == MediumType_Shareable)
3854 InsertConfigInteger(pCfg, "Shareable", 1);
3855
3856 if (!fUseHostIOCache)
3857 {
3858 InsertConfigInteger(pCfg, "UseNewIo", 1);
3859 /*
3860 * Activate the builtin I/O cache for harddisks only.
3861 * It caches writes only which doesn't make sense for DVD drives
3862 * and just increases the overhead.
3863 */
3864 if ( fBuiltinIOCache
3865 && (enmType == DeviceType_HardDisk))
3866 InsertConfigInteger(pCfg, "BlockCache", 1);
3867 }
3868
3869 if (fSetupMerge)
3870 {
3871 InsertConfigInteger(pCfg, "SetupMerge", 1);
3872 if (uImage == uMergeSource)
3873 InsertConfigInteger(pCfg, "MergeSource", 1);
3874 else if (uImage == uMergeTarget)
3875 InsertConfigInteger(pCfg, "MergeTarget", 1);
3876 }
3877
3878 switch (enmType)
3879 {
3880 case DeviceType_DVD:
3881 InsertConfigString(pCfg, "Type", "DVD");
3882 break;
3883 case DeviceType_Floppy:
3884 InsertConfigString(pCfg, "Type", "Floppy");
3885 break;
3886 case DeviceType_HardDisk:
3887 default:
3888 InsertConfigString(pCfg, "Type", "HardDisk");
3889 }
3890
3891 if (pcszBwGroup)
3892 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3893
3894 if (fDiscard)
3895 InsertConfigInteger(pCfg, "Discard", 1);
3896
3897 /* Pass all custom parameters. */
3898 bool fHostIP = true;
3899 SafeArray<BSTR> names;
3900 SafeArray<BSTR> values;
3901 hrc = pMedium->GetProperties(Bstr().raw(),
3902 ComSafeArrayAsOutParam(names),
3903 ComSafeArrayAsOutParam(values)); H();
3904
3905 if (names.size() != 0)
3906 {
3907 PCFGMNODE pVDC;
3908 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3909 for (size_t ii = 0; ii < names.size(); ++ii)
3910 {
3911 if (values[ii] && *values[ii])
3912 {
3913 Utf8Str name = names[ii];
3914 Utf8Str value = values[ii];
3915 InsertConfigString(pVDC, name.c_str(), value);
3916 if ( name.compare("HostIPStack") == 0
3917 && value.compare("0") == 0)
3918 fHostIP = false;
3919 }
3920 }
3921 }
3922
3923 /* Create an inverted list of parents. */
3924 uImage--;
3925 IMedium *pParentMedium = pMedium;
3926 for (PCFGMNODE pParent = pCfg;; uImage--)
3927 {
3928 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3929 if (!pMedium)
3930 break;
3931
3932 PCFGMNODE pCur;
3933 InsertConfigNode(pParent, "Parent", &pCur);
3934 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3935 InsertConfigString(pCur, "Path", bstr);
3936
3937 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3938 InsertConfigString(pCur, "Format", bstr);
3939
3940 if (fSetupMerge)
3941 {
3942 if (uImage == uMergeSource)
3943 InsertConfigInteger(pCur, "MergeSource", 1);
3944 else if (uImage == uMergeTarget)
3945 InsertConfigInteger(pCur, "MergeTarget", 1);
3946 }
3947
3948 /* Pass all custom parameters. */
3949 SafeArray<BSTR> aNames;
3950 SafeArray<BSTR> aValues;
3951 hrc = pMedium->GetProperties(NULL,
3952 ComSafeArrayAsOutParam(aNames),
3953 ComSafeArrayAsOutParam(aValues)); H();
3954
3955 if (aNames.size() != 0)
3956 {
3957 PCFGMNODE pVDC;
3958 InsertConfigNode(pCur, "VDConfig", &pVDC);
3959 for (size_t ii = 0; ii < aNames.size(); ++ii)
3960 {
3961 if (aValues[ii] && *aValues[ii])
3962 {
3963 Utf8Str name = aNames[ii];
3964 Utf8Str value = aValues[ii];
3965 InsertConfigString(pVDC, name.c_str(), value);
3966 if ( name.compare("HostIPStack") == 0
3967 && value.compare("0") == 0)
3968 fHostIP = false;
3969 }
3970 }
3971 }
3972
3973 /* next */
3974 pParent = pCur;
3975 pParentMedium = pMedium;
3976 }
3977
3978 /* Custom code: put marker to not use host IP stack to driver
3979 * configuration node. Simplifies life of DrvVD a bit. */
3980 if (!fHostIP)
3981 InsertConfigInteger(pCfg, "HostIPStack", 0);
3982 }
3983 }
3984#undef H
3985 }
3986 catch (ConfigError &x)
3987 {
3988 // InsertConfig threw something:
3989 return x.m_vrc;
3990 }
3991
3992 return VINF_SUCCESS;
3993}
3994
3995/**
3996 * Construct the Network configuration tree
3997 *
3998 * @returns VBox status code.
3999 *
4000 * @param pszDevice The PDM device name.
4001 * @param uInstance The PDM device instance.
4002 * @param uLun The PDM LUN number of the drive.
4003 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4004 * @param pCfg Configuration node for the device
4005 * @param pLunL0 To store the pointer to the LUN#0.
4006 * @param pInst The instance CFGM node
4007 * @param fAttachDetach To determine if the network attachment should
4008 * be attached/detached after/before
4009 * configuration.
4010 * @param fIgnoreConnectFailure
4011 * True if connection failures should be ignored
4012 * (makes only sense for bridged/host-only networks).
4013 *
4014 * @note Locks this object for writing.
4015 * @thread EMT
4016 */
4017int Console::configNetwork(const char *pszDevice,
4018 unsigned uInstance,
4019 unsigned uLun,
4020 INetworkAdapter *aNetworkAdapter,
4021 PCFGMNODE pCfg,
4022 PCFGMNODE pLunL0,
4023 PCFGMNODE pInst,
4024 bool fAttachDetach,
4025 bool fIgnoreConnectFailure)
4026{
4027 AutoCaller autoCaller(this);
4028 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4029
4030 // InsertConfig* throws
4031 try
4032 {
4033 int rc = VINF_SUCCESS;
4034 HRESULT hrc;
4035 Bstr bstr;
4036
4037#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
4038
4039 /*
4040 * Locking the object before doing VMR3* calls is quite safe here, since
4041 * we're on EMT. Write lock is necessary because we indirectly modify the
4042 * meAttachmentType member.
4043 */
4044 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4045
4046 ComPtr<IMachine> pMachine = machine();
4047
4048 ComPtr<IVirtualBox> virtualBox;
4049 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
4050
4051 ComPtr<IHost> host;
4052 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
4053
4054 BOOL fSniffer;
4055 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
4056
4057 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
4058 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
4059 const char *pszPromiscuousGuestPolicy;
4060 switch (enmPromiscModePolicy)
4061 {
4062 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
4063 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
4064 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
4065 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
4066 }
4067
4068 if (fAttachDetach)
4069 {
4070 rc = PDMR3DeviceDetach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
4071 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4072 rc = VINF_SUCCESS;
4073 AssertLogRelRCReturn(rc, rc);
4074
4075 /* nuke anything which might have been left behind. */
4076 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
4077 }
4078
4079#ifdef VBOX_WITH_NETSHAPER
4080 ComObjPtr<IBandwidthGroup> pBwGroup;
4081 Bstr strBwGroup;
4082 hrc = aNetworkAdapter->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
4083
4084 if (!pBwGroup.isNull())
4085 {
4086 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
4087 }
4088#endif /* VBOX_WITH_NETSHAPER */
4089
4090 Utf8Str strNetDriver;
4091
4092
4093 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4094
4095#ifdef VBOX_WITH_NETSHAPER
4096 if (!strBwGroup.isEmpty())
4097 {
4098 InsertConfigString(pLunL0, "Driver", "NetShaper");
4099 InsertConfigNode(pLunL0, "Config", &pCfg);
4100 InsertConfigString(pCfg, "BwGroup", strBwGroup);
4101 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4102 }
4103#endif /* VBOX_WITH_NETSHAPER */
4104
4105 if (fSniffer)
4106 {
4107 InsertConfigString(pLunL0, "Driver", "NetSniffer");
4108 InsertConfigNode(pLunL0, "Config", &pCfg);
4109 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
4110 if (!bstr.isEmpty()) /* check convention for indicating default file. */
4111 InsertConfigString(pCfg, "File", bstr);
4112 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4113 }
4114
4115
4116 Bstr networkName, trunkName, trunkType;
4117 NetworkAttachmentType_T eAttachmentType;
4118 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
4119 switch (eAttachmentType)
4120 {
4121 case NetworkAttachmentType_Null:
4122 break;
4123
4124 case NetworkAttachmentType_NAT:
4125 {
4126 ComPtr<INATEngine> natEngine;
4127 hrc = aNetworkAdapter->COMGETTER(NATEngine)(natEngine.asOutParam()); H();
4128 InsertConfigString(pLunL0, "Driver", "NAT");
4129 InsertConfigNode(pLunL0, "Config", &pCfg);
4130
4131 /* Configure TFTP prefix and boot filename. */
4132 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
4133 if (!bstr.isEmpty())
4134 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
4135 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
4136 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
4137
4138 hrc = natEngine->COMGETTER(Network)(bstr.asOutParam()); H();
4139 if (!bstr.isEmpty())
4140 InsertConfigString(pCfg, "Network", bstr);
4141 else
4142 {
4143 ULONG uSlot;
4144 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
4145 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
4146 }
4147 hrc = natEngine->COMGETTER(HostIP)(bstr.asOutParam()); H();
4148 if (!bstr.isEmpty())
4149 InsertConfigString(pCfg, "BindIP", bstr);
4150 ULONG mtu = 0;
4151 ULONG sockSnd = 0;
4152 ULONG sockRcv = 0;
4153 ULONG tcpSnd = 0;
4154 ULONG tcpRcv = 0;
4155 hrc = natEngine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
4156 if (mtu)
4157 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
4158 if (sockRcv)
4159 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
4160 if (sockSnd)
4161 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
4162 if (tcpRcv)
4163 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
4164 if (tcpSnd)
4165 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
4166 hrc = natEngine->COMGETTER(TFTPPrefix)(bstr.asOutParam()); H();
4167 if (!bstr.isEmpty())
4168 {
4169 RemoveConfigValue(pCfg, "TFTPPrefix");
4170 InsertConfigString(pCfg, "TFTPPrefix", bstr);
4171 }
4172 hrc = natEngine->COMGETTER(TFTPBootFile)(bstr.asOutParam()); H();
4173 if (!bstr.isEmpty())
4174 {
4175 RemoveConfigValue(pCfg, "BootFile");
4176 InsertConfigString(pCfg, "BootFile", bstr);
4177 }
4178 hrc = natEngine->COMGETTER(TFTPNextServer)(bstr.asOutParam()); H();
4179 if (!bstr.isEmpty())
4180 InsertConfigString(pCfg, "NextServer", bstr);
4181 BOOL fDNSFlag;
4182 hrc = natEngine->COMGETTER(DNSPassDomain)(&fDNSFlag); H();
4183 InsertConfigInteger(pCfg, "PassDomain", fDNSFlag);
4184 hrc = natEngine->COMGETTER(DNSProxy)(&fDNSFlag); H();
4185 InsertConfigInteger(pCfg, "DNSProxy", fDNSFlag);
4186 hrc = natEngine->COMGETTER(DNSUseHostResolver)(&fDNSFlag); H();
4187 InsertConfigInteger(pCfg, "UseHostResolver", fDNSFlag);
4188
4189 ULONG aliasMode;
4190 hrc = natEngine->COMGETTER(AliasMode)(&aliasMode); H();
4191 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
4192
4193 /* port-forwarding */
4194 SafeArray<BSTR> pfs;
4195 hrc = natEngine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
4196 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
4197 for (unsigned int i = 0; i < pfs.size(); ++i)
4198 {
4199 uint16_t port = 0;
4200 BSTR r = pfs[i];
4201 Utf8Str utf = Utf8Str(r);
4202 Utf8Str strName;
4203 Utf8Str strProto;
4204 Utf8Str strHostPort;
4205 Utf8Str strHostIP;
4206 Utf8Str strGuestPort;
4207 Utf8Str strGuestIP;
4208 size_t pos, ppos;
4209 pos = ppos = 0;
4210#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
4211 do { \
4212 pos = str.find(",", ppos); \
4213 if (pos == Utf8Str::npos) \
4214 { \
4215 Log(( #res " extracting from %s is failed\n", str.c_str())); \
4216 continue; \
4217 } \
4218 res = str.substr(ppos, pos - ppos); \
4219 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
4220 ppos = pos + 1; \
4221 } while (0)
4222 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
4223 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
4224 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
4225 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
4226 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
4227 strGuestPort = utf.substr(ppos, utf.length() - ppos);
4228#undef ITERATE_TO_NEXT_TERM
4229
4230 uint32_t proto = strProto.toUInt32();
4231 bool fValid = true;
4232 switch (proto)
4233 {
4234 case NATProtocol_UDP:
4235 strProto = "UDP";
4236 break;
4237 case NATProtocol_TCP:
4238 strProto = "TCP";
4239 break;
4240 default:
4241 fValid = false;
4242 }
4243 /* continue with next rule if no valid proto was passed */
4244 if (!fValid)
4245 continue;
4246
4247 InsertConfigNode(pCfg, strName.c_str(), &pPF);
4248 InsertConfigString(pPF, "Protocol", strProto);
4249
4250 if (!strHostIP.isEmpty())
4251 InsertConfigString(pPF, "BindIP", strHostIP);
4252
4253 if (!strGuestIP.isEmpty())
4254 InsertConfigString(pPF, "GuestIP", strGuestIP);
4255
4256 port = RTStrToUInt16(strHostPort.c_str());
4257 if (port)
4258 InsertConfigInteger(pPF, "HostPort", port);
4259
4260 port = RTStrToUInt16(strGuestPort.c_str());
4261 if (port)
4262 InsertConfigInteger(pPF, "GuestPort", port);
4263 }
4264 break;
4265 }
4266
4267 case NetworkAttachmentType_Bridged:
4268 {
4269#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
4270 hrc = attachToTapInterface(aNetworkAdapter);
4271 if (FAILED(hrc))
4272 {
4273 switch (hrc)
4274 {
4275 case VERR_ACCESS_DENIED:
4276 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4277 "Failed to open '/dev/net/tun' for read/write access. Please check the "
4278 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
4279 "change the group of that node and make yourself a member of that group. Make "
4280 "sure that these changes are permanent, especially if you are "
4281 "using udev"));
4282 default:
4283 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
4284 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4285 "Failed to initialize Host Interface Networking"));
4286 }
4287 }
4288
4289 Assert((int)maTapFD[uInstance] >= 0);
4290 if ((int)maTapFD[uInstance] >= 0)
4291 {
4292 InsertConfigString(pLunL0, "Driver", "HostInterface");
4293 InsertConfigNode(pLunL0, "Config", &pCfg);
4294 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4295 }
4296
4297#elif defined(VBOX_WITH_NETFLT)
4298 /*
4299 * This is the new VBoxNetFlt+IntNet stuff.
4300 */
4301 Bstr BridgedIfName;
4302 hrc = aNetworkAdapter->COMGETTER(BridgedInterface)(BridgedIfName.asOutParam());
4303 if (FAILED(hrc))
4304 {
4305 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(BridgedInterface) failed, hrc (0x%x)\n", hrc));
4306 H();
4307 }
4308
4309 Utf8Str BridgedIfNameUtf8(BridgedIfName);
4310 const char *pszBridgedIfName = BridgedIfNameUtf8.c_str();
4311
4312# if defined(RT_OS_DARWIN)
4313 /* The name is on the form 'ifX: long name', chop it off at the colon. */
4314 char szTrunk[8];
4315 RTStrCopy(szTrunk, sizeof(szTrunk), pszBridgedIfName);
4316 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4317// Quick fix for @bugref{5633}
4318// if (!pszColon)
4319// {
4320// /*
4321// * Dynamic changing of attachment causes an attempt to configure
4322// * network with invalid host adapter (as it is must be changed before
4323// * the attachment), calling Detach here will cause a deadlock.
4324// * See @bugref{4750}.
4325// * hrc = aNetworkAdapter->Detach(); H();
4326// */
4327// return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4328// N_("Malformed host interface networking name '%ls'"),
4329// BridgedIfName.raw());
4330// }
4331 if (pszColon)
4332 *pszColon = '\0';
4333 const char *pszTrunk = szTrunk;
4334
4335# elif defined(RT_OS_SOLARIS)
4336 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
4337 char szTrunk[256];
4338 strlcpy(szTrunk, pszBridgedIfName, sizeof(szTrunk));
4339 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
4340
4341 /*
4342 * Currently don't bother about malformed names here for the sake of people using
4343 * VBoxManage and setting only the NIC name from there. If there is a space we
4344 * chop it off and proceed, otherwise just use whatever we've got.
4345 */
4346 if (pszSpace)
4347 *pszSpace = '\0';
4348
4349 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
4350 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4351 if (pszColon)
4352 *pszColon = '\0';
4353
4354 const char *pszTrunk = szTrunk;
4355
4356# elif defined(RT_OS_WINDOWS)
4357 ComPtr<IHostNetworkInterface> hostInterface;
4358 hrc = host->FindHostNetworkInterfaceByName(BridgedIfName.raw(),
4359 hostInterface.asOutParam());
4360 if (!SUCCEEDED(hrc))
4361 {
4362 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
4363 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4364 N_("Nonexistent host networking interface, name '%ls'"),
4365 BridgedIfName.raw());
4366 }
4367
4368 HostNetworkInterfaceType_T eIfType;
4369 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4370 if (FAILED(hrc))
4371 {
4372 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4373 H();
4374 }
4375
4376 if (eIfType != HostNetworkInterfaceType_Bridged)
4377 {
4378 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4379 N_("Interface ('%ls') is not a Bridged Adapter interface"),
4380 BridgedIfName.raw());
4381 }
4382
4383 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4384 if (FAILED(hrc))
4385 {
4386 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4387 H();
4388 }
4389 Guid hostIFGuid(bstr);
4390
4391 INetCfg *pNc;
4392 ComPtr<INetCfgComponent> pAdaptorComponent;
4393 LPWSTR pszApp;
4394
4395 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4396 Assert(hrc == S_OK);
4397 if (hrc != S_OK)
4398 {
4399 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4400 H();
4401 }
4402
4403 /* get the adapter's INetCfgComponent*/
4404 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4405 if (hrc != S_OK)
4406 {
4407 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4408 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)\n", hrc));
4409 H();
4410 }
4411#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4412 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4413 char *pszTrunkName = szTrunkName;
4414 wchar_t * pswzBindName;
4415 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4416 Assert(hrc == S_OK);
4417 if (hrc == S_OK)
4418 {
4419 int cwBindName = (int)wcslen(pswzBindName) + 1;
4420 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4421 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4422 {
4423 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4424 pszTrunkName += cbFullBindNamePrefix-1;
4425 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4426 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4427 {
4428 DWORD err = GetLastError();
4429 hrc = HRESULT_FROM_WIN32(err);
4430 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
4431 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4432 }
4433 }
4434 else
4435 {
4436 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
4437 /** @todo set appropriate error code */
4438 hrc = E_FAIL;
4439 }
4440
4441 if (hrc != S_OK)
4442 {
4443 AssertFailed();
4444 CoTaskMemFree(pswzBindName);
4445 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4446 H();
4447 }
4448
4449 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
4450 }
4451 else
4452 {
4453 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4454 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
4455 H();
4456 }
4457
4458 const char *pszTrunk = szTrunkName;
4459 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
4460
4461# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
4462# if defined(RT_OS_FREEBSD)
4463 /*
4464 * If we bridge to a tap interface open it the `old' direct way.
4465 * This works and performs better than bridging a physical
4466 * interface via the current FreeBSD vboxnetflt implementation.
4467 */
4468 if (!strncmp(pszBridgedIfName, RT_STR_TUPLE("tap"))) {
4469 hrc = attachToTapInterface(aNetworkAdapter);
4470 if (FAILED(hrc))
4471 {
4472 switch (hrc)
4473 {
4474 case VERR_ACCESS_DENIED:
4475 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4476 "Failed to open '/dev/%s' for read/write access. Please check the "
4477 "permissions of that node, and that the net.link.tap.user_open "
4478 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
4479 "change the group of that node to vboxusers and make yourself "
4480 "a member of that group. Make sure that these changes are permanent."), pszBridgedIfName, pszBridgedIfName);
4481 default:
4482 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
4483 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4484 "Failed to initialize Host Interface Networking"));
4485 }
4486 }
4487
4488 Assert((int)maTapFD[uInstance] >= 0);
4489 if ((int)maTapFD[uInstance] >= 0)
4490 {
4491 InsertConfigString(pLunL0, "Driver", "HostInterface");
4492 InsertConfigNode(pLunL0, "Config", &pCfg);
4493 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4494 }
4495 break;
4496 }
4497# endif
4498 /** @todo Check for malformed names. */
4499 const char *pszTrunk = pszBridgedIfName;
4500
4501 /* Issue a warning if the interface is down */
4502 {
4503 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4504 if (iSock >= 0)
4505 {
4506 struct ifreq Req;
4507 RT_ZERO(Req);
4508 RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pszBridgedIfName);
4509 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
4510 if ((Req.ifr_flags & IFF_UP) == 0)
4511 setVMRuntimeErrorCallbackF(0, "BridgedInterfaceDown",
4512 N_("Bridged interface %s is down. Guest will not be able to use this interface"),
4513 pszBridgedIfName);
4514
4515 close(iSock);
4516 }
4517 }
4518
4519# else
4520# error "PORTME (VBOX_WITH_NETFLT)"
4521# endif
4522
4523 InsertConfigString(pLunL0, "Driver", "IntNet");
4524 InsertConfigNode(pLunL0, "Config", &pCfg);
4525 InsertConfigString(pCfg, "Trunk", pszTrunk);
4526 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4527 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
4528 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4529 char szNetwork[INTNET_MAX_NETWORK_NAME];
4530
4531#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
4532 /*
4533 * 'pszTrunk' contains just the interface name required in ring-0, while 'pszBridgedIfName' contains
4534 * interface name + optional description. We must not pass any description to the VM as it can differ
4535 * for the same interface name, eg: "nge0 - ethernet" (GUI) vs "nge0" (VBoxManage).
4536 */
4537 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszTrunk);
4538#else
4539 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszBridgedIfName);
4540#endif
4541 InsertConfigString(pCfg, "Network", szNetwork);
4542 networkName = Bstr(szNetwork);
4543 trunkName = Bstr(pszTrunk);
4544 trunkType = Bstr(TRUNKTYPE_NETFLT);
4545
4546# if defined(RT_OS_DARWIN)
4547 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
4548 if ( strstr(pszBridgedIfName, "Wireless")
4549 || strstr(pszBridgedIfName, "AirPort" ))
4550 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4551# elif defined(RT_OS_LINUX)
4552 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4553 if (iSock >= 0)
4554 {
4555 struct iwreq WRq;
4556
4557 RT_ZERO(WRq);
4558 strncpy(WRq.ifr_name, pszBridgedIfName, IFNAMSIZ);
4559 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
4560 close(iSock);
4561 if (fSharedMacOnWire)
4562 {
4563 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4564 Log(("Set SharedMacOnWire\n"));
4565 }
4566 else
4567 Log(("Failed to get wireless name\n"));
4568 }
4569 else
4570 Log(("Failed to open wireless socket\n"));
4571# elif defined(RT_OS_FREEBSD)
4572 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4573 if (iSock >= 0)
4574 {
4575 struct ieee80211req WReq;
4576 uint8_t abData[32];
4577
4578 RT_ZERO(WReq);
4579 strncpy(WReq.i_name, pszBridgedIfName, sizeof(WReq.i_name));
4580 WReq.i_type = IEEE80211_IOC_SSID;
4581 WReq.i_val = -1;
4582 WReq.i_data = abData;
4583 WReq.i_len = sizeof(abData);
4584
4585 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
4586 close(iSock);
4587 if (fSharedMacOnWire)
4588 {
4589 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4590 Log(("Set SharedMacOnWire\n"));
4591 }
4592 else
4593 Log(("Failed to get wireless name\n"));
4594 }
4595 else
4596 Log(("Failed to open wireless socket\n"));
4597# elif defined(RT_OS_WINDOWS)
4598# define DEVNAME_PREFIX L"\\\\.\\"
4599 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
4600 * there is a pretty long way till there though since we need to obtain the symbolic link name
4601 * for the adapter device we are going to query given the device Guid */
4602
4603
4604 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
4605
4606 wchar_t FileName[MAX_PATH];
4607 wcscpy(FileName, DEVNAME_PREFIX);
4608 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
4609
4610 /* open the device */
4611 HANDLE hDevice = CreateFile(FileName,
4612 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
4613 NULL,
4614 OPEN_EXISTING,
4615 FILE_ATTRIBUTE_NORMAL,
4616 NULL);
4617
4618 if (hDevice != INVALID_HANDLE_VALUE)
4619 {
4620 bool fSharedMacOnWire = false;
4621
4622 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4623 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4624 NDIS_PHYSICAL_MEDIUM PhMedium;
4625 DWORD cbResult;
4626 if (DeviceIoControl(hDevice,
4627 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4628 &Oid,
4629 sizeof(Oid),
4630 &PhMedium,
4631 sizeof(PhMedium),
4632 &cbResult,
4633 NULL))
4634 {
4635 /* that was simple, now examine PhMedium */
4636 if ( PhMedium == NdisPhysicalMediumWirelessWan
4637 || PhMedium == NdisPhysicalMediumWirelessLan
4638 || PhMedium == NdisPhysicalMediumNative802_11
4639 || PhMedium == NdisPhysicalMediumBluetooth)
4640 fSharedMacOnWire = true;
4641 }
4642 else
4643 {
4644 int winEr = GetLastError();
4645 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4646 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4647 }
4648 CloseHandle(hDevice);
4649
4650 if (fSharedMacOnWire)
4651 {
4652 Log(("this is a wireless adapter"));
4653 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4654 Log(("Set SharedMacOnWire\n"));
4655 }
4656 else
4657 Log(("this is NOT a wireless adapter"));
4658 }
4659 else
4660 {
4661 int winEr = GetLastError();
4662 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4663 }
4664
4665 CoTaskMemFree(pswzBindName);
4666
4667 pAdaptorComponent.setNull();
4668 /* release the pNc finally */
4669 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4670# else
4671 /** @todo PORTME: wireless detection */
4672# endif
4673
4674# if defined(RT_OS_SOLARIS)
4675# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4676 /* Zone access restriction, don't allow snooping the global zone. */
4677 zoneid_t ZoneId = getzoneid();
4678 if (ZoneId != GLOBAL_ZONEID)
4679 {
4680 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4681 }
4682# endif
4683# endif
4684
4685#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4686 /* NOTHING TO DO HERE */
4687#elif defined(RT_OS_LINUX)
4688/// @todo aleksey: is there anything to be done here?
4689#elif defined(RT_OS_FREEBSD)
4690/** @todo FreeBSD: Check out this later (HIF networking). */
4691#else
4692# error "Port me"
4693#endif
4694 break;
4695 }
4696
4697 case NetworkAttachmentType_Internal:
4698 {
4699 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4700 if (!bstr.isEmpty())
4701 {
4702 InsertConfigString(pLunL0, "Driver", "IntNet");
4703 InsertConfigNode(pLunL0, "Config", &pCfg);
4704 InsertConfigString(pCfg, "Network", bstr);
4705 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4706 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4707 networkName = bstr;
4708 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4709 }
4710 break;
4711 }
4712
4713 case NetworkAttachmentType_HostOnly:
4714 {
4715 InsertConfigString(pLunL0, "Driver", "IntNet");
4716 InsertConfigNode(pLunL0, "Config", &pCfg);
4717
4718 Bstr HostOnlyName;
4719 hrc = aNetworkAdapter->COMGETTER(HostOnlyInterface)(HostOnlyName.asOutParam());
4720 if (FAILED(hrc))
4721 {
4722 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostOnlyInterface) failed, hrc (0x%x)\n", hrc));
4723 H();
4724 }
4725
4726 Utf8Str HostOnlyNameUtf8(HostOnlyName);
4727 const char *pszHostOnlyName = HostOnlyNameUtf8.c_str();
4728 ComPtr<IHostNetworkInterface> hostInterface;
4729 rc = host->FindHostNetworkInterfaceByName(HostOnlyName.raw(),
4730 hostInterface.asOutParam());
4731 if (!SUCCEEDED(rc))
4732 {
4733 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4734 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4735 N_("Nonexistent host networking interface, name '%ls'"),
4736 HostOnlyName.raw());
4737 }
4738
4739 char szNetwork[INTNET_MAX_NETWORK_NAME];
4740 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHostOnlyName);
4741
4742#if defined(RT_OS_WINDOWS)
4743# ifndef VBOX_WITH_NETFLT
4744 hrc = E_NOTIMPL;
4745 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4746 H();
4747# else /* defined VBOX_WITH_NETFLT*/
4748 /** @todo r=bird: Put this in a function. */
4749
4750 HostNetworkInterfaceType_T eIfType;
4751 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4752 if (FAILED(hrc))
4753 {
4754 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4755 H();
4756 }
4757
4758 if (eIfType != HostNetworkInterfaceType_HostOnly)
4759 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4760 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4761 HostOnlyName.raw());
4762
4763 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4764 if (FAILED(hrc))
4765 {
4766 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4767 H();
4768 }
4769 Guid hostIFGuid(bstr);
4770
4771 INetCfg *pNc;
4772 ComPtr<INetCfgComponent> pAdaptorComponent;
4773 LPWSTR pszApp;
4774 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4775 Assert(hrc == S_OK);
4776 if (hrc != S_OK)
4777 {
4778 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4779 H();
4780 }
4781
4782 /* get the adapter's INetCfgComponent*/
4783 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4784 if (hrc != S_OK)
4785 {
4786 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4787 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4788 H();
4789 }
4790# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4791 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4792 char *pszTrunkName = szTrunkName;
4793 wchar_t * pswzBindName;
4794 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4795 Assert(hrc == S_OK);
4796 if (hrc == S_OK)
4797 {
4798 int cwBindName = (int)wcslen(pswzBindName) + 1;
4799 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4800 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4801 {
4802 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4803 pszTrunkName += cbFullBindNamePrefix-1;
4804 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4805 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4806 {
4807 DWORD err = GetLastError();
4808 hrc = HRESULT_FROM_WIN32(err);
4809 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4810 }
4811 }
4812 else
4813 {
4814 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4815 /** @todo set appropriate error code */
4816 hrc = E_FAIL;
4817 }
4818
4819 if (hrc != S_OK)
4820 {
4821 AssertFailed();
4822 CoTaskMemFree(pswzBindName);
4823 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4824 H();
4825 }
4826 }
4827 else
4828 {
4829 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4830 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4831 H();
4832 }
4833
4834
4835 CoTaskMemFree(pswzBindName);
4836
4837 pAdaptorComponent.setNull();
4838 /* release the pNc finally */
4839 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4840
4841 const char *pszTrunk = szTrunkName;
4842
4843 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4844 InsertConfigString(pCfg, "Trunk", pszTrunk);
4845 InsertConfigString(pCfg, "Network", szNetwork);
4846 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this windows only?? */
4847 networkName = Bstr(szNetwork);
4848 trunkName = Bstr(pszTrunk);
4849 trunkType = TRUNKTYPE_NETADP;
4850# endif /* defined VBOX_WITH_NETFLT*/
4851#elif defined(RT_OS_DARWIN)
4852 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4853 InsertConfigString(pCfg, "Network", szNetwork);
4854 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4855 networkName = Bstr(szNetwork);
4856 trunkName = Bstr(pszHostOnlyName);
4857 trunkType = TRUNKTYPE_NETADP;
4858#else
4859 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4860 InsertConfigString(pCfg, "Network", szNetwork);
4861 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4862 networkName = Bstr(szNetwork);
4863 trunkName = Bstr(pszHostOnlyName);
4864 trunkType = TRUNKTYPE_NETFLT;
4865#endif
4866 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4867
4868#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4869
4870 Bstr tmpAddr, tmpMask;
4871
4872 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4873 pszHostOnlyName).raw(),
4874 tmpAddr.asOutParam());
4875 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4876 {
4877 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4878 pszHostOnlyName).raw(),
4879 tmpMask.asOutParam());
4880 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4881 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4882 tmpMask.raw());
4883 else
4884 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4885 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4886 }
4887 else
4888 {
4889 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4890 hrc = hostInterface->EnableStaticIPConfig(getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw(),
4891 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4892 }
4893
4894 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4895
4896 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4897 pszHostOnlyName).raw(),
4898 tmpAddr.asOutParam());
4899 if (SUCCEEDED(hrc))
4900 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHostOnlyName).raw(),
4901 tmpMask.asOutParam());
4902 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4903 {
4904 hrc = hostInterface->EnableStaticIPConfigV6(tmpAddr.raw(),
4905 Utf8Str(tmpMask).toUInt32());
4906 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4907 }
4908#endif
4909 break;
4910 }
4911
4912 case NetworkAttachmentType_Generic:
4913 {
4914 hrc = aNetworkAdapter->COMGETTER(GenericDriver)(bstr.asOutParam()); H();
4915 SafeArray<BSTR> names;
4916 SafeArray<BSTR> values;
4917 hrc = aNetworkAdapter->GetProperties(Bstr().raw(),
4918 ComSafeArrayAsOutParam(names),
4919 ComSafeArrayAsOutParam(values)); H();
4920
4921 InsertConfigString(pLunL0, "Driver", bstr);
4922 InsertConfigNode(pLunL0, "Config", &pCfg);
4923 for (size_t ii = 0; ii < names.size(); ++ii)
4924 {
4925 if (values[ii] && *values[ii])
4926 {
4927 Utf8Str name = names[ii];
4928 Utf8Str value = values[ii];
4929 InsertConfigString(pCfg, name.c_str(), value);
4930 }
4931 }
4932 break;
4933 }
4934
4935 case NetworkAttachmentType_NATNetwork:
4936 {
4937 hrc = aNetworkAdapter->COMGETTER(NATNetwork)(bstr.asOutParam()); H();
4938 if (!bstr.isEmpty())
4939 {
4940 /** @todo add intnet prefix to separate namespaces, and add trunk if dealing with vboxnatX */
4941 InsertConfigString(pLunL0, "Driver", "IntNet");
4942 InsertConfigNode(pLunL0, "Config", &pCfg);
4943 InsertConfigString(pCfg, "Network", bstr);
4944 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4945 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4946 networkName = bstr;
4947 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4948 }
4949 break;
4950 }
4951
4952 default:
4953 AssertMsgFailed(("should not get here!\n"));
4954 break;
4955 }
4956
4957 /*
4958 * Attempt to attach the driver.
4959 */
4960 switch (eAttachmentType)
4961 {
4962 case NetworkAttachmentType_Null:
4963 break;
4964
4965 case NetworkAttachmentType_Bridged:
4966 case NetworkAttachmentType_Internal:
4967 case NetworkAttachmentType_HostOnly:
4968 case NetworkAttachmentType_NAT:
4969 case NetworkAttachmentType_Generic:
4970 case NetworkAttachmentType_NATNetwork:
4971 {
4972 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4973 {
4974 if (fAttachDetach)
4975 {
4976 rc = PDMR3DriverAttach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4977 //AssertRC(rc);
4978 }
4979
4980 {
4981 /** @todo pritesh: get the dhcp server name from the
4982 * previous network configuration and then stop the server
4983 * else it may conflict with the dhcp server running with
4984 * the current attachment type
4985 */
4986 /* Stop the hostonly DHCP Server */
4987 }
4988
4989 if (!networkName.isEmpty())
4990 {
4991 /*
4992 * Until we implement service reference counters DHCP Server will be stopped
4993 * by DHCPServerRunner destructor.
4994 */
4995 ComPtr<IDHCPServer> dhcpServer;
4996 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4997 dhcpServer.asOutParam());
4998 if (SUCCEEDED(hrc))
4999 {
5000 /* there is a DHCP server available for this network */
5001 BOOL fEnabledDhcp;
5002 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabledDhcp);
5003 if (FAILED(hrc))
5004 {
5005 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)\n", hrc));
5006 H();
5007 }
5008
5009 if (fEnabledDhcp)
5010 hrc = dhcpServer->Start(networkName.raw(),
5011 trunkName.raw(),
5012 trunkType.raw());
5013 }
5014 else
5015 hrc = S_OK;
5016 }
5017 }
5018
5019 break;
5020 }
5021
5022 default:
5023 AssertMsgFailed(("should not get here!\n"));
5024 break;
5025 }
5026
5027 meAttachmentType[uInstance] = eAttachmentType;
5028 }
5029 catch (ConfigError &x)
5030 {
5031 // InsertConfig threw something:
5032 return x.m_vrc;
5033 }
5034
5035#undef H
5036
5037 return VINF_SUCCESS;
5038}
5039
5040#ifdef VBOX_WITH_GUEST_PROPS
5041/**
5042 * Set an array of guest properties
5043 */
5044static void configSetProperties(VMMDev * const pVMMDev,
5045 void *names,
5046 void *values,
5047 void *timestamps,
5048 void *flags)
5049{
5050 VBOXHGCMSVCPARM parms[4];
5051
5052 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5053 parms[0].u.pointer.addr = names;
5054 parms[0].u.pointer.size = 0; /* We don't actually care. */
5055 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5056 parms[1].u.pointer.addr = values;
5057 parms[1].u.pointer.size = 0; /* We don't actually care. */
5058 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
5059 parms[2].u.pointer.addr = timestamps;
5060 parms[2].u.pointer.size = 0; /* We don't actually care. */
5061 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
5062 parms[3].u.pointer.addr = flags;
5063 parms[3].u.pointer.size = 0; /* We don't actually care. */
5064
5065 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
5066 guestProp::SET_PROPS_HOST,
5067 4,
5068 &parms[0]);
5069}
5070
5071/**
5072 * Set a single guest property
5073 */
5074static void configSetProperty(VMMDev * const pVMMDev,
5075 const char *pszName,
5076 const char *pszValue,
5077 const char *pszFlags)
5078{
5079 VBOXHGCMSVCPARM parms[4];
5080
5081 AssertPtrReturnVoid(pszName);
5082 AssertPtrReturnVoid(pszValue);
5083 AssertPtrReturnVoid(pszFlags);
5084 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5085 parms[0].u.pointer.addr = (void *)pszName;
5086 parms[0].u.pointer.size = (uint32_t)strlen(pszName) + 1;
5087 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5088 parms[1].u.pointer.addr = (void *)pszValue;
5089 parms[1].u.pointer.size = (uint32_t)strlen(pszValue) + 1;
5090 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
5091 parms[2].u.pointer.addr = (void *)pszFlags;
5092 parms[2].u.pointer.size = (uint32_t)strlen(pszFlags) + 1;
5093 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
5094 &parms[0]);
5095}
5096
5097/**
5098 * Set the global flags value by calling the service
5099 * @returns the status returned by the call to the service
5100 *
5101 * @param pTable the service instance handle
5102 * @param eFlags the flags to set
5103 */
5104int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
5105 guestProp::ePropFlags eFlags)
5106{
5107 VBOXHGCMSVCPARM paParm;
5108 paParm.setUInt32(eFlags);
5109 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
5110 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
5111 &paParm);
5112 if (RT_FAILURE(rc))
5113 {
5114 char szFlags[guestProp::MAX_FLAGS_LEN];
5115 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
5116 Log(("Failed to set the global flags.\n"));
5117 else
5118 Log(("Failed to set the global flags \"%s\".\n", szFlags));
5119 }
5120 return rc;
5121}
5122#endif /* VBOX_WITH_GUEST_PROPS */
5123
5124/**
5125 * Set up the Guest Property service, populate it with properties read from
5126 * the machine XML and set a couple of initial properties.
5127 */
5128/* static */ int Console::configGuestProperties(void *pvConsole, PUVM pUVM)
5129{
5130#ifdef VBOX_WITH_GUEST_PROPS
5131 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5132 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5133 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
5134
5135 /* Load the service */
5136 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
5137
5138 if (RT_FAILURE(rc))
5139 {
5140 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
5141 /* That is not a fatal failure. */
5142 rc = VINF_SUCCESS;
5143 }
5144 else
5145 {
5146 /*
5147 * Initialize built-in properties that can be changed and saved.
5148 *
5149 * These are typically transient properties that the guest cannot
5150 * change.
5151 */
5152
5153 {
5154 VBOXHGCMSVCPARM Params[2];
5155 int rc2 = pConsole->m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::GET_DBGF_INFO_FN, 2, &Params[0]);
5156 if (RT_SUCCESS(rc2))
5157 {
5158 PFNDBGFHANDLEREXT pfnHandler = (PFNDBGFHANDLEREXT)(uintptr_t)Params[0].u.pointer.addr;
5159 void *pService = (void*)Params[1].u.pointer.addr;
5160 DBGFR3InfoRegisterExternal(pUVM, "guestprops", "Display the guest properties", pfnHandler, pService);
5161 }
5162 }
5163
5164 /* Sysprep execution by VBoxService. */
5165 configSetProperty(pConsole->m_pVMMDev,
5166 "/VirtualBox/HostGuest/SysprepExec", "",
5167 "TRANSIENT, RDONLYGUEST");
5168 configSetProperty(pConsole->m_pVMMDev,
5169 "/VirtualBox/HostGuest/SysprepArgs", "",
5170 "TRANSIENT, RDONLYGUEST");
5171
5172 /*
5173 * Pull over the properties from the server.
5174 */
5175 SafeArray<BSTR> namesOut;
5176 SafeArray<BSTR> valuesOut;
5177 SafeArray<LONG64> timestampsOut;
5178 SafeArray<BSTR> flagsOut;
5179 HRESULT hrc;
5180 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
5181 ComSafeArrayAsOutParam(valuesOut),
5182 ComSafeArrayAsOutParam(timestampsOut),
5183 ComSafeArrayAsOutParam(flagsOut));
5184 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE);
5185 size_t cProps = namesOut.size();
5186 size_t cAlloc = cProps + 1;
5187 if ( valuesOut.size() != cProps
5188 || timestampsOut.size() != cProps
5189 || flagsOut.size() != cProps
5190 )
5191 AssertFailedReturn(VERR_INVALID_PARAMETER);
5192
5193 char **papszNames, **papszValues, **papszFlags;
5194 char szEmpty[] = "";
5195 LONG64 *pai64Timestamps;
5196 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5197 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5198 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
5199 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5200 if (papszNames && papszValues && pai64Timestamps && papszFlags)
5201 {
5202 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
5203 {
5204 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
5205 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
5206 if (RT_FAILURE(rc))
5207 break;
5208 if (valuesOut[i])
5209 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
5210 else
5211 papszValues[i] = szEmpty;
5212 if (RT_FAILURE(rc))
5213 break;
5214 pai64Timestamps[i] = timestampsOut[i];
5215 if (flagsOut[i])
5216 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
5217 else
5218 papszFlags[i] = szEmpty;
5219 }
5220 if (RT_SUCCESS(rc))
5221 configSetProperties(pConsole->m_pVMMDev,
5222 (void *)papszNames,
5223 (void *)papszValues,
5224 (void *)pai64Timestamps,
5225 (void *)papszFlags);
5226 for (unsigned i = 0; i < cProps; ++i)
5227 {
5228 RTStrFree(papszNames[i]);
5229 if (valuesOut[i])
5230 RTStrFree(papszValues[i]);
5231 if (flagsOut[i])
5232 RTStrFree(papszFlags[i]);
5233 }
5234 }
5235 else
5236 rc = VERR_NO_MEMORY;
5237 RTMemTmpFree(papszNames);
5238 RTMemTmpFree(papszValues);
5239 RTMemTmpFree(pai64Timestamps);
5240 RTMemTmpFree(papszFlags);
5241 AssertRCReturn(rc, rc);
5242
5243 /*
5244 * These properties have to be set before pulling over the properties
5245 * from the machine XML, to ensure that properties saved in the XML
5246 * will override them.
5247 */
5248 /* Set the raw VBox version string as a guest property. Used for host/guest
5249 * version comparison. */
5250 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
5251 VBOX_VERSION_STRING_RAW, "TRANSIENT, RDONLYGUEST");
5252 /* Set the full VBox version string as a guest property. Can contain vendor-specific
5253 * information/branding and/or pre-release tags. */
5254 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVerExt",
5255 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
5256 /* Set the VBox SVN revision as a guest property */
5257 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
5258 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
5259
5260 /*
5261 * Register the host notification callback
5262 */
5263 HGCMSVCEXTHANDLE hDummy;
5264 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
5265 Console::doGuestPropNotification,
5266 pvConsole);
5267
5268#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
5269 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
5270 guestProp::RDONLYGUEST);
5271 AssertRCReturn(rc, rc);
5272#endif
5273
5274 Log(("Set VBoxGuestPropSvc property store\n"));
5275 }
5276 return VINF_SUCCESS;
5277#else /* !VBOX_WITH_GUEST_PROPS */
5278 return VERR_NOT_SUPPORTED;
5279#endif /* !VBOX_WITH_GUEST_PROPS */
5280}
5281
5282/**
5283 * Set up the Guest Control service.
5284 */
5285/* static */ int Console::configGuestControl(void *pvConsole)
5286{
5287#ifdef VBOX_WITH_GUEST_CONTROL
5288 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5289 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5290
5291 /* Load the service */
5292 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
5293
5294 if (RT_FAILURE(rc))
5295 {
5296 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
5297 /* That is not a fatal failure. */
5298 rc = VINF_SUCCESS;
5299 }
5300 else
5301 {
5302 HGCMSVCEXTHANDLE hDummy;
5303 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
5304 &Guest::notifyCtrlDispatcher,
5305 pConsole->getGuest());
5306 if (RT_FAILURE(rc))
5307 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
5308 else
5309 Log(("VBoxGuestControlSvc loaded\n"));
5310 }
5311
5312 return rc;
5313#else /* !VBOX_WITH_GUEST_CONTROL */
5314 return VERR_NOT_SUPPORTED;
5315#endif /* !VBOX_WITH_GUEST_CONTROL */
5316}
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