VirtualBox

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

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

Main: don't log the medium type of host DVD drives

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

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