VirtualBox

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

Last change on this file since 48701 was 48701, checked in by vboxsync, 12 years ago

Introduced /CPUM/MaxIntelFamilyModelStep config variable to hack Mac OS X guests into working.

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

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