VirtualBox

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

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

Main/Mouse: add priorities to mouse devices so that the USB mouse is preferred over the PS/2 one when supported by the guest.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 214.7 KB
Line 
1/* $Id: ConsoleImpl2.cpp 47758 2013-08-15 12:39:09Z 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 = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Exclusive, &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 {
2448 InsertConfigNode(pUsbDevices, "HidMouse", &pDev);
2449 InsertConfigNode(pDev, "0", &pInst);
2450 InsertConfigNode(pInst, "Config", &pCfg);
2451
2452 InsertConfigString(pCfg, "Mode", "relative");
2453 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2454 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2455 InsertConfigNode(pLunL0, "Config", &pCfg);
2456 InsertConfigInteger(pCfg, "QueueSize", 128);
2457
2458 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2459 InsertConfigString(pLunL1, "Driver", "MainMouse");
2460 InsertConfigNode(pLunL1, "Config", &pCfg);
2461 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2462 InsertConfigInteger(pCfg, "Priority", 2); /* Prefer over PS/2 */
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 && ( lType == DeviceType_DVD
3558 || lType == DeviceType_Floppy))
3559 {
3560 /*
3561 * Informative logging.
3562 */
3563 ComPtr<IMediumFormat> pMediumFormat;
3564 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3565 ULONG uCaps = 0;
3566 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
3567 hrc = pMediumFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap)); H();
3568
3569 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
3570 uCaps |= mediumFormatCap[j];
3571
3572 if (uCaps & MediumFormatCapabilities_File)
3573 {
3574 Bstr strFile;
3575 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3576 Utf8Str utfFile = Utf8Str(strFile);
3577 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3578 (void)RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3579 LogRel(("File system of '%s' (%s) is %s\n",
3580 utfFile.c_str(), lType == DeviceType_DVD ? "DVD" : "Floppy",
3581 RTFsTypeName(enmFsTypeFile)));
3582 }
3583 }
3584
3585 BOOL fPassthrough;
3586 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
3587
3588 ComObjPtr<IBandwidthGroup> pBwGroup;
3589 Bstr strBwGroup;
3590 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3591
3592 if (!pBwGroup.isNull())
3593 {
3594 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3595 }
3596
3597 rc = configMedium(pLunL0,
3598 !!fPassthrough,
3599 lType,
3600 fUseHostIOCache,
3601 fBuiltinIOCache,
3602 fSetupMerge,
3603 uMergeSource,
3604 uMergeTarget,
3605 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3606 !!fDiscard,
3607 pMedium,
3608 aMachineState,
3609 phrc);
3610 if (RT_FAILURE(rc))
3611 return rc;
3612
3613 if (fAttachDetach)
3614 {
3615 /* Attach the new driver. */
3616 rc = PDMR3DeviceAttach(pUVM, pcszDevice, uInstance, uLUN,
3617 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3618 AssertRCReturn(rc, rc);
3619
3620 /* There is no need to handle removable medium mounting, as we
3621 * unconditionally replace everthing including the block driver level.
3622 * This means the new medium will be picked up automatically. */
3623 }
3624
3625 if (paLedDevType)
3626 paLedDevType[uLUN] = lType;
3627 }
3628 catch (ConfigError &x)
3629 {
3630 // InsertConfig threw something:
3631 return x.m_vrc;
3632 }
3633
3634#undef H
3635
3636 return VINF_SUCCESS;
3637}
3638
3639int Console::configMedium(PCFGMNODE pLunL0,
3640 bool fPassthrough,
3641 DeviceType_T enmType,
3642 bool fUseHostIOCache,
3643 bool fBuiltinIOCache,
3644 bool fSetupMerge,
3645 unsigned uMergeSource,
3646 unsigned uMergeTarget,
3647 const char *pcszBwGroup,
3648 bool fDiscard,
3649 IMedium *pMedium,
3650 MachineState_T aMachineState,
3651 HRESULT *phrc)
3652{
3653 // InsertConfig* throws
3654 try
3655 {
3656 int rc = VINF_SUCCESS;
3657 HRESULT hrc;
3658 Bstr bstr;
3659 PCFGMNODE pLunL1 = NULL;
3660 PCFGMNODE pCfg = NULL;
3661
3662#define H() \
3663 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
3664
3665
3666 BOOL fHostDrive = FALSE;
3667 MediumType_T mediumType = MediumType_Normal;
3668 if (pMedium)
3669 {
3670 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3671 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3672 }
3673
3674 if (fHostDrive)
3675 {
3676 Assert(pMedium);
3677 if (enmType == DeviceType_DVD)
3678 {
3679 InsertConfigString(pLunL0, "Driver", "HostDVD");
3680 InsertConfigNode(pLunL0, "Config", &pCfg);
3681
3682 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3683 InsertConfigString(pCfg, "Path", bstr);
3684
3685 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3686 }
3687 else if (enmType == DeviceType_Floppy)
3688 {
3689 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3690 InsertConfigNode(pLunL0, "Config", &pCfg);
3691
3692 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3693 InsertConfigString(pCfg, "Path", bstr);
3694 }
3695 }
3696 else
3697 {
3698 InsertConfigString(pLunL0, "Driver", "Block");
3699 InsertConfigNode(pLunL0, "Config", &pCfg);
3700 switch (enmType)
3701 {
3702 case DeviceType_DVD:
3703 InsertConfigString(pCfg, "Type", "DVD");
3704 InsertConfigInteger(pCfg, "Mountable", 1);
3705 break;
3706 case DeviceType_Floppy:
3707 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3708 InsertConfigInteger(pCfg, "Mountable", 1);
3709 break;
3710 case DeviceType_HardDisk:
3711 default:
3712 InsertConfigString(pCfg, "Type", "HardDisk");
3713 InsertConfigInteger(pCfg, "Mountable", 0);
3714 }
3715
3716 if ( pMedium
3717 && ( enmType == DeviceType_DVD
3718 || enmType == DeviceType_Floppy)
3719 )
3720 {
3721 // if this medium represents an ISO image and this image is inaccessible,
3722 // the ignore it instead of causing a failure; this can happen when we
3723 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3724 // Additions were mounted and the user upgraded VirtualBox. Previously
3725 // we failed on startup, but that's not good because the only way out then
3726 // would be to discard the VM state...
3727 MediumState_T mediumState;
3728 hrc = pMedium->RefreshState(&mediumState); H();
3729 if (mediumState == MediumState_Inaccessible)
3730 {
3731 Bstr loc;
3732 hrc = pMedium->COMGETTER(Location)(loc.asOutParam()); H();
3733 setVMRuntimeErrorCallbackF(0, "DvdOrFloppyImageInaccessible",
3734 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3735 loc.raw(),
3736 enmType == DeviceType_DVD ? "DVD" : "floppy");
3737 pMedium = NULL;
3738 }
3739 }
3740
3741 if (pMedium)
3742 {
3743 /* Start with length of parent chain, as the list is reversed */
3744 unsigned uImage = 0;
3745 IMedium *pTmp = pMedium;
3746 while (pTmp)
3747 {
3748 uImage++;
3749 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3750 }
3751 /* Index of last image */
3752 uImage--;
3753
3754#if 0 /* Enable for I/O debugging */
3755 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3756 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3757 InsertConfigNode(pLunL0, "Config", &pCfg);
3758 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3759 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3760#endif
3761
3762 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3763 InsertConfigString(pLunL1, "Driver", "VD");
3764 InsertConfigNode(pLunL1, "Config", &pCfg);
3765
3766 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3767 InsertConfigString(pCfg, "Path", bstr);
3768
3769 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3770 InsertConfigString(pCfg, "Format", bstr);
3771
3772 if (mediumType == MediumType_Readonly)
3773 InsertConfigInteger(pCfg, "ReadOnly", 1);
3774 else if (enmType == DeviceType_Floppy)
3775 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3776
3777 /* Start without exclusive write access to the images. */
3778 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3779 * we're resuming the VM if some 3rd dude have any of the VDIs open
3780 * with write sharing denied. However, if the two VMs are sharing a
3781 * image it really is necessary....
3782 *
3783 * So, on the "lock-media" command, the target teleporter should also
3784 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3785 * that. Grumble. */
3786 if ( enmType == DeviceType_HardDisk
3787 && ( aMachineState == MachineState_TeleportingIn
3788 || aMachineState == MachineState_FaultTolerantSyncing))
3789 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3790
3791 /* Flag for opening the medium for sharing between VMs. This
3792 * is done at the moment only for the first (and only) medium
3793 * in the chain, as shared media can have no diffs. */
3794 if (mediumType == MediumType_Shareable)
3795 InsertConfigInteger(pCfg, "Shareable", 1);
3796
3797 if (!fUseHostIOCache)
3798 {
3799 InsertConfigInteger(pCfg, "UseNewIo", 1);
3800 /*
3801 * Activate the builtin I/O cache for harddisks only.
3802 * It caches writes only which doesn't make sense for DVD drives
3803 * and just increases the overhead.
3804 */
3805 if ( fBuiltinIOCache
3806 && (enmType == DeviceType_HardDisk))
3807 InsertConfigInteger(pCfg, "BlockCache", 1);
3808 }
3809
3810 if (fSetupMerge)
3811 {
3812 InsertConfigInteger(pCfg, "SetupMerge", 1);
3813 if (uImage == uMergeSource)
3814 InsertConfigInteger(pCfg, "MergeSource", 1);
3815 else if (uImage == uMergeTarget)
3816 InsertConfigInteger(pCfg, "MergeTarget", 1);
3817 }
3818
3819 switch (enmType)
3820 {
3821 case DeviceType_DVD:
3822 InsertConfigString(pCfg, "Type", "DVD");
3823 break;
3824 case DeviceType_Floppy:
3825 InsertConfigString(pCfg, "Type", "Floppy");
3826 break;
3827 case DeviceType_HardDisk:
3828 default:
3829 InsertConfigString(pCfg, "Type", "HardDisk");
3830 }
3831
3832 if (pcszBwGroup)
3833 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3834
3835 if (fDiscard)
3836 InsertConfigInteger(pCfg, "Discard", 1);
3837
3838 /* Pass all custom parameters. */
3839 bool fHostIP = true;
3840 SafeArray<BSTR> names;
3841 SafeArray<BSTR> values;
3842 hrc = pMedium->GetProperties(Bstr().raw(),
3843 ComSafeArrayAsOutParam(names),
3844 ComSafeArrayAsOutParam(values)); H();
3845
3846 if (names.size() != 0)
3847 {
3848 PCFGMNODE pVDC;
3849 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3850 for (size_t ii = 0; ii < names.size(); ++ii)
3851 {
3852 if (values[ii] && *values[ii])
3853 {
3854 Utf8Str name = names[ii];
3855 Utf8Str value = values[ii];
3856 InsertConfigString(pVDC, name.c_str(), value);
3857 if ( name.compare("HostIPStack") == 0
3858 && value.compare("0") == 0)
3859 fHostIP = false;
3860 }
3861 }
3862 }
3863
3864 /* Create an inverted list of parents. */
3865 uImage--;
3866 IMedium *pParentMedium = pMedium;
3867 for (PCFGMNODE pParent = pCfg;; uImage--)
3868 {
3869 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3870 if (!pMedium)
3871 break;
3872
3873 PCFGMNODE pCur;
3874 InsertConfigNode(pParent, "Parent", &pCur);
3875 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3876 InsertConfigString(pCur, "Path", bstr);
3877
3878 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3879 InsertConfigString(pCur, "Format", bstr);
3880
3881 if (fSetupMerge)
3882 {
3883 if (uImage == uMergeSource)
3884 InsertConfigInteger(pCur, "MergeSource", 1);
3885 else if (uImage == uMergeTarget)
3886 InsertConfigInteger(pCur, "MergeTarget", 1);
3887 }
3888
3889 /* Pass all custom parameters. */
3890 SafeArray<BSTR> aNames;
3891 SafeArray<BSTR> aValues;
3892 hrc = pMedium->GetProperties(NULL,
3893 ComSafeArrayAsOutParam(aNames),
3894 ComSafeArrayAsOutParam(aValues)); H();
3895
3896 if (aNames.size() != 0)
3897 {
3898 PCFGMNODE pVDC;
3899 InsertConfigNode(pCur, "VDConfig", &pVDC);
3900 for (size_t ii = 0; ii < aNames.size(); ++ii)
3901 {
3902 if (aValues[ii] && *aValues[ii])
3903 {
3904 Utf8Str name = aNames[ii];
3905 Utf8Str value = aValues[ii];
3906 InsertConfigString(pVDC, name.c_str(), value);
3907 if ( name.compare("HostIPStack") == 0
3908 && value.compare("0") == 0)
3909 fHostIP = false;
3910 }
3911 }
3912 }
3913
3914 /* next */
3915 pParent = pCur;
3916 pParentMedium = pMedium;
3917 }
3918
3919 /* Custom code: put marker to not use host IP stack to driver
3920 * configuration node. Simplifies life of DrvVD a bit. */
3921 if (!fHostIP)
3922 InsertConfigInteger(pCfg, "HostIPStack", 0);
3923 }
3924 }
3925#undef H
3926 }
3927 catch (ConfigError &x)
3928 {
3929 // InsertConfig threw something:
3930 return x.m_vrc;
3931 }
3932
3933 return VINF_SUCCESS;
3934}
3935
3936/**
3937 * Construct the Network configuration tree
3938 *
3939 * @returns VBox status code.
3940 *
3941 * @param pszDevice The PDM device name.
3942 * @param uInstance The PDM device instance.
3943 * @param uLun The PDM LUN number of the drive.
3944 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3945 * @param pCfg Configuration node for the device
3946 * @param pLunL0 To store the pointer to the LUN#0.
3947 * @param pInst The instance CFGM node
3948 * @param fAttachDetach To determine if the network attachment should
3949 * be attached/detached after/before
3950 * configuration.
3951 * @param fIgnoreConnectFailure
3952 * True if connection failures should be ignored
3953 * (makes only sense for bridged/host-only networks).
3954 *
3955 * @note Locks this object for writing.
3956 * @thread EMT
3957 */
3958int Console::configNetwork(const char *pszDevice,
3959 unsigned uInstance,
3960 unsigned uLun,
3961 INetworkAdapter *aNetworkAdapter,
3962 PCFGMNODE pCfg,
3963 PCFGMNODE pLunL0,
3964 PCFGMNODE pInst,
3965 bool fAttachDetach,
3966 bool fIgnoreConnectFailure)
3967{
3968 AutoCaller autoCaller(this);
3969 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3970
3971 // InsertConfig* throws
3972 try
3973 {
3974 int rc = VINF_SUCCESS;
3975 HRESULT hrc;
3976 Bstr bstr;
3977
3978#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3979
3980 /*
3981 * Locking the object before doing VMR3* calls is quite safe here, since
3982 * we're on EMT. Write lock is necessary because we indirectly modify the
3983 * meAttachmentType member.
3984 */
3985 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3986
3987 ComPtr<IMachine> pMachine = machine();
3988
3989 ComPtr<IVirtualBox> virtualBox;
3990 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
3991
3992 ComPtr<IHost> host;
3993 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
3994
3995 BOOL fSniffer;
3996 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
3997
3998 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
3999 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
4000 const char *pszPromiscuousGuestPolicy;
4001 switch (enmPromiscModePolicy)
4002 {
4003 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
4004 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
4005 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
4006 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
4007 }
4008
4009 if (fAttachDetach)
4010 {
4011 rc = PDMR3DeviceDetach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
4012 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4013 rc = VINF_SUCCESS;
4014 AssertLogRelRCReturn(rc, rc);
4015
4016 /* nuke anything which might have been left behind. */
4017 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
4018 }
4019
4020#ifdef VBOX_WITH_NETSHAPER
4021 ComObjPtr<IBandwidthGroup> pBwGroup;
4022 Bstr strBwGroup;
4023 hrc = aNetworkAdapter->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
4024
4025 if (!pBwGroup.isNull())
4026 {
4027 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
4028 }
4029#endif /* VBOX_WITH_NETSHAPER */
4030
4031 Utf8Str strNetDriver;
4032
4033
4034 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4035
4036#ifdef VBOX_WITH_NETSHAPER
4037 if (!strBwGroup.isEmpty())
4038 {
4039 InsertConfigString(pLunL0, "Driver", "NetShaper");
4040 InsertConfigNode(pLunL0, "Config", &pCfg);
4041 InsertConfigString(pCfg, "BwGroup", strBwGroup);
4042 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4043 }
4044#endif /* VBOX_WITH_NETSHAPER */
4045
4046 if (fSniffer)
4047 {
4048 InsertConfigString(pLunL0, "Driver", "NetSniffer");
4049 InsertConfigNode(pLunL0, "Config", &pCfg);
4050 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
4051 if (!bstr.isEmpty()) /* check convention for indicating default file. */
4052 InsertConfigString(pCfg, "File", bstr);
4053 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4054 }
4055
4056
4057 Bstr networkName, trunkName, trunkType;
4058 NetworkAttachmentType_T eAttachmentType;
4059 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
4060 switch (eAttachmentType)
4061 {
4062 case NetworkAttachmentType_Null:
4063 break;
4064
4065 case NetworkAttachmentType_NAT:
4066 {
4067 ComPtr<INATEngine> natEngine;
4068 hrc = aNetworkAdapter->COMGETTER(NATEngine)(natEngine.asOutParam()); H();
4069 InsertConfigString(pLunL0, "Driver", "NAT");
4070 InsertConfigNode(pLunL0, "Config", &pCfg);
4071
4072 /* Configure TFTP prefix and boot filename. */
4073 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
4074 if (!bstr.isEmpty())
4075 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
4076 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
4077 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
4078
4079 hrc = natEngine->COMGETTER(Network)(bstr.asOutParam()); H();
4080 if (!bstr.isEmpty())
4081 InsertConfigString(pCfg, "Network", bstr);
4082 else
4083 {
4084 ULONG uSlot;
4085 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
4086 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
4087 }
4088 hrc = natEngine->COMGETTER(HostIP)(bstr.asOutParam()); H();
4089 if (!bstr.isEmpty())
4090 InsertConfigString(pCfg, "BindIP", bstr);
4091 ULONG mtu = 0;
4092 ULONG sockSnd = 0;
4093 ULONG sockRcv = 0;
4094 ULONG tcpSnd = 0;
4095 ULONG tcpRcv = 0;
4096 hrc = natEngine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
4097 if (mtu)
4098 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
4099 if (sockRcv)
4100 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
4101 if (sockSnd)
4102 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
4103 if (tcpRcv)
4104 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
4105 if (tcpSnd)
4106 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
4107 hrc = natEngine->COMGETTER(TFTPPrefix)(bstr.asOutParam()); H();
4108 if (!bstr.isEmpty())
4109 {
4110 RemoveConfigValue(pCfg, "TFTPPrefix");
4111 InsertConfigString(pCfg, "TFTPPrefix", bstr);
4112 }
4113 hrc = natEngine->COMGETTER(TFTPBootFile)(bstr.asOutParam()); H();
4114 if (!bstr.isEmpty())
4115 {
4116 RemoveConfigValue(pCfg, "BootFile");
4117 InsertConfigString(pCfg, "BootFile", bstr);
4118 }
4119 hrc = natEngine->COMGETTER(TFTPNextServer)(bstr.asOutParam()); H();
4120 if (!bstr.isEmpty())
4121 InsertConfigString(pCfg, "NextServer", bstr);
4122 BOOL fDNSFlag;
4123 hrc = natEngine->COMGETTER(DNSPassDomain)(&fDNSFlag); H();
4124 InsertConfigInteger(pCfg, "PassDomain", fDNSFlag);
4125 hrc = natEngine->COMGETTER(DNSProxy)(&fDNSFlag); H();
4126 InsertConfigInteger(pCfg, "DNSProxy", fDNSFlag);
4127 hrc = natEngine->COMGETTER(DNSUseHostResolver)(&fDNSFlag); H();
4128 InsertConfigInteger(pCfg, "UseHostResolver", fDNSFlag);
4129
4130 ULONG aliasMode;
4131 hrc = natEngine->COMGETTER(AliasMode)(&aliasMode); H();
4132 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
4133
4134 /* port-forwarding */
4135 SafeArray<BSTR> pfs;
4136 hrc = natEngine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
4137 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
4138 for (unsigned int i = 0; i < pfs.size(); ++i)
4139 {
4140 uint16_t port = 0;
4141 BSTR r = pfs[i];
4142 Utf8Str utf = Utf8Str(r);
4143 Utf8Str strName;
4144 Utf8Str strProto;
4145 Utf8Str strHostPort;
4146 Utf8Str strHostIP;
4147 Utf8Str strGuestPort;
4148 Utf8Str strGuestIP;
4149 size_t pos, ppos;
4150 pos = ppos = 0;
4151#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
4152 do { \
4153 pos = str.find(",", ppos); \
4154 if (pos == Utf8Str::npos) \
4155 { \
4156 Log(( #res " extracting from %s is failed\n", str.c_str())); \
4157 continue; \
4158 } \
4159 res = str.substr(ppos, pos - ppos); \
4160 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
4161 ppos = pos + 1; \
4162 } while (0)
4163 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
4164 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
4165 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
4166 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
4167 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
4168 strGuestPort = utf.substr(ppos, utf.length() - ppos);
4169#undef ITERATE_TO_NEXT_TERM
4170
4171 uint32_t proto = strProto.toUInt32();
4172 bool fValid = true;
4173 switch (proto)
4174 {
4175 case NATProtocol_UDP:
4176 strProto = "UDP";
4177 break;
4178 case NATProtocol_TCP:
4179 strProto = "TCP";
4180 break;
4181 default:
4182 fValid = false;
4183 }
4184 /* continue with next rule if no valid proto was passed */
4185 if (!fValid)
4186 continue;
4187
4188 InsertConfigNode(pCfg, strName.c_str(), &pPF);
4189 InsertConfigString(pPF, "Protocol", strProto);
4190
4191 if (!strHostIP.isEmpty())
4192 InsertConfigString(pPF, "BindIP", strHostIP);
4193
4194 if (!strGuestIP.isEmpty())
4195 InsertConfigString(pPF, "GuestIP", strGuestIP);
4196
4197 port = RTStrToUInt16(strHostPort.c_str());
4198 if (port)
4199 InsertConfigInteger(pPF, "HostPort", port);
4200
4201 port = RTStrToUInt16(strGuestPort.c_str());
4202 if (port)
4203 InsertConfigInteger(pPF, "GuestPort", port);
4204 }
4205 break;
4206 }
4207
4208 case NetworkAttachmentType_Bridged:
4209 {
4210#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
4211 hrc = attachToTapInterface(aNetworkAdapter);
4212 if (FAILED(hrc))
4213 {
4214 switch (hrc)
4215 {
4216 case VERR_ACCESS_DENIED:
4217 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4218 "Failed to open '/dev/net/tun' for read/write access. Please check the "
4219 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
4220 "change the group of that node and make yourself a member of that group. Make "
4221 "sure that these changes are permanent, especially if you are "
4222 "using udev"));
4223 default:
4224 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
4225 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4226 "Failed to initialize Host Interface Networking"));
4227 }
4228 }
4229
4230 Assert((int)maTapFD[uInstance] >= 0);
4231 if ((int)maTapFD[uInstance] >= 0)
4232 {
4233 InsertConfigString(pLunL0, "Driver", "HostInterface");
4234 InsertConfigNode(pLunL0, "Config", &pCfg);
4235 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4236 }
4237
4238#elif defined(VBOX_WITH_NETFLT)
4239 /*
4240 * This is the new VBoxNetFlt+IntNet stuff.
4241 */
4242 Bstr BridgedIfName;
4243 hrc = aNetworkAdapter->COMGETTER(BridgedInterface)(BridgedIfName.asOutParam());
4244 if (FAILED(hrc))
4245 {
4246 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(BridgedInterface) failed, hrc (0x%x)\n", hrc));
4247 H();
4248 }
4249
4250 Utf8Str BridgedIfNameUtf8(BridgedIfName);
4251 const char *pszBridgedIfName = BridgedIfNameUtf8.c_str();
4252
4253# if defined(RT_OS_DARWIN)
4254 /* The name is on the form 'ifX: long name', chop it off at the colon. */
4255 char szTrunk[8];
4256 RTStrCopy(szTrunk, sizeof(szTrunk), pszBridgedIfName);
4257 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4258// Quick fix for @bugref{5633}
4259// if (!pszColon)
4260// {
4261// /*
4262// * Dynamic changing of attachment causes an attempt to configure
4263// * network with invalid host adapter (as it is must be changed before
4264// * the attachment), calling Detach here will cause a deadlock.
4265// * See @bugref{4750}.
4266// * hrc = aNetworkAdapter->Detach(); H();
4267// */
4268// return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4269// N_("Malformed host interface networking name '%ls'"),
4270// BridgedIfName.raw());
4271// }
4272 if (pszColon)
4273 *pszColon = '\0';
4274 const char *pszTrunk = szTrunk;
4275
4276# elif defined(RT_OS_SOLARIS)
4277 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
4278 char szTrunk[256];
4279 strlcpy(szTrunk, pszBridgedIfName, sizeof(szTrunk));
4280 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
4281
4282 /*
4283 * Currently don't bother about malformed names here for the sake of people using
4284 * VBoxManage and setting only the NIC name from there. If there is a space we
4285 * chop it off and proceed, otherwise just use whatever we've got.
4286 */
4287 if (pszSpace)
4288 *pszSpace = '\0';
4289
4290 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
4291 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4292 if (pszColon)
4293 *pszColon = '\0';
4294
4295 const char *pszTrunk = szTrunk;
4296
4297# elif defined(RT_OS_WINDOWS)
4298 ComPtr<IHostNetworkInterface> hostInterface;
4299 hrc = host->FindHostNetworkInterfaceByName(BridgedIfName.raw(),
4300 hostInterface.asOutParam());
4301 if (!SUCCEEDED(hrc))
4302 {
4303 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
4304 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4305 N_("Nonexistent host networking interface, name '%ls'"),
4306 BridgedIfName.raw());
4307 }
4308
4309 HostNetworkInterfaceType_T eIfType;
4310 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4311 if (FAILED(hrc))
4312 {
4313 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4314 H();
4315 }
4316
4317 if (eIfType != HostNetworkInterfaceType_Bridged)
4318 {
4319 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4320 N_("Interface ('%ls') is not a Bridged Adapter interface"),
4321 BridgedIfName.raw());
4322 }
4323
4324 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4325 if (FAILED(hrc))
4326 {
4327 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4328 H();
4329 }
4330 Guid hostIFGuid(bstr);
4331
4332 INetCfg *pNc;
4333 ComPtr<INetCfgComponent> pAdaptorComponent;
4334 LPWSTR pszApp;
4335
4336 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4337 Assert(hrc == S_OK);
4338 if (hrc != S_OK)
4339 {
4340 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4341 H();
4342 }
4343
4344 /* get the adapter's INetCfgComponent*/
4345 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4346 if (hrc != S_OK)
4347 {
4348 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4349 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)\n", hrc));
4350 H();
4351 }
4352#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4353 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4354 char *pszTrunkName = szTrunkName;
4355 wchar_t * pswzBindName;
4356 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4357 Assert(hrc == S_OK);
4358 if (hrc == S_OK)
4359 {
4360 int cwBindName = (int)wcslen(pswzBindName) + 1;
4361 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4362 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4363 {
4364 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4365 pszTrunkName += cbFullBindNamePrefix-1;
4366 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4367 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4368 {
4369 DWORD err = GetLastError();
4370 hrc = HRESULT_FROM_WIN32(err);
4371 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
4372 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4373 }
4374 }
4375 else
4376 {
4377 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
4378 /** @todo set appropriate error code */
4379 hrc = E_FAIL;
4380 }
4381
4382 if (hrc != S_OK)
4383 {
4384 AssertFailed();
4385 CoTaskMemFree(pswzBindName);
4386 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4387 H();
4388 }
4389
4390 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
4391 }
4392 else
4393 {
4394 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4395 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
4396 H();
4397 }
4398
4399 const char *pszTrunk = szTrunkName;
4400 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
4401
4402# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
4403# if defined(RT_OS_FREEBSD)
4404 /*
4405 * If we bridge to a tap interface open it the `old' direct way.
4406 * This works and performs better than bridging a physical
4407 * interface via the current FreeBSD vboxnetflt implementation.
4408 */
4409 if (!strncmp(pszBridgedIfName, RT_STR_TUPLE("tap"))) {
4410 hrc = attachToTapInterface(aNetworkAdapter);
4411 if (FAILED(hrc))
4412 {
4413 switch (hrc)
4414 {
4415 case VERR_ACCESS_DENIED:
4416 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4417 "Failed to open '/dev/%s' for read/write access. Please check the "
4418 "permissions of that node, and that the net.link.tap.user_open "
4419 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
4420 "change the group of that node to vboxusers and make yourself "
4421 "a member of that group. Make sure that these changes are permanent."), pszBridgedIfName, pszBridgedIfName);
4422 default:
4423 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
4424 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4425 "Failed to initialize Host Interface Networking"));
4426 }
4427 }
4428
4429 Assert((int)maTapFD[uInstance] >= 0);
4430 if ((int)maTapFD[uInstance] >= 0)
4431 {
4432 InsertConfigString(pLunL0, "Driver", "HostInterface");
4433 InsertConfigNode(pLunL0, "Config", &pCfg);
4434 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4435 }
4436 break;
4437 }
4438# endif
4439 /** @todo Check for malformed names. */
4440 const char *pszTrunk = pszBridgedIfName;
4441
4442 /* Issue a warning if the interface is down */
4443 {
4444 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4445 if (iSock >= 0)
4446 {
4447 struct ifreq Req;
4448 RT_ZERO(Req);
4449 RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pszBridgedIfName);
4450 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
4451 if ((Req.ifr_flags & IFF_UP) == 0)
4452 setVMRuntimeErrorCallbackF(0, "BridgedInterfaceDown",
4453 N_("Bridged interface %s is down. Guest will not be able to use this interface"),
4454 pszBridgedIfName);
4455
4456 close(iSock);
4457 }
4458 }
4459
4460# else
4461# error "PORTME (VBOX_WITH_NETFLT)"
4462# endif
4463
4464 InsertConfigString(pLunL0, "Driver", "IntNet");
4465 InsertConfigNode(pLunL0, "Config", &pCfg);
4466 InsertConfigString(pCfg, "Trunk", pszTrunk);
4467 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4468 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
4469 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4470 char szNetwork[INTNET_MAX_NETWORK_NAME];
4471
4472#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
4473 /*
4474 * 'pszTrunk' contains just the interface name required in ring-0, while 'pszBridgedIfName' contains
4475 * interface name + optional description. We must not pass any description to the VM as it can differ
4476 * for the same interface name, eg: "nge0 - ethernet" (GUI) vs "nge0" (VBoxManage).
4477 */
4478 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszTrunk);
4479#else
4480 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszBridgedIfName);
4481#endif
4482 InsertConfigString(pCfg, "Network", szNetwork);
4483 networkName = Bstr(szNetwork);
4484 trunkName = Bstr(pszTrunk);
4485 trunkType = Bstr(TRUNKTYPE_NETFLT);
4486
4487# if defined(RT_OS_DARWIN)
4488 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
4489 if ( strstr(pszBridgedIfName, "Wireless")
4490 || strstr(pszBridgedIfName, "AirPort" ))
4491 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4492# elif defined(RT_OS_LINUX)
4493 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4494 if (iSock >= 0)
4495 {
4496 struct iwreq WRq;
4497
4498 RT_ZERO(WRq);
4499 strncpy(WRq.ifr_name, pszBridgedIfName, IFNAMSIZ);
4500 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
4501 close(iSock);
4502 if (fSharedMacOnWire)
4503 {
4504 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4505 Log(("Set SharedMacOnWire\n"));
4506 }
4507 else
4508 Log(("Failed to get wireless name\n"));
4509 }
4510 else
4511 Log(("Failed to open wireless socket\n"));
4512# elif defined(RT_OS_FREEBSD)
4513 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4514 if (iSock >= 0)
4515 {
4516 struct ieee80211req WReq;
4517 uint8_t abData[32];
4518
4519 RT_ZERO(WReq);
4520 strncpy(WReq.i_name, pszBridgedIfName, sizeof(WReq.i_name));
4521 WReq.i_type = IEEE80211_IOC_SSID;
4522 WReq.i_val = -1;
4523 WReq.i_data = abData;
4524 WReq.i_len = sizeof(abData);
4525
4526 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
4527 close(iSock);
4528 if (fSharedMacOnWire)
4529 {
4530 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4531 Log(("Set SharedMacOnWire\n"));
4532 }
4533 else
4534 Log(("Failed to get wireless name\n"));
4535 }
4536 else
4537 Log(("Failed to open wireless socket\n"));
4538# elif defined(RT_OS_WINDOWS)
4539# define DEVNAME_PREFIX L"\\\\.\\"
4540 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
4541 * there is a pretty long way till there though since we need to obtain the symbolic link name
4542 * for the adapter device we are going to query given the device Guid */
4543
4544
4545 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
4546
4547 wchar_t FileName[MAX_PATH];
4548 wcscpy(FileName, DEVNAME_PREFIX);
4549 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
4550
4551 /* open the device */
4552 HANDLE hDevice = CreateFile(FileName,
4553 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
4554 NULL,
4555 OPEN_EXISTING,
4556 FILE_ATTRIBUTE_NORMAL,
4557 NULL);
4558
4559 if (hDevice != INVALID_HANDLE_VALUE)
4560 {
4561 bool fSharedMacOnWire = false;
4562
4563 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4564 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4565 NDIS_PHYSICAL_MEDIUM PhMedium;
4566 DWORD cbResult;
4567 if (DeviceIoControl(hDevice,
4568 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4569 &Oid,
4570 sizeof(Oid),
4571 &PhMedium,
4572 sizeof(PhMedium),
4573 &cbResult,
4574 NULL))
4575 {
4576 /* that was simple, now examine PhMedium */
4577 if ( PhMedium == NdisPhysicalMediumWirelessWan
4578 || PhMedium == NdisPhysicalMediumWirelessLan
4579 || PhMedium == NdisPhysicalMediumNative802_11
4580 || PhMedium == NdisPhysicalMediumBluetooth)
4581 fSharedMacOnWire = true;
4582 }
4583 else
4584 {
4585 int winEr = GetLastError();
4586 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4587 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4588 }
4589 CloseHandle(hDevice);
4590
4591 if (fSharedMacOnWire)
4592 {
4593 Log(("this is a wireless adapter"));
4594 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4595 Log(("Set SharedMacOnWire\n"));
4596 }
4597 else
4598 Log(("this is NOT a wireless adapter"));
4599 }
4600 else
4601 {
4602 int winEr = GetLastError();
4603 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4604 }
4605
4606 CoTaskMemFree(pswzBindName);
4607
4608 pAdaptorComponent.setNull();
4609 /* release the pNc finally */
4610 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4611# else
4612 /** @todo PORTME: wireless detection */
4613# endif
4614
4615# if defined(RT_OS_SOLARIS)
4616# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4617 /* Zone access restriction, don't allow snooping the global zone. */
4618 zoneid_t ZoneId = getzoneid();
4619 if (ZoneId != GLOBAL_ZONEID)
4620 {
4621 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4622 }
4623# endif
4624# endif
4625
4626#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4627 /* NOTHING TO DO HERE */
4628#elif defined(RT_OS_LINUX)
4629/// @todo aleksey: is there anything to be done here?
4630#elif defined(RT_OS_FREEBSD)
4631/** @todo FreeBSD: Check out this later (HIF networking). */
4632#else
4633# error "Port me"
4634#endif
4635 break;
4636 }
4637
4638 case NetworkAttachmentType_Internal:
4639 {
4640 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4641 if (!bstr.isEmpty())
4642 {
4643 InsertConfigString(pLunL0, "Driver", "IntNet");
4644 InsertConfigNode(pLunL0, "Config", &pCfg);
4645 InsertConfigString(pCfg, "Network", bstr);
4646 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4647 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4648 networkName = bstr;
4649 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4650 }
4651 break;
4652 }
4653
4654 case NetworkAttachmentType_HostOnly:
4655 {
4656 InsertConfigString(pLunL0, "Driver", "IntNet");
4657 InsertConfigNode(pLunL0, "Config", &pCfg);
4658
4659 Bstr HostOnlyName;
4660 hrc = aNetworkAdapter->COMGETTER(HostOnlyInterface)(HostOnlyName.asOutParam());
4661 if (FAILED(hrc))
4662 {
4663 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostOnlyInterface) failed, hrc (0x%x)\n", hrc));
4664 H();
4665 }
4666
4667 Utf8Str HostOnlyNameUtf8(HostOnlyName);
4668 const char *pszHostOnlyName = HostOnlyNameUtf8.c_str();
4669 ComPtr<IHostNetworkInterface> hostInterface;
4670 rc = host->FindHostNetworkInterfaceByName(HostOnlyName.raw(),
4671 hostInterface.asOutParam());
4672 if (!SUCCEEDED(rc))
4673 {
4674 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4675 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4676 N_("Nonexistent host networking interface, name '%ls'"),
4677 HostOnlyName.raw());
4678 }
4679
4680 char szNetwork[INTNET_MAX_NETWORK_NAME];
4681 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHostOnlyName);
4682
4683#if defined(RT_OS_WINDOWS)
4684# ifndef VBOX_WITH_NETFLT
4685 hrc = E_NOTIMPL;
4686 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4687 H();
4688# else /* defined VBOX_WITH_NETFLT*/
4689 /** @todo r=bird: Put this in a function. */
4690
4691 HostNetworkInterfaceType_T eIfType;
4692 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4693 if (FAILED(hrc))
4694 {
4695 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4696 H();
4697 }
4698
4699 if (eIfType != HostNetworkInterfaceType_HostOnly)
4700 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4701 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4702 HostOnlyName.raw());
4703
4704 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4705 if (FAILED(hrc))
4706 {
4707 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4708 H();
4709 }
4710 Guid hostIFGuid(bstr);
4711
4712 INetCfg *pNc;
4713 ComPtr<INetCfgComponent> pAdaptorComponent;
4714 LPWSTR pszApp;
4715 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4716 Assert(hrc == S_OK);
4717 if (hrc != S_OK)
4718 {
4719 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4720 H();
4721 }
4722
4723 /* get the adapter's INetCfgComponent*/
4724 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4725 if (hrc != S_OK)
4726 {
4727 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4728 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4729 H();
4730 }
4731# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4732 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4733 char *pszTrunkName = szTrunkName;
4734 wchar_t * pswzBindName;
4735 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4736 Assert(hrc == S_OK);
4737 if (hrc == S_OK)
4738 {
4739 int cwBindName = (int)wcslen(pswzBindName) + 1;
4740 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4741 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4742 {
4743 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4744 pszTrunkName += cbFullBindNamePrefix-1;
4745 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4746 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4747 {
4748 DWORD err = GetLastError();
4749 hrc = HRESULT_FROM_WIN32(err);
4750 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4751 }
4752 }
4753 else
4754 {
4755 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4756 /** @todo set appropriate error code */
4757 hrc = E_FAIL;
4758 }
4759
4760 if (hrc != S_OK)
4761 {
4762 AssertFailed();
4763 CoTaskMemFree(pswzBindName);
4764 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4765 H();
4766 }
4767 }
4768 else
4769 {
4770 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4771 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4772 H();
4773 }
4774
4775
4776 CoTaskMemFree(pswzBindName);
4777
4778 pAdaptorComponent.setNull();
4779 /* release the pNc finally */
4780 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4781
4782 const char *pszTrunk = szTrunkName;
4783
4784 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4785 InsertConfigString(pCfg, "Trunk", pszTrunk);
4786 InsertConfigString(pCfg, "Network", szNetwork);
4787 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this windows only?? */
4788 networkName = Bstr(szNetwork);
4789 trunkName = Bstr(pszTrunk);
4790 trunkType = TRUNKTYPE_NETADP;
4791# endif /* defined VBOX_WITH_NETFLT*/
4792#elif defined(RT_OS_DARWIN)
4793 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4794 InsertConfigString(pCfg, "Network", szNetwork);
4795 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4796 networkName = Bstr(szNetwork);
4797 trunkName = Bstr(pszHostOnlyName);
4798 trunkType = TRUNKTYPE_NETADP;
4799#else
4800 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4801 InsertConfigString(pCfg, "Network", szNetwork);
4802 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4803 networkName = Bstr(szNetwork);
4804 trunkName = Bstr(pszHostOnlyName);
4805 trunkType = TRUNKTYPE_NETFLT;
4806#endif
4807 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4808
4809#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4810
4811 Bstr tmpAddr, tmpMask;
4812
4813 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4814 pszHostOnlyName).raw(),
4815 tmpAddr.asOutParam());
4816 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4817 {
4818 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4819 pszHostOnlyName).raw(),
4820 tmpMask.asOutParam());
4821 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4822 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4823 tmpMask.raw());
4824 else
4825 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4826 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4827 }
4828 else
4829 {
4830 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4831 hrc = hostInterface->EnableStaticIPConfig(getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw(),
4832 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4833 }
4834
4835 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4836
4837 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4838 pszHostOnlyName).raw(),
4839 tmpAddr.asOutParam());
4840 if (SUCCEEDED(hrc))
4841 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHostOnlyName).raw(),
4842 tmpMask.asOutParam());
4843 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4844 {
4845 hrc = hostInterface->EnableStaticIPConfigV6(tmpAddr.raw(),
4846 Utf8Str(tmpMask).toUInt32());
4847 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4848 }
4849#endif
4850 break;
4851 }
4852
4853 case NetworkAttachmentType_Generic:
4854 {
4855 hrc = aNetworkAdapter->COMGETTER(GenericDriver)(bstr.asOutParam()); H();
4856 SafeArray<BSTR> names;
4857 SafeArray<BSTR> values;
4858 hrc = aNetworkAdapter->GetProperties(Bstr().raw(),
4859 ComSafeArrayAsOutParam(names),
4860 ComSafeArrayAsOutParam(values)); H();
4861
4862 InsertConfigString(pLunL0, "Driver", bstr);
4863 InsertConfigNode(pLunL0, "Config", &pCfg);
4864 for (size_t ii = 0; ii < names.size(); ++ii)
4865 {
4866 if (values[ii] && *values[ii])
4867 {
4868 Utf8Str name = names[ii];
4869 Utf8Str value = values[ii];
4870 InsertConfigString(pCfg, name.c_str(), value);
4871 }
4872 }
4873 break;
4874 }
4875
4876 default:
4877 AssertMsgFailed(("should not get here!\n"));
4878 break;
4879 }
4880
4881 /*
4882 * Attempt to attach the driver.
4883 */
4884 switch (eAttachmentType)
4885 {
4886 case NetworkAttachmentType_Null:
4887 break;
4888
4889 case NetworkAttachmentType_Bridged:
4890 case NetworkAttachmentType_Internal:
4891 case NetworkAttachmentType_HostOnly:
4892 case NetworkAttachmentType_NAT:
4893 case NetworkAttachmentType_Generic:
4894 {
4895 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4896 {
4897 if (fAttachDetach)
4898 {
4899 rc = PDMR3DriverAttach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4900 //AssertRC(rc);
4901 }
4902
4903 {
4904 /** @todo pritesh: get the dhcp server name from the
4905 * previous network configuration and then stop the server
4906 * else it may conflict with the dhcp server running with
4907 * the current attachment type
4908 */
4909 /* Stop the hostonly DHCP Server */
4910 }
4911
4912 if (!networkName.isEmpty())
4913 {
4914 /*
4915 * Until we implement service reference counters DHCP Server will be stopped
4916 * by DHCPServerRunner destructor.
4917 */
4918 ComPtr<IDHCPServer> dhcpServer;
4919 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4920 dhcpServer.asOutParam());
4921 if (SUCCEEDED(hrc))
4922 {
4923 /* there is a DHCP server available for this network */
4924 BOOL fEnabledDhcp;
4925 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabledDhcp);
4926 if (FAILED(hrc))
4927 {
4928 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)\n", hrc));
4929 H();
4930 }
4931
4932 if (fEnabledDhcp)
4933 hrc = dhcpServer->Start(networkName.raw(),
4934 trunkName.raw(),
4935 trunkType.raw());
4936 }
4937 else
4938 hrc = S_OK;
4939 }
4940 }
4941
4942 break;
4943 }
4944
4945 default:
4946 AssertMsgFailed(("should not get here!\n"));
4947 break;
4948 }
4949
4950 meAttachmentType[uInstance] = eAttachmentType;
4951 }
4952 catch (ConfigError &x)
4953 {
4954 // InsertConfig threw something:
4955 return x.m_vrc;
4956 }
4957
4958#undef H
4959
4960 return VINF_SUCCESS;
4961}
4962
4963#ifdef VBOX_WITH_GUEST_PROPS
4964/**
4965 * Set an array of guest properties
4966 */
4967static void configSetProperties(VMMDev * const pVMMDev,
4968 void *names,
4969 void *values,
4970 void *timestamps,
4971 void *flags)
4972{
4973 VBOXHGCMSVCPARM parms[4];
4974
4975 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4976 parms[0].u.pointer.addr = names;
4977 parms[0].u.pointer.size = 0; /* We don't actually care. */
4978 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4979 parms[1].u.pointer.addr = values;
4980 parms[1].u.pointer.size = 0; /* We don't actually care. */
4981 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4982 parms[2].u.pointer.addr = timestamps;
4983 parms[2].u.pointer.size = 0; /* We don't actually care. */
4984 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
4985 parms[3].u.pointer.addr = flags;
4986 parms[3].u.pointer.size = 0; /* We don't actually care. */
4987
4988 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4989 guestProp::SET_PROPS_HOST,
4990 4,
4991 &parms[0]);
4992}
4993
4994/**
4995 * Set a single guest property
4996 */
4997static void configSetProperty(VMMDev * const pVMMDev,
4998 const char *pszName,
4999 const char *pszValue,
5000 const char *pszFlags)
5001{
5002 VBOXHGCMSVCPARM parms[4];
5003
5004 AssertPtrReturnVoid(pszName);
5005 AssertPtrReturnVoid(pszValue);
5006 AssertPtrReturnVoid(pszFlags);
5007 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5008 parms[0].u.pointer.addr = (void *)pszName;
5009 parms[0].u.pointer.size = (uint32_t)strlen(pszName) + 1;
5010 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5011 parms[1].u.pointer.addr = (void *)pszValue;
5012 parms[1].u.pointer.size = (uint32_t)strlen(pszValue) + 1;
5013 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
5014 parms[2].u.pointer.addr = (void *)pszFlags;
5015 parms[2].u.pointer.size = (uint32_t)strlen(pszFlags) + 1;
5016 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
5017 &parms[0]);
5018}
5019
5020/**
5021 * Set the global flags value by calling the service
5022 * @returns the status returned by the call to the service
5023 *
5024 * @param pTable the service instance handle
5025 * @param eFlags the flags to set
5026 */
5027int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
5028 guestProp::ePropFlags eFlags)
5029{
5030 VBOXHGCMSVCPARM paParm;
5031 paParm.setUInt32(eFlags);
5032 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
5033 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
5034 &paParm);
5035 if (RT_FAILURE(rc))
5036 {
5037 char szFlags[guestProp::MAX_FLAGS_LEN];
5038 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
5039 Log(("Failed to set the global flags.\n"));
5040 else
5041 Log(("Failed to set the global flags \"%s\".\n", szFlags));
5042 }
5043 return rc;
5044}
5045#endif /* VBOX_WITH_GUEST_PROPS */
5046
5047/**
5048 * Set up the Guest Property service, populate it with properties read from
5049 * the machine XML and set a couple of initial properties.
5050 */
5051/* static */ int Console::configGuestProperties(void *pvConsole, PUVM pUVM)
5052{
5053#ifdef VBOX_WITH_GUEST_PROPS
5054 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5055 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5056 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
5057
5058 /* Load the service */
5059 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
5060
5061 if (RT_FAILURE(rc))
5062 {
5063 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
5064 /* That is not a fatal failure. */
5065 rc = VINF_SUCCESS;
5066 }
5067 else
5068 {
5069 /*
5070 * Initialize built-in properties that can be changed and saved.
5071 *
5072 * These are typically transient properties that the guest cannot
5073 * change.
5074 */
5075
5076 {
5077 VBOXHGCMSVCPARM Params[2];
5078 int rc2 = pConsole->m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::GET_DBGF_INFO_FN, 2, &Params[0]);
5079 if (RT_SUCCESS(rc2))
5080 {
5081 PFNDBGFHANDLEREXT pfnHandler = (PFNDBGFHANDLEREXT)(uintptr_t)Params[0].u.pointer.addr;
5082 void *pService = (void*)Params[1].u.pointer.addr;
5083 DBGFR3InfoRegisterExternal(pUVM, "guestprops", "Display the guest properties", pfnHandler, pService);
5084 }
5085 }
5086
5087 /* Sysprep execution by VBoxService. */
5088 configSetProperty(pConsole->m_pVMMDev,
5089 "/VirtualBox/HostGuest/SysprepExec", "",
5090 "TRANSIENT, RDONLYGUEST");
5091 configSetProperty(pConsole->m_pVMMDev,
5092 "/VirtualBox/HostGuest/SysprepArgs", "",
5093 "TRANSIENT, RDONLYGUEST");
5094
5095 /*
5096 * Pull over the properties from the server.
5097 */
5098 SafeArray<BSTR> namesOut;
5099 SafeArray<BSTR> valuesOut;
5100 SafeArray<LONG64> timestampsOut;
5101 SafeArray<BSTR> flagsOut;
5102 HRESULT hrc;
5103 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
5104 ComSafeArrayAsOutParam(valuesOut),
5105 ComSafeArrayAsOutParam(timestampsOut),
5106 ComSafeArrayAsOutParam(flagsOut));
5107 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rrc\n", hrc), VERR_GENERAL_FAILURE);
5108 size_t cProps = namesOut.size();
5109 size_t cAlloc = cProps + 1;
5110 if ( valuesOut.size() != cProps
5111 || timestampsOut.size() != cProps
5112 || flagsOut.size() != cProps
5113 )
5114 AssertFailedReturn(VERR_INVALID_PARAMETER);
5115
5116 char **papszNames, **papszValues, **papszFlags;
5117 char szEmpty[] = "";
5118 LONG64 *pai64Timestamps;
5119 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5120 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5121 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
5122 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5123 if (papszNames && papszValues && pai64Timestamps && papszFlags)
5124 {
5125 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
5126 {
5127 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
5128 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
5129 if (RT_FAILURE(rc))
5130 break;
5131 if (valuesOut[i])
5132 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
5133 else
5134 papszValues[i] = szEmpty;
5135 if (RT_FAILURE(rc))
5136 break;
5137 pai64Timestamps[i] = timestampsOut[i];
5138 if (flagsOut[i])
5139 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
5140 else
5141 papszFlags[i] = szEmpty;
5142 }
5143 if (RT_SUCCESS(rc))
5144 configSetProperties(pConsole->m_pVMMDev,
5145 (void *)papszNames,
5146 (void *)papszValues,
5147 (void *)pai64Timestamps,
5148 (void *)papszFlags);
5149 for (unsigned i = 0; i < cProps; ++i)
5150 {
5151 RTStrFree(papszNames[i]);
5152 if (valuesOut[i])
5153 RTStrFree(papszValues[i]);
5154 if (flagsOut[i])
5155 RTStrFree(papszFlags[i]);
5156 }
5157 }
5158 else
5159 rc = VERR_NO_MEMORY;
5160 RTMemTmpFree(papszNames);
5161 RTMemTmpFree(papszValues);
5162 RTMemTmpFree(pai64Timestamps);
5163 RTMemTmpFree(papszFlags);
5164 AssertRCReturn(rc, rc);
5165
5166 /*
5167 * These properties have to be set before pulling over the properties
5168 * from the machine XML, to ensure that properties saved in the XML
5169 * will override them.
5170 */
5171 /* Set the raw VBox version string as a guest property. Used for host/guest
5172 * version comparison. */
5173 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
5174 VBOX_VERSION_STRING_RAW, "TRANSIENT, RDONLYGUEST");
5175 /* Set the full VBox version string as a guest property. Can contain vendor-specific
5176 * information/branding and/or pre-release tags. */
5177 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVerExt",
5178 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
5179 /* Set the VBox SVN revision as a guest property */
5180 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
5181 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
5182
5183 /*
5184 * Register the host notification callback
5185 */
5186 HGCMSVCEXTHANDLE hDummy;
5187 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
5188 Console::doGuestPropNotification,
5189 pvConsole);
5190
5191#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
5192 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
5193 guestProp::RDONLYGUEST);
5194 AssertRCReturn(rc, rc);
5195#endif
5196
5197 Log(("Set VBoxGuestPropSvc property store\n"));
5198 }
5199 return VINF_SUCCESS;
5200#else /* !VBOX_WITH_GUEST_PROPS */
5201 return VERR_NOT_SUPPORTED;
5202#endif /* !VBOX_WITH_GUEST_PROPS */
5203}
5204
5205/**
5206 * Set up the Guest Control service.
5207 */
5208/* static */ int Console::configGuestControl(void *pvConsole)
5209{
5210#ifdef VBOX_WITH_GUEST_CONTROL
5211 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5212 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5213
5214 /* Load the service */
5215 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
5216
5217 if (RT_FAILURE(rc))
5218 {
5219 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
5220 /* That is not a fatal failure. */
5221 rc = VINF_SUCCESS;
5222 }
5223 else
5224 {
5225 HGCMSVCEXTHANDLE hDummy;
5226 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
5227 &Guest::notifyCtrlDispatcher,
5228 pConsole->getGuest());
5229 if (RT_FAILURE(rc))
5230 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
5231 else
5232 Log(("VBoxGuestControlSvc loaded\n"));
5233 }
5234
5235 return rc;
5236#else /* !VBOX_WITH_GUEST_CONTROL */
5237 return VERR_NOT_SUPPORTED;
5238#endif /* !VBOX_WITH_GUEST_CONTROL */
5239}
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