VirtualBox

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

Last change on this file since 37952 was 37902, checked in by vboxsync, 13 years ago

Main: don't search for the extension pack if PCI passthrough is not enabled at all

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