VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/DrvHostBase.cpp@ 6291

Last change on this file since 6291 was 6291, checked in by vboxsync, 17 years ago

Big virtual disk changeset containing several modifications

  • remove the always buggy translation setting and replace it with two sets of geometries, physical and logical
  • complete vmdk creation (fixed/dynamic variants, both split in 2G chunks and single file)
  • implemented VBoxHDD-new generic snapshot support, i.e. diff image creation and image merging (completely untested, I'm pretty sure there are bugs)
  • assorted changes which generalize the VBoxHDD-new interfaces (both externally and internally)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 70.7 KB
Line 
1/* $Id: DrvHostBase.cpp 6291 2008-01-09 10:57:05Z vboxsync $ */
2/** @file
3 * DrvHostBase - Host base drive access driver.
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_HOST_BASE
23#ifdef RT_OS_DARWIN
24# include <mach/mach.h>
25# include <Carbon/Carbon.h>
26# include <IOKit/IOKitLib.h>
27# include <IOKit/storage/IOStorageDeviceCharacteristics.h>
28# include <IOKit/scsi-commands/SCSITaskLib.h>
29# include <IOKit/scsi-commands/SCSICommandOperationCodes.h>
30# include <IOKit/IOBSD.h>
31# include <DiskArbitration/DiskArbitration.h>
32# include <mach/mach_error.h>
33# include <VBox/scsi.h>
34
35#elif defined(RT_OS_L4)
36 /* Nothing special requires... yeah, right. */
37
38#elif defined(RT_OS_LINUX)
39# include <sys/ioctl.h>
40# include <sys/fcntl.h>
41# include <errno.h>
42
43#elif defined(RT_OS_SOLARIS)
44# include <fcntl.h>
45# include <errno.h>
46# include <stropts.h>
47# include <malloc.h>
48# include <sys/dkio.h>
49extern "C" char *getfullblkname(char *);
50
51#elif defined(RT_OS_WINDOWS)
52# define WIN32_NO_STATUS
53# include <Windows.h>
54# include <dbt.h>
55# undef WIN32_NO_STATUS
56# include <ntstatus.h>
57
58/* from ntdef.h */
59typedef LONG NTSTATUS;
60
61/* from ntddk.h */
62typedef struct _IO_STATUS_BLOCK {
63 union {
64 NTSTATUS Status;
65 PVOID Pointer;
66 };
67 ULONG_PTR Information;
68} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
69
70
71/* from ntinternals.com */
72typedef enum _FS_INFORMATION_CLASS {
73 FileFsVolumeInformation=1,
74 FileFsLabelInformation,
75 FileFsSizeInformation,
76 FileFsDeviceInformation,
77 FileFsAttributeInformation,
78 FileFsControlInformation,
79 FileFsFullSizeInformation,
80 FileFsObjectIdInformation,
81 FileFsMaximumInformation
82} FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS;
83
84typedef struct _FILE_FS_SIZE_INFORMATION {
85 LARGE_INTEGER TotalAllocationUnits;
86 LARGE_INTEGER AvailableAllocationUnits;
87 ULONG SectorsPerAllocationUnit;
88 ULONG BytesPerSector;
89} FILE_FS_SIZE_INFORMATION, *PFILE_FS_SIZE_INFORMATION;
90
91extern "C"
92NTSTATUS __stdcall NtQueryVolumeInformationFile(
93 /*IN*/ HANDLE FileHandle,
94 /*OUT*/ PIO_STATUS_BLOCK IoStatusBlock,
95 /*OUT*/ PVOID FileSystemInformation,
96 /*IN*/ ULONG Length,
97 /*IN*/ FS_INFORMATION_CLASS FileSystemInformationClass );
98
99#else
100# error "Unsupported Platform."
101#endif
102
103#include <VBox/pdmdrv.h>
104#include <iprt/assert.h>
105#include <iprt/file.h>
106#include <iprt/path.h>
107#include <iprt/string.h>
108#include <iprt/thread.h>
109#include <iprt/semaphore.h>
110#include <iprt/uuid.h>
111#include <iprt/asm.h>
112#include <iprt/critsect.h>
113#include <iprt/ctype.h>
114
115#include "DrvHostBase.h"
116
117
118
119
120/* -=-=-=-=- IBlock -=-=-=-=- */
121
122/** @copydoc PDMIBLOCK::pfnRead */
123static DECLCALLBACK(int) drvHostBaseRead(PPDMIBLOCK pInterface, uint64_t off, void *pvBuf, size_t cbRead)
124{
125 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
126 LogFlow(("%s-%d: drvHostBaseRead: off=%#llx pvBuf=%p cbRead=%#x (%s)\n",
127 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, off, pvBuf, cbRead, pThis->pszDevice));
128 RTCritSectEnter(&pThis->CritSect);
129
130 /*
131 * Check the state.
132 */
133 int rc;
134#ifdef RT_OS_DARWIN
135 if ( pThis->fMediaPresent
136 && pThis->ppScsiTaskDI
137 && pThis->cbBlock)
138#else
139 if (pThis->fMediaPresent)
140#endif
141 {
142#ifdef RT_OS_DARWIN
143 /*
144 * Issue a READ(12) request.
145 */
146 const uint32_t LBA = off / pThis->cbBlock;
147 AssertReturn(!(off % pThis->cbBlock), VERR_INVALID_PARAMETER);
148 const uint32_t cBlocks = cbRead / pThis->cbBlock;
149 AssertReturn(!(cbRead % pThis->cbBlock), VERR_INVALID_PARAMETER);
150 uint8_t abCmd[16] =
151 {
152 SCSI_READ_12, 0,
153 RT_BYTE4(LBA), RT_BYTE3(LBA), RT_BYTE2(LBA), RT_BYTE1(LBA),
154 RT_BYTE4(cBlocks), RT_BYTE3(cBlocks), RT_BYTE2(cBlocks), RT_BYTE1(cBlocks),
155 0, 0, 0, 0, 0
156 };
157 rc = DRVHostBaseScsiCmd(pThis, abCmd, 12, PDMBLOCKTXDIR_FROM_DEVICE, pvBuf, &cbRead, NULL, 0, 0);
158
159#else
160 /*
161 * Seek and read.
162 */
163 rc = RTFileSeek(pThis->FileDevice, off, RTFILE_SEEK_BEGIN, NULL);
164 if (VBOX_SUCCESS(rc))
165 {
166 rc = RTFileRead(pThis->FileDevice, pvBuf, cbRead, NULL);
167 if (VBOX_SUCCESS(rc))
168 {
169 Log2(("%s-%d: drvHostBaseRead: off=%#llx cbRead=%#x\n"
170 "%16.*Vhxd\n",
171 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, off, cbRead, cbRead, pvBuf));
172 }
173 else
174 Log(("%s-%d: drvHostBaseRead: RTFileRead(%d, %p, %#x) -> %Vrc (off=%#llx '%s')\n",
175 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->FileDevice,
176 pvBuf, cbRead, rc, off, pThis->pszDevice));
177 }
178 else
179 Log(("%s-%d: drvHostBaseRead: RTFileSeek(%d,%#llx,) -> %Vrc\n", pThis->pDrvIns->pDrvReg->szDriverName,
180 pThis->pDrvIns->iInstance, pThis->FileDevice, off, rc));
181#endif
182 }
183 else
184 rc = VERR_MEDIA_NOT_PRESENT;
185
186 RTCritSectLeave(&pThis->CritSect);
187 LogFlow(("%s-%d: drvHostBaseRead: returns %Vrc\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, rc));
188 return rc;
189}
190
191
192/** @copydoc PDMIBLOCK::pfnWrite */
193static DECLCALLBACK(int) drvHostBaseWrite(PPDMIBLOCK pInterface, uint64_t off, const void *pvBuf, size_t cbWrite)
194{
195 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
196 LogFlow(("%s-%d: drvHostBaseWrite: off=%#llx pvBuf=%p cbWrite=%#x (%s)\n",
197 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, off, pvBuf, cbWrite, pThis->pszDevice));
198 Log2(("%s-%d: drvHostBaseWrite: off=%#llx cbWrite=%#x\n"
199 "%16.*Vhxd\n",
200 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, off, cbWrite, cbWrite, pvBuf));
201 RTCritSectEnter(&pThis->CritSect);
202
203 /*
204 * Check the state.
205 */
206 int rc;
207 if (!pThis->fReadOnly)
208 {
209 if (pThis->fMediaPresent)
210 {
211#ifdef RT_OS_DARWIN
212 /** @todo write support... */
213 rc = VERR_WRITE_PROTECT;
214
215#else
216 /*
217 * Seek and write.
218 */
219 rc = RTFileSeek(pThis->FileDevice, off, RTFILE_SEEK_BEGIN, NULL);
220 if (VBOX_SUCCESS(rc))
221 {
222 rc = RTFileWrite(pThis->FileDevice, pvBuf, cbWrite, NULL);
223 if (VBOX_FAILURE(rc))
224 Log(("%s-%d: drvHostBaseWrite: RTFileWrite(%d, %p, %#x) -> %Vrc (off=%#llx '%s')\n",
225 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->FileDevice,
226 pvBuf, cbWrite, rc, off, pThis->pszDevice));
227 }
228 else
229 Log(("%s-%d: drvHostBaseWrite: RTFileSeek(%d,%#llx,) -> %Vrc\n",
230 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->FileDevice, off, rc));
231#endif
232 }
233 else
234 rc = VERR_MEDIA_NOT_PRESENT;
235 }
236 else
237 rc = VERR_WRITE_PROTECT;
238
239 RTCritSectLeave(&pThis->CritSect);
240 LogFlow(("%s-%d: drvHostBaseWrite: returns %Vrc\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, rc));
241 return rc;
242}
243
244
245/** @copydoc PDMIBLOCK::pfnFlush */
246static DECLCALLBACK(int) drvHostBaseFlush(PPDMIBLOCK pInterface)
247{
248 int rc;
249 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
250 LogFlow(("%s-%d: drvHostBaseFlush: (%s)\n",
251 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->pszDevice));
252 RTCritSectEnter(&pThis->CritSect);
253
254 if (pThis->fMediaPresent)
255 {
256#ifdef RT_OS_DARWIN
257 rc = VINF_SUCCESS;
258 /** @todo scsi device buffer flush... */
259#else
260 rc = RTFileFlush(pThis->FileDevice);
261#endif
262 }
263 else
264 rc = VERR_MEDIA_NOT_PRESENT;
265
266 RTCritSectLeave(&pThis->CritSect);
267 LogFlow(("%s-%d: drvHostBaseFlush: returns %Vrc\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, rc));
268 return rc;
269}
270
271
272/** @copydoc PDMIBLOCK::pfnIsReadOnly */
273static DECLCALLBACK(bool) drvHostBaseIsReadOnly(PPDMIBLOCK pInterface)
274{
275 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
276 return pThis->fReadOnly;
277}
278
279
280/** @copydoc PDMIBLOCK::pfnGetSize */
281static DECLCALLBACK(uint64_t) drvHostBaseGetSize(PPDMIBLOCK pInterface)
282{
283 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
284 RTCritSectEnter(&pThis->CritSect);
285
286 uint64_t cb = 0;
287 if (pThis->fMediaPresent)
288 cb = pThis->cbSize;
289
290 RTCritSectLeave(&pThis->CritSect);
291 LogFlow(("%s-%d: drvHostBaseGetSize: returns %llu\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, cb));
292 return cb;
293}
294
295
296/** @copydoc PDMIBLOCK::pfnGetType */
297static DECLCALLBACK(PDMBLOCKTYPE) drvHostBaseGetType(PPDMIBLOCK pInterface)
298{
299 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
300 LogFlow(("%s-%d: drvHostBaseGetType: returns %d\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->enmType));
301 return pThis->enmType;
302}
303
304
305/** @copydoc PDMIBLOCK::pfnGetUuid */
306static DECLCALLBACK(int) drvHostBaseGetUuid(PPDMIBLOCK pInterface, PRTUUID pUuid)
307{
308 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
309
310 *pUuid = pThis->Uuid;
311
312 LogFlow(("%s-%d: drvHostBaseGetUuid: returns VINF_SUCCESS *pUuid=%Vuuid\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pUuid));
313 return VINF_SUCCESS;
314}
315
316
317/* -=-=-=-=- IBlockBios -=-=-=-=- */
318
319/** Makes a PDRVHOSTBASE out of a PPDMIBLOCKBIOS. */
320#define PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface) ( (PDRVHOSTBASE((uintptr_t)pInterface - RT_OFFSETOF(DRVHOSTBASE, IBlockBios))) )
321
322
323/** @copydoc PDMIBLOCKBIOS::pfnGetPCHSGeometry */
324static DECLCALLBACK(int) drvHostBaseGetPCHSGeometry(PPDMIBLOCKBIOS pInterface, PPDMMEDIAGEOMETRY pPCHSGeometry)
325{
326 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
327 RTCritSectEnter(&pThis->CritSect);
328
329 int rc = VINF_SUCCESS;
330 if (pThis->fMediaPresent)
331 {
332 if ( pThis->PCHSGeometry.cCylinders > 0
333 && pThis->PCHSGeometry.cHeads > 0
334 && pThis->PCHSGeometry.cSectors > 0)
335 {
336 *pPCHSGeometry = pThis->PCHSGeometry;
337 }
338 else
339 rc = VERR_PDM_GEOMETRY_NOT_SET;
340 }
341 else
342 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
343
344 RTCritSectLeave(&pThis->CritSect);
345 LogFlow(("%s-%d: %s: returns %Vrc CHS={%d,%d,%d}\n",
346 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, __FUNCTION__, rc, pThis->PCHSGeometry.cCylinders, pThis->PCHSGeometry.cHeads, pThis->PCHSGeometry.cSectors));
347 return rc;
348}
349
350
351/** @copydoc PDMIBLOCKBIOS::pfnSetPCHSGeometry */
352static DECLCALLBACK(int) drvHostBaseSetPCHSGeometry(PPDMIBLOCKBIOS pInterface, PCPDMMEDIAGEOMETRY pPCHSGeometry)
353{
354 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
355 LogFlow(("%s-%d: %s: cCylinders=%d cHeads=%d cSectors=%d\n",
356 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, __FUNCTION__, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
357 RTCritSectEnter(&pThis->CritSect);
358
359 int rc = VINF_SUCCESS;
360 if (pThis->fMediaPresent)
361 {
362 pThis->PCHSGeometry = *pPCHSGeometry;
363 }
364 else
365 {
366 AssertMsgFailed(("Invalid state! Not mounted!\n"));
367 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
368 }
369
370 RTCritSectLeave(&pThis->CritSect);
371 return rc;
372}
373
374
375/** @copydoc PDMIBLOCKBIOS::pfnGetLCHSGeometry */
376static DECLCALLBACK(int) drvHostBaseGetLCHSGeometry(PPDMIBLOCKBIOS pInterface, PPDMMEDIAGEOMETRY pLCHSGeometry)
377{
378 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
379 RTCritSectEnter(&pThis->CritSect);
380
381 int rc = VINF_SUCCESS;
382 if (pThis->fMediaPresent)
383 {
384 if ( pThis->LCHSGeometry.cCylinders > 0
385 && pThis->LCHSGeometry.cHeads > 0
386 && pThis->LCHSGeometry.cSectors > 0)
387 {
388 *pLCHSGeometry = pThis->LCHSGeometry;
389 }
390 else
391 rc = VERR_PDM_GEOMETRY_NOT_SET;
392 }
393 else
394 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
395
396 RTCritSectLeave(&pThis->CritSect);
397 LogFlow(("%s-%d: %s: returns %Vrc CHS={%d,%d,%d}\n",
398 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, __FUNCTION__, rc, pThis->LCHSGeometry.cCylinders, pThis->LCHSGeometry.cHeads, pThis->LCHSGeometry.cSectors));
399 return rc;
400}
401
402
403/** @copydoc PDMIBLOCKBIOS::pfnSetLCHSGeometry */
404static DECLCALLBACK(int) drvHostBaseSetLCHSGeometry(PPDMIBLOCKBIOS pInterface, PCPDMMEDIAGEOMETRY pLCHSGeometry)
405{
406 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
407 LogFlow(("%s-%d: %s: cCylinders=%d cHeads=%d cSectors=%d\n",
408 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, __FUNCTION__, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
409 RTCritSectEnter(&pThis->CritSect);
410
411 int rc = VINF_SUCCESS;
412 if (pThis->fMediaPresent)
413 {
414 pThis->LCHSGeometry = *pLCHSGeometry;
415 }
416 else
417 {
418 AssertMsgFailed(("Invalid state! Not mounted!\n"));
419 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
420 }
421
422 RTCritSectLeave(&pThis->CritSect);
423 return rc;
424}
425
426
427/** @copydoc PDMIBLOCKBIOS::pfnIsVisible */
428static DECLCALLBACK(bool) drvHostBaseIsVisible(PPDMIBLOCKBIOS pInterface)
429{
430 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
431 return pThis->fBiosVisible;
432}
433
434
435/** @copydoc PDMIBLOCKBIOS::pfnGetType */
436static DECLCALLBACK(PDMBLOCKTYPE) drvHostBaseBiosGetType(PPDMIBLOCKBIOS pInterface)
437{
438 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
439 return pThis->enmType;
440}
441
442
443
444/* -=-=-=-=- IMount -=-=-=-=- */
445
446/** @copydoc PDMIMOUNT::pfnMount */
447static DECLCALLBACK(int) drvHostBaseMount(PPDMIMOUNT pInterface, const char *pszFilename, const char *pszCoreDriver)
448{
449 /* We're not mountable. */
450 AssertMsgFailed(("drvHostBaseMount: This shouldn't be called!\n"));
451 return VERR_PDM_MEDIA_MOUNTED;
452}
453
454
455/** @copydoc PDMIMOUNT::pfnUnmount */
456static DECLCALLBACK(int) drvHostBaseUnmount(PPDMIMOUNT pInterface, bool fForce)
457{
458 LogFlow(("drvHostBaseUnmount: returns VERR_NOT_SUPPORTED\n"));
459 return VERR_NOT_SUPPORTED;
460}
461
462
463/** @copydoc PDMIMOUNT::pfnIsMounted */
464static DECLCALLBACK(bool) drvHostBaseIsMounted(PPDMIMOUNT pInterface)
465{
466 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
467 RTCritSectEnter(&pThis->CritSect);
468
469 bool fRc = pThis->fMediaPresent;
470
471 RTCritSectLeave(&pThis->CritSect);
472 return fRc;
473}
474
475
476/** @copydoc PDMIMOUNT::pfnIsLocked */
477static DECLCALLBACK(int) drvHostBaseLock(PPDMIMOUNT pInterface)
478{
479 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
480 RTCritSectEnter(&pThis->CritSect);
481
482 int rc = VINF_SUCCESS;
483 if (!pThis->fLocked)
484 {
485 if (pThis->pfnDoLock)
486 rc = pThis->pfnDoLock(pThis, true);
487 if (VBOX_SUCCESS(rc))
488 pThis->fLocked = true;
489 }
490 else
491 LogFlow(("%s-%d: drvHostBaseLock: already locked\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance));
492
493 RTCritSectLeave(&pThis->CritSect);
494 LogFlow(("%s-%d: drvHostBaseLock: returns %Vrc\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, rc));
495 return rc;
496}
497
498
499/** @copydoc PDMIMOUNT::pfnIsLocked */
500static DECLCALLBACK(int) drvHostBaseUnlock(PPDMIMOUNT pInterface)
501{
502 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
503 RTCritSectEnter(&pThis->CritSect);
504
505 int rc = VINF_SUCCESS;
506 if (pThis->fLocked)
507 {
508 if (pThis->pfnDoLock)
509 rc = pThis->pfnDoLock(pThis, false);
510 if (VBOX_SUCCESS(rc))
511 pThis->fLocked = false;
512 }
513 else
514 LogFlow(("%s-%d: drvHostBaseUnlock: not locked\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance));
515
516 RTCritSectLeave(&pThis->CritSect);
517 LogFlow(("%s-%d: drvHostBaseUnlock: returns %Vrc\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, rc));
518 return rc;
519}
520
521
522/** @copydoc PDMIMOUNT::pfnIsLocked */
523static DECLCALLBACK(bool) drvHostBaseIsLocked(PPDMIMOUNT pInterface)
524{
525 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
526 RTCritSectEnter(&pThis->CritSect);
527
528 bool fRc = pThis->fLocked;
529
530 RTCritSectLeave(&pThis->CritSect);
531 return fRc;
532}
533
534
535/* -=-=-=-=- IBase -=-=-=-=- */
536
537/** @copydoc PDMIBASE::pfnQueryInterface. */
538static DECLCALLBACK(void *) drvHostBaseQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
539{
540 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
541 PDRVHOSTBASE pThis = PDMINS2DATA(pDrvIns, PDRVHOSTBASE);
542 switch (enmInterface)
543 {
544 case PDMINTERFACE_BASE:
545 return &pDrvIns->IBase;
546 case PDMINTERFACE_BLOCK:
547 return &pThis->IBlock;
548 case PDMINTERFACE_BLOCK_BIOS:
549 return pThis->fBiosVisible ? &pThis->IBlockBios : NULL;
550 case PDMINTERFACE_MOUNT:
551 return &pThis->IMount;
552 default:
553 return NULL;
554 }
555}
556
557
558/* -=-=-=-=- poller thread -=-=-=-=- */
559
560#ifdef RT_OS_DARWIN
561/** The runloop input source name for the disk arbitration events. */
562#define MY_RUN_LOOP_MODE CFSTR("drvHostBaseDA")
563
564/**
565 * Gets the BSD Name (/dev/disc[0-9]+) for the service.
566 *
567 * This is done by recursing down the I/O registry until we hit upon an entry
568 * with a BSD Name. Usually we find it two levels down. (Further down under
569 * the IOCDPartitionScheme, the volume (slices) BSD Name is found. We don't
570 * seem to have to go this far fortunately.)
571 *
572 * @return VINF_SUCCESS if found, VERR_FILE_NOT_FOUND otherwise.
573 * @param Entry The current I/O registry entry reference.
574 * @param pszName Where to store the name. 128 bytes.
575 * @param cRecursions Number of recursions. This is used as an precation
576 * just to limit the depth and avoid blowing the stack
577 * should we hit a bug or something.
578 */
579static int drvHostBaseGetBSDName(io_registry_entry_t Entry, char *pszName, unsigned cRecursions)
580{
581 int rc = VERR_FILE_NOT_FOUND;
582 io_iterator_t Children = 0;
583 kern_return_t krc = IORegistryEntryGetChildIterator(Entry, kIOServicePlane, &Children);
584 if (krc == KERN_SUCCESS)
585 {
586 io_object_t Child;
587 while ( rc == VERR_FILE_NOT_FOUND
588 && (Child = IOIteratorNext(Children)) != 0)
589 {
590 CFStringRef BSDNameStrRef = (CFStringRef)IORegistryEntryCreateCFProperty(Child, CFSTR(kIOBSDNameKey), kCFAllocatorDefault, 0);
591 if (BSDNameStrRef)
592 {
593 if (CFStringGetCString(BSDNameStrRef, pszName, 128, kCFStringEncodingUTF8))
594 rc = VINF_SUCCESS;
595 else
596 AssertFailed();
597 CFRelease(BSDNameStrRef);
598 }
599 if (rc == VERR_FILE_NOT_FOUND && cRecursions < 10)
600 rc = drvHostBaseGetBSDName(Child, pszName, cRecursions + 1);
601 IOObjectRelease(Child);
602 }
603 IOObjectRelease(Children);
604 }
605 return rc;
606}
607
608
609/**
610 * Callback notifying us that the async DADiskClaim()/DADiskUnmount call has completed.
611 *
612 * @param DiskRef The disk that was attempted claimed / unmounted.
613 * @param DissenterRef NULL on success, contains details on failure.
614 * @param pvContext Pointer to the return code variable.
615 */
616static void drvHostBaseDADoneCallback(DADiskRef DiskRef, DADissenterRef DissenterRef, void *pvContext)
617{
618 int *prc = (int *)pvContext;
619 if (!DissenterRef)
620 *prc = 0;
621 else
622 *prc = DADissenterGetStatus(DissenterRef) ? DADissenterGetStatus(DissenterRef) : -1;
623 CFRunLoopStop(CFRunLoopGetCurrent());
624}
625
626
627/**
628 * Obtain exclusive access to the DVD device, umount it if necessary.
629 *
630 * @return VBox status code.
631 * @param pThis The driver instance.
632 * @param DVDService The DVD service object.
633 */
634static int drvHostBaseObtainExclusiveAccess(PDRVHOSTBASE pThis, io_object_t DVDService)
635{
636 PPDMDRVINS pDrvIns = pThis->pDrvIns; NOREF(pDrvIns);
637
638 for (unsigned iTry = 0;; iTry++)
639 {
640 IOReturn irc = (*pThis->ppScsiTaskDI)->ObtainExclusiveAccess(pThis->ppScsiTaskDI);
641 if (irc == kIOReturnSuccess)
642 {
643 /*
644 * This is a bit weird, but if we unmounted the DVD drive we also need to
645 * unlock it afterwards or the guest won't be able to eject it later on.
646 */
647 if (pThis->pDADisk)
648 {
649 uint8_t abCmd[16] =
650 {
651 SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL, 0, 0, 0, false, 0,
652 0,0,0,0,0,0,0,0,0,0
653 };
654 DRVHostBaseScsiCmd(pThis, abCmd, 6, PDMBLOCKTXDIR_NONE, NULL, NULL, NULL, 0, 0);
655 }
656 return VINF_SUCCESS;
657 }
658 if (irc == kIOReturnExclusiveAccess)
659 return VERR_SHARING_VIOLATION; /* already used exclusivly. */
660 if (irc != kIOReturnBusy)
661 return VERR_GENERAL_FAILURE; /* not mounted */
662
663 /*
664 * Attempt to the unmount all volumes of the device.
665 * It seems we can can do this all in one go without having to enumerate the
666 * volumes (sessions) and deal with them one by one. This is very fortuitous
667 * as the disk arbitration API is a bit cumbersome to deal with.
668 */
669 if (iTry > 2)
670 return VERR_DRIVE_LOCKED;
671 char szName[128];
672 int rc = drvHostBaseGetBSDName(DVDService, &szName[0], 0);
673 if (VBOX_SUCCESS(rc))
674 {
675 pThis->pDASession = DASessionCreate(kCFAllocatorDefault);
676 if (pThis->pDASession)
677 {
678 DASessionScheduleWithRunLoop(pThis->pDASession, CFRunLoopGetCurrent(), MY_RUN_LOOP_MODE);
679 pThis->pDADisk = DADiskCreateFromBSDName(kCFAllocatorDefault, pThis->pDASession, szName);
680 if (pThis->pDADisk)
681 {
682 /*
683 * Try claim the device.
684 */
685 Log(("%s-%d: calling DADiskClaim on '%s'.\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, szName));
686 int rcDA = -2;
687 DADiskClaim(pThis->pDADisk, kDADiskClaimOptionDefault, NULL, NULL, drvHostBaseDADoneCallback, &rcDA);
688 SInt32 rc32 = CFRunLoopRunInMode(MY_RUN_LOOP_MODE, 120.0, FALSE);
689 AssertMsg(rc32 == kCFRunLoopRunStopped, ("rc32=%RI32 (%RX32)\n", rc32, rc32));
690 if ( rc32 == kCFRunLoopRunStopped
691 && !rcDA)
692 {
693 /*
694 * Try unmount the device.
695 */
696 Log(("%s-%d: calling DADiskUnmount on '%s'.\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, szName));
697 rcDA = -2;
698 DADiskUnmount(pThis->pDADisk, kDADiskUnmountOptionWhole, drvHostBaseDADoneCallback, &rcDA);
699 SInt32 rc32 = CFRunLoopRunInMode(MY_RUN_LOOP_MODE, 120.0, FALSE);
700 AssertMsg(rc32 == kCFRunLoopRunStopped, ("rc32=%RI32 (%RX32)\n", rc32, rc32));
701 if ( rc32 == kCFRunLoopRunStopped
702 && !rcDA)
703 {
704 iTry = 99;
705 DASessionUnscheduleFromRunLoop(pThis->pDASession, CFRunLoopGetCurrent(), MY_RUN_LOOP_MODE);
706 Log(("%s-%d: unmount succeed - retrying.\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
707 continue;
708 }
709 Log(("%s-%d: umount => rc32=%d & rcDA=%#x\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, rc32, rcDA));
710
711 /* failed - cleanup */
712 DADiskUnclaim(pThis->pDADisk);
713 }
714 else
715 Log(("%s-%d: claim => rc32=%d & rcDA=%#x\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, rc32, rcDA));
716
717 CFRelease(pThis->pDADisk);
718 pThis->pDADisk = NULL;
719 }
720 else
721 Log(("%s-%d: failed to open disk '%s'!\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, szName));
722
723 DASessionUnscheduleFromRunLoop(pThis->pDASession, CFRunLoopGetCurrent(), MY_RUN_LOOP_MODE);
724 CFRelease(pThis->pDASession);
725 pThis->pDASession = NULL;
726 }
727 else
728 Log(("%s-%d: failed to create DA session!\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
729 }
730 RTThreadSleep(10);
731 }
732}
733#endif /* RT_OS_DARWIN */
734
735
736#ifndef RT_OS_SOLARIS
737/**
738 * Wrapper for open / RTFileOpen / IOKit.
739 *
740 * @remark The Darwin code must correspond exactly to the enumeration
741 * done in Main/darwin/iokit.c.
742 */
743static int drvHostBaseOpen(PDRVHOSTBASE pThis, PRTFILE pFileDevice, bool fReadOnly)
744{
745#ifdef RT_OS_DARWIN
746 /* Darwin is kind of special... */
747 Assert(!pFileDevice); NOREF(pFileDevice);
748 Assert(!pThis->cbBlock);
749 Assert(!pThis->MasterPort);
750 Assert(!pThis->ppMMCDI);
751 Assert(!pThis->ppScsiTaskDI);
752
753 /*
754 * Open the master port on the first invocation.
755 */
756 kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &pThis->MasterPort);
757 AssertReturn(krc == KERN_SUCCESS, VERR_GENERAL_FAILURE);
758
759 /*
760 * Create a matching dictionary for searching for DVD services in the IOKit.
761 *
762 * [If I understand this correctly, plain CDROMs doesn't show up as
763 * IODVDServices. Too keep things simple, we will only support DVDs
764 * until somebody complains about it and we get hardware to test it on.
765 * (Unless I'm much mistaken, there aren't any (orignal) intel macs with
766 * plain cdroms.)]
767 */
768 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IODVDServices");
769 AssertReturn(RefMatchingDict, NULL);
770
771 /*
772 * do the search and get a collection of keyboards.
773 */
774 io_iterator_t DVDServices = NULL;
775 IOReturn irc = IOServiceGetMatchingServices(pThis->MasterPort, RefMatchingDict, &DVDServices);
776 AssertMsgReturn(irc == kIOReturnSuccess, ("irc=%d\n", irc), NULL);
777 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
778
779 /*
780 * Enumerate the DVD drives (services).
781 * (This enumeration must be identical to the one performed in DrvHostBase.cpp.)
782 */
783 int rc = VERR_FILE_NOT_FOUND;
784 unsigned i = 0;
785 io_object_t DVDService;
786 while ((DVDService = IOIteratorNext(DVDServices)) != 0)
787 {
788 /*
789 * Get the properties we use to identify the DVD drive.
790 *
791 * While there is a (weird 12 byte) GUID, it isn't persistent
792 * accross boots. So, we have to use a combination of the
793 * vendor name and product name properties with an optional
794 * sequence number for identification.
795 */
796 CFMutableDictionaryRef PropsRef = 0;
797 kern_return_t krc = IORegistryEntryCreateCFProperties(DVDService, &PropsRef, kCFAllocatorDefault, kNilOptions);
798 if (krc == KERN_SUCCESS)
799 {
800 /* Get the Device Characteristics dictionary. */
801 CFDictionaryRef DevCharRef = (CFDictionaryRef)CFDictionaryGetValue(PropsRef, CFSTR(kIOPropertyDeviceCharacteristicsKey));
802 if (DevCharRef)
803 {
804 /* The vendor name. */
805 char szVendor[128];
806 char *pszVendor = &szVendor[0];
807 CFTypeRef ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyVendorNameKey));
808 if ( ValueRef
809 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
810 && CFStringGetCString((CFStringRef)ValueRef, szVendor, sizeof(szVendor), kCFStringEncodingUTF8))
811 pszVendor = RTStrStrip(szVendor);
812 else
813 *pszVendor = '\0';
814
815 /* The product name. */
816 char szProduct[128];
817 char *pszProduct = &szProduct[0];
818 ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyProductNameKey));
819 if ( ValueRef
820 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
821 && CFStringGetCString((CFStringRef)ValueRef, szProduct, sizeof(szProduct), kCFStringEncodingUTF8))
822 pszProduct = RTStrStrip(szProduct);
823 else
824 *pszProduct = '\0';
825
826 /* Construct the two names and compare thwm with the one we're searching for. */
827 char szName1[256 + 32];
828 char szName2[256 + 32];
829 if (*pszVendor || *pszProduct)
830 {
831 if (*pszVendor && *pszProduct)
832 {
833 RTStrPrintf(szName1, sizeof(szName1), "%s %s", pszVendor, pszProduct);
834 RTStrPrintf(szName2, sizeof(szName2), "%s %s (#%u)", pszVendor, pszProduct, i);
835 }
836 else
837 {
838 strcpy(szName1, *pszVendor ? pszVendor : pszProduct);
839 RTStrPrintf(szName2, sizeof(szName2), "%s %s (#%u)", *pszVendor ? pszVendor : pszProduct, i);
840 }
841 }
842 else
843 {
844 RTStrPrintf(szName1, sizeof(szName1), "(#%u)", i);
845 strcpy(szName2, szName1);
846 }
847
848 if ( !strcmp(szName1, pThis->pszDeviceOpen)
849 || !strcmp(szName2, pThis->pszDeviceOpen))
850 {
851 /*
852 * Found it! Now, get the client interface and stuff.
853 * Note that we could also query kIOSCSITaskDeviceUserClientTypeID here if the
854 * MMC client plugin is missing. For now we assume this won't be necessary.
855 */
856 SInt32 Score = 0;
857 IOCFPlugInInterface **ppPlugInInterface = NULL;
858 krc = IOCreatePlugInInterfaceForService(DVDService, kIOMMCDeviceUserClientTypeID, kIOCFPlugInInterfaceID,
859 &ppPlugInInterface, &Score);
860 if (krc == KERN_SUCCESS)
861 {
862 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
863 CFUUIDGetUUIDBytes(kIOMMCDeviceInterfaceID),
864 (LPVOID *)&pThis->ppMMCDI);
865 (*ppPlugInInterface)->Release(ppPlugInInterface);
866 ppPlugInInterface = NULL;
867 if (hrc == S_OK)
868 {
869 pThis->ppScsiTaskDI = (*pThis->ppMMCDI)->GetSCSITaskDeviceInterface(pThis->ppMMCDI);
870 if (pThis->ppScsiTaskDI)
871 rc = VINF_SUCCESS;
872 else
873 {
874 LogRel(("GetSCSITaskDeviceInterface failed on '%s'\n", pThis->pszDeviceOpen));
875 rc = VERR_NOT_SUPPORTED;
876 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
877 }
878 }
879 else
880 {
881 rc = VERR_GENERAL_FAILURE;//RTErrConvertFromDarwinCOM(krc);
882 pThis->ppMMCDI = NULL;
883 }
884 }
885 else /* Check for kIOSCSITaskDeviceUserClientTypeID? */
886 rc = VERR_GENERAL_FAILURE;//RTErrConvertFromDarwinKern(krc);
887
888 /* Obtain exclusive access to the device so we can send SCSI commands. */
889 if (VBOX_SUCCESS(rc))
890 rc = drvHostBaseObtainExclusiveAccess(pThis, DVDService);
891
892 /* Cleanup on failure. */
893 if (VBOX_FAILURE(rc))
894 {
895 if (pThis->ppScsiTaskDI)
896 {
897 (*pThis->ppScsiTaskDI)->Release(pThis->ppScsiTaskDI);
898 pThis->ppScsiTaskDI = NULL;
899 }
900 if (pThis->ppMMCDI)
901 {
902 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
903 pThis->ppMMCDI = NULL;
904 }
905 }
906
907 IOObjectRelease(DVDService);
908 break;
909 }
910 }
911 CFRelease(PropsRef);
912 }
913 else
914 AssertMsgFailed(("krc=%#x\n", krc));
915
916 IOObjectRelease(DVDService);
917 i++;
918 }
919
920 IOObjectRelease(DVDServices);
921 return rc;
922
923#elif defined(RT_OS_LINUX)
924 /** @todo we've got RTFILE_O_NON_BLOCK now. Change the code to use RTFileOpen. */
925 int FileDevice = open(pThis->pszDeviceOpen, (pThis->fReadOnlyConfig ? O_RDONLY : O_RDWR) | O_NONBLOCK);
926 if (FileDevice < 0)
927 return RTErrConvertFromErrno(errno);
928 *pFileDevice = FileDevice;
929 return VINF_SUCCESS;
930
931#else
932 return RTFileOpen(pFileDevice, pThis->pszDeviceOpen,
933 (fReadOnly ? RTFILE_O_READ : RTFILE_O_READWRITE) | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
934#endif
935}
936
937#else /* RT_OS_SOLARIS */
938
939/**
940 * Solaris wrapper for RTFileOpen.
941 *
942 * Solaris has to deal with two filehandles, a block and a raw one. Rather than messing
943 * with drvHostBaseOpen's function signature & body, having a seperate one is better.
944 *
945 * @returns VBox status code.
946 */
947static int drvHostBaseOpen(PDRVHOSTBASE pThis, PRTFILE pFileBlockDevice, PRTFILE pFileRawDevice, bool fReadOnly)
948{
949 unsigned fFlags = (fReadOnly ? RTFILE_O_READ : RTFILE_O_READWRITE) | RTFILE_O_NON_BLOCK;
950 int rc = RTFileOpen(pFileBlockDevice, pThis->pszDeviceOpen, fFlags);
951 if (RT_SUCCESS(rc))
952 {
953 rc = RTFileOpen(pFileRawDevice, pThis->pszRawDeviceOpen, fFlags);
954 if (RT_FAILURE(rc))
955 {
956 LogRel(("DVD: failed to open device %s\n", pThis->pszRawDeviceOpen));
957 RTFileClose(*pFileBlockDevice);
958 }
959 }
960 else
961 LogRel(("DVD: failed to open device %s\n", pThis->pszRawDeviceOpen));
962 return rc;
963}
964#endif /* RT_OS_SOLARIS */
965
966
967/**
968 * (Re)opens the device.
969 *
970 * This is used to open the device during construction, but it's also used to re-open
971 * the device when a media is inserted. This re-open will kill off any cached data
972 * that Linux for some peculiar reason thinks should survive a media change...
973 *
974 * @returns VBOX status code.
975 * @param pThis Instance data.
976 */
977static int drvHostBaseReopen(PDRVHOSTBASE pThis)
978{
979#ifndef RT_OS_DARWIN /* Only *one* open for darwin. */
980 LogFlow(("%s-%d: drvHostBaseReopen: '%s'\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->pszDeviceOpen));
981
982 RTFILE FileDevice;
983#ifdef RT_OS_SOLARIS
984 RTFILE FileRawDevice;
985 int rc = drvHostBaseOpen(pThis, &FileDevice, &FileRawDevice, pThis->fReadOnlyConfig);
986#else
987 int rc = drvHostBaseOpen(pThis, &FileDevice, pThis->fReadOnlyConfig);
988#endif
989 if (VBOX_FAILURE(rc))
990 {
991 if (!pThis->fReadOnlyConfig)
992 {
993 LogFlow(("%s-%d: drvHostBaseReopen: '%s' - retry readonly (%Vrc)\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->pszDeviceOpen, rc));
994#ifdef RT_OS_SOLARIS
995 rc = drvHostBaseOpen(pThis, &FileDevice, &FileRawDevice, false);
996#else
997 rc = drvHostBaseOpen(pThis, &FileDevice, false);
998#endif
999 }
1000 if (VBOX_FAILURE(rc))
1001 {
1002 LogFlow(("%s-%d: failed to open device '%s', rc=%Vrc\n",
1003 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
1004 return rc;
1005 }
1006 pThis->fReadOnly = true;
1007 }
1008 else
1009 pThis->fReadOnly = pThis->fReadOnlyConfig;
1010
1011#ifdef RT_OS_SOLARIS
1012 if (pThis->FileRawDevice != NIL_RTFILE)
1013 RTFileClose(pThis->FileRawDevice);
1014 pThis->FileRawDevice = FileRawDevice;
1015#endif
1016
1017 if (pThis->FileDevice != NIL_RTFILE)
1018 RTFileClose(pThis->FileDevice);
1019 pThis->FileDevice = FileDevice;
1020#endif /* !RT_OS_DARWIN */
1021 return VINF_SUCCESS;
1022}
1023
1024
1025/**
1026 * Queries the media size.
1027 *
1028 * @returns VBox status code.
1029 * @param pThis Pointer to the instance data.
1030 * @param pcb Where to store the media size in bytes.
1031 */
1032static int drvHostBaseGetMediaSize(PDRVHOSTBASE pThis, uint64_t *pcb)
1033{
1034#ifdef RT_OS_DARWIN
1035 /*
1036 * Try a READ_CAPACITY command...
1037 */
1038 struct
1039 {
1040 uint32_t cBlocks;
1041 uint32_t cbBlock;
1042 } Buf = {0, 0};
1043 size_t cbBuf = sizeof(Buf);
1044 uint8_t abCmd[16] =
1045 {
1046 SCSI_READ_CAPACITY, 0, 0, 0, 0, 0, 0,
1047 0,0,0,0,0,0,0,0,0
1048 };
1049 int rc = DRVHostBaseScsiCmd(pThis, abCmd, 6, PDMBLOCKTXDIR_FROM_DEVICE, &Buf, &cbBuf, NULL, 0, 0);
1050 if (VBOX_SUCCESS(rc))
1051 {
1052 Assert(cbBuf == sizeof(Buf));
1053 Buf.cBlocks = RT_BE2H_U32(Buf.cBlocks);
1054 Buf.cbBlock = RT_BE2H_U32(Buf.cbBlock);
1055 //if (Buf.cbBlock > 2048) /* everyone else is doing this... check if it needed/right.*/
1056 // Buf.cbBlock = 2048;
1057 pThis->cbBlock = Buf.cbBlock;
1058
1059 *pcb = (uint64_t)Buf.cBlocks * Buf.cbBlock;
1060 }
1061 return rc;
1062
1063#elif defined(RT_OS_SOLARIS)
1064 /*
1065 * Sun docs suggests using DKIOCGGEOM instead of DKIOCGMEDIAINFO, but
1066 * Sun themselves use DKIOCGMEDIAINFO for DVDs/CDs, and use DKIOCGGEOM
1067 * for secondary storage devices.
1068 */
1069 struct dk_minfo MediaInfo;
1070 if (ioctl(pThis->FileRawDevice, DKIOCGMEDIAINFO, &MediaInfo) == 0)
1071 {
1072 *pcb = MediaInfo.dki_capacity * (uint64_t)MediaInfo.dki_lbsize;
1073 return VINF_SUCCESS;
1074 }
1075 return RTFileSeek(pThis->FileDevice, 0, RTFILE_SEEK_END, pcb);
1076
1077#elif defined(RT_OS_WINDOWS)
1078 /* use NT api, retry a few times if the media is being verified. */
1079 IO_STATUS_BLOCK IoStatusBlock = {0};
1080 FILE_FS_SIZE_INFORMATION FsSize= {0};
1081 NTSTATUS rcNt = NtQueryVolumeInformationFile((HANDLE)pThis->FileDevice, &IoStatusBlock,
1082 &FsSize, sizeof(FsSize), FileFsSizeInformation);
1083 int cRetries = 5;
1084 while (rcNt == STATUS_VERIFY_REQUIRED && cRetries-- > 0)
1085 {
1086 RTThreadSleep(10);
1087 rcNt = NtQueryVolumeInformationFile((HANDLE)pThis->FileDevice, &IoStatusBlock,
1088 &FsSize, sizeof(FsSize), FileFsSizeInformation);
1089 }
1090 if (rcNt >= 0)
1091 {
1092 *pcb = FsSize.TotalAllocationUnits.QuadPart * FsSize.BytesPerSector;
1093 return VINF_SUCCESS;
1094 }
1095
1096 /* convert nt status code to VBox status code. */
1097 /** @todo Make convertion function!. */
1098 int rc = VERR_GENERAL_FAILURE;
1099 switch (rcNt)
1100 {
1101 case STATUS_NO_MEDIA_IN_DEVICE: rc = VERR_MEDIA_NOT_PRESENT; break;
1102 case STATUS_VERIFY_REQUIRED: rc = VERR_TRY_AGAIN; break;
1103 }
1104 LogFlow(("drvHostBaseGetMediaSize: NtQueryVolumeInformationFile -> %#lx\n", rcNt, rc));
1105 return rc;
1106#else
1107 return RTFileSeek(pThis->FileDevice, 0, RTFILE_SEEK_END, pcb);
1108#endif
1109}
1110
1111
1112#ifdef RT_OS_DARWIN
1113/**
1114 * Execute a SCSI command.
1115 *
1116 * @param pThis The instance data.
1117 * @param pbCmd Pointer to the SCSI command.
1118 * @param cbCmd The size of the SCSI command.
1119 * @param enmTxDir The transfer direction.
1120 * @param pvBuf The buffer. Can be NULL if enmTxDir is PDMBLOCKTXDIR_NONE.
1121 * @param pcbBuf Where to get the buffer size from and put the actual transfer size. Can be NULL.
1122 * @param pbSense Where to put the sense data. Can be NULL.
1123 * @param cbSense Size of the sense data buffer.
1124 * @param cTimeoutMillies The timeout. 0 mean the default timeout.
1125 *
1126 * @returns VINF_SUCCESS on success (no sense code).
1127 * @returns VERR_UNRESOLVED_ERROR if sense code is present.
1128 * @returns Some other VBox status code on failures without sense code.
1129 *
1130 * @todo Fix VERR_UNRESOLVED_ERROR abuse.
1131 */
1132DECLCALLBACK(int) DRVHostBaseScsiCmd(PDRVHOSTBASE pThis, const uint8_t *pbCmd, size_t cbCmd, PDMBLOCKTXDIR enmTxDir,
1133 void *pvBuf, size_t *pcbBuf, uint8_t *pbSense, size_t cbSense, uint32_t cTimeoutMillies)
1134{
1135 /*
1136 * Minimal input validation.
1137 */
1138 Assert(enmTxDir == PDMBLOCKTXDIR_NONE || enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE || enmTxDir == PDMBLOCKTXDIR_TO_DEVICE);
1139 Assert(!pvBuf || pcbBuf);
1140 Assert(pvBuf || enmTxDir == PDMBLOCKTXDIR_NONE);
1141 Assert(pbSense || !cbSense);
1142 AssertPtr(pbCmd);
1143 Assert(cbCmd <= 16 && cbCmd >= 1);
1144 const size_t cbBuf = pcbBuf ? *pcbBuf : 0;
1145 if (pcbBuf)
1146 *pcbBuf = 0;
1147
1148# ifdef RT_OS_DARWIN
1149 Assert(pThis->ppScsiTaskDI);
1150
1151 int rc = VERR_GENERAL_FAILURE;
1152 SCSITaskInterface **ppScsiTaskI = (*pThis->ppScsiTaskDI)->CreateSCSITask(pThis->ppScsiTaskDI);
1153 if (!ppScsiTaskI)
1154 return VERR_NO_MEMORY;
1155 do
1156 {
1157 /* Setup the scsi command. */
1158 SCSICommandDescriptorBlock cdb = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1159 memcpy(&cdb[0], pbCmd, cbCmd);
1160 IOReturn irc = (*ppScsiTaskI)->SetCommandDescriptorBlock(ppScsiTaskI, cdb, cbCmd);
1161 AssertBreak(irc == kIOReturnSuccess,);
1162
1163 /* Setup the buffer. */
1164 if (enmTxDir == PDMBLOCKTXDIR_NONE)
1165 irc = (*ppScsiTaskI)->SetScatterGatherEntries(ppScsiTaskI, NULL, 0, 0, kSCSIDataTransfer_NoDataTransfer);
1166 else
1167 {
1168 IOVirtualRange Range = { (IOVirtualAddress)pvBuf, cbBuf };
1169 irc = (*ppScsiTaskI)->SetScatterGatherEntries(ppScsiTaskI, &Range, 1, cbBuf,
1170 enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE
1171 ? kSCSIDataTransfer_FromTargetToInitiator
1172 : kSCSIDataTransfer_FromInitiatorToTarget);
1173 }
1174 AssertBreak(irc == kIOReturnSuccess,);
1175
1176 /* Set the timeout. */
1177 irc = (*ppScsiTaskI)->SetTimeoutDuration(ppScsiTaskI, cTimeoutMillies ? cTimeoutMillies : 30000 /*ms*/);
1178 AssertBreak(irc == kIOReturnSuccess,);
1179
1180 /* Execute the command and get the response. */
1181 SCSI_Sense_Data SenseData = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1182 SCSIServiceResponse ServiceResponse = kSCSIServiceResponse_Request_In_Process;
1183 SCSITaskStatus TaskStatus = kSCSITaskStatus_GOOD;
1184 UInt64 cbReturned = 0;
1185 irc = (*ppScsiTaskI)->ExecuteTaskSync(ppScsiTaskI, &SenseData, &TaskStatus, &cbReturned);
1186 AssertBreak(irc == kIOReturnSuccess,);
1187 if (pcbBuf)
1188 *pcbBuf = cbReturned;
1189
1190 irc = (*ppScsiTaskI)->GetSCSIServiceResponse(ppScsiTaskI, &ServiceResponse);
1191 AssertBreak(irc == kIOReturnSuccess,);
1192 AssertBreak(ServiceResponse == kSCSIServiceResponse_TASK_COMPLETE,);
1193
1194 if (TaskStatus == kSCSITaskStatus_GOOD)
1195 rc = VINF_SUCCESS;
1196 else if ( TaskStatus == kSCSITaskStatus_CHECK_CONDITION
1197 && pbSense)
1198 {
1199 memset(pbSense, 0, cbSense); /* lazy */
1200 memcpy(pbSense, &SenseData, RT_MIN(sizeof(SenseData), cbSense));
1201 rc = VERR_UNRESOLVED_ERROR;
1202 }
1203 /** @todo convert sense codes when caller doesn't wish to do this himself. */
1204 /*else if ( TaskStatus == kSCSITaskStatus_CHECK_CONDITION
1205 && SenseData.ADDITIONAL_SENSE_CODE == 0x3A)
1206 rc = VERR_MEDIA_NOT_PRESENT; */
1207 else
1208 {
1209 rc = enmTxDir == PDMBLOCKTXDIR_NONE
1210 ? VERR_DEV_IO_ERROR
1211 : enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE
1212 ? VERR_READ_ERROR
1213 : VERR_WRITE_ERROR;
1214 if (pThis->cLogRelErrors++ < 10)
1215 LogRel(("DVD scsi error: cmd={%.*Rhxs} TaskStatus=%#x key=%#x ASC=%#x ASCQ=%#x (%Vrc)\n",
1216 cbCmd, pbCmd, TaskStatus, SenseData.SENSE_KEY, SenseData.ADDITIONAL_SENSE_CODE,
1217 SenseData.ADDITIONAL_SENSE_CODE_QUALIFIER, rc));
1218 }
1219 } while (0);
1220
1221 (*ppScsiTaskI)->Release(ppScsiTaskI);
1222
1223# endif
1224
1225 return rc;
1226}
1227#endif
1228
1229
1230/**
1231 * Media present.
1232 * Query the size and notify the above driver / device.
1233 *
1234 * @param pThis The instance data.
1235 */
1236int DRVHostBaseMediaPresent(PDRVHOSTBASE pThis)
1237{
1238 /*
1239 * Open the drive.
1240 */
1241 int rc = drvHostBaseReopen(pThis);
1242 if (VBOX_FAILURE(rc))
1243 return rc;
1244
1245 /*
1246 * Determin the size.
1247 */
1248 uint64_t cb;
1249 rc = pThis->pfnGetMediaSize(pThis, &cb);
1250 if (VBOX_FAILURE(rc))
1251 {
1252 LogFlow(("%s-%d: failed to figure media size of %s, rc=%Vrc\n",
1253 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
1254 return rc;
1255 }
1256
1257 /*
1258 * Update the data and inform the unit.
1259 */
1260 pThis->cbSize = cb;
1261 pThis->fMediaPresent = true;
1262 if (pThis->pDrvMountNotify)
1263 pThis->pDrvMountNotify->pfnMountNotify(pThis->pDrvMountNotify);
1264 LogFlow(("%s-%d: drvHostBaseMediaPresent: cbSize=%lld (%#llx)\n",
1265 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, pThis->cbSize, pThis->cbSize));
1266 return VINF_SUCCESS;
1267}
1268
1269
1270/**
1271 * Media no longer present.
1272 * @param pThis The instance data.
1273 */
1274void DRVHostBaseMediaNotPresent(PDRVHOSTBASE pThis)
1275{
1276 pThis->fMediaPresent = false;
1277 pThis->fLocked = false;
1278 pThis->PCHSGeometry.cCylinders = 0;
1279 pThis->PCHSGeometry.cHeads = 0;
1280 pThis->PCHSGeometry.cSectors = 0;
1281 pThis->LCHSGeometry.cCylinders = 0;
1282 pThis->LCHSGeometry.cHeads = 0;
1283 pThis->LCHSGeometry.cSectors = 0;
1284 if (pThis->pDrvMountNotify)
1285 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
1286}
1287
1288
1289#ifdef RT_OS_WINDOWS
1290
1291/**
1292 * Window procedure for the invisible window used to catch the WM_DEVICECHANGE broadcasts.
1293 */
1294static LRESULT CALLBACK DeviceChangeWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1295{
1296 Log2(("DeviceChangeWindowProc: hwnd=%08x uMsg=%08x\n", hwnd, uMsg));
1297 if (uMsg == WM_DESTROY)
1298 {
1299 PDRVHOSTBASE pThis = (PDRVHOSTBASE)GetWindowLong(hwnd, GWLP_USERDATA);
1300 if (pThis)
1301 ASMAtomicXchgSize(&pThis->hwndDeviceChange, NULL);
1302 PostQuitMessage(0);
1303 }
1304
1305 if (uMsg != WM_DEVICECHANGE)
1306 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1307
1308 PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
1309 PDRVHOSTBASE pThis = (PDRVHOSTBASE)GetWindowLongPtr(hwnd, GWLP_USERDATA);
1310 Assert(pThis);
1311 if (pThis == NULL)
1312 return 0;
1313
1314 switch (wParam)
1315 {
1316 case DBT_DEVICEARRIVAL:
1317 case DBT_DEVICEREMOVECOMPLETE:
1318 // Check whether a CD or DVD was inserted into or removed from a drive.
1319 if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
1320 {
1321 PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
1322 if ( (lpdbv->dbcv_flags & DBTF_MEDIA)
1323 && (pThis->fUnitMask & lpdbv->dbcv_unitmask))
1324 {
1325 RTCritSectEnter(&pThis->CritSect);
1326 if (wParam == DBT_DEVICEARRIVAL)
1327 {
1328 int cRetries = 10;
1329 int rc = DRVHostBaseMediaPresent(pThis);
1330 while (VBOX_FAILURE(rc) && cRetries-- > 0)
1331 {
1332 RTThreadSleep(50);
1333 rc = DRVHostBaseMediaPresent(pThis);
1334 }
1335 }
1336 else
1337 DRVHostBaseMediaNotPresent(pThis);
1338 RTCritSectLeave(&pThis->CritSect);
1339 }
1340 }
1341 break;
1342 }
1343 return TRUE;
1344}
1345
1346#endif /* RT_OS_WINDOWS */
1347
1348
1349/**
1350 * This thread will periodically poll the device for media presence.
1351 *
1352 * @returns Ignored.
1353 * @param ThreadSelf Handle of this thread. Ignored.
1354 * @param pvUser Pointer to the driver instance structure.
1355 */
1356static DECLCALLBACK(int) drvHostBaseMediaThread(RTTHREAD ThreadSelf, void *pvUser)
1357{
1358 PDRVHOSTBASE pThis = (PDRVHOSTBASE)pvUser;
1359 LogFlow(("%s-%d: drvHostBaseMediaThread: ThreadSelf=%p pvUser=%p\n",
1360 pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, ThreadSelf, pvUser));
1361#ifdef RT_OS_WINDOWS
1362 static WNDCLASS s_classDeviceChange = {0};
1363 static ATOM s_hAtomDeviceChange = 0;
1364
1365 /*
1366 * Register custom window class.
1367 */
1368 if (s_hAtomDeviceChange == 0)
1369 {
1370 memset(&s_classDeviceChange, 0, sizeof(s_classDeviceChange));
1371 s_classDeviceChange.lpfnWndProc = DeviceChangeWindowProc;
1372 s_classDeviceChange.lpszClassName = "VBOX_DeviceChangeClass";
1373 s_classDeviceChange.hInstance = GetModuleHandle("VBOXDD.DLL");
1374 Assert(s_classDeviceChange.hInstance);
1375 s_hAtomDeviceChange = RegisterClassA(&s_classDeviceChange);
1376 Assert(s_hAtomDeviceChange);
1377 }
1378
1379 /*
1380 * Create Window w/ the pThis as user data.
1381 */
1382 HWND hwnd = CreateWindow((LPCTSTR)s_hAtomDeviceChange, "", WS_POPUP, 0, 0, 0, 0, 0, 0, s_classDeviceChange.hInstance, 0);
1383 AssertMsg(hwnd, ("CreateWindow failed with %d\n", GetLastError()));
1384 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)pThis);
1385
1386 /*
1387 * Signal the waiting EMT thread that everything went fine.
1388 */
1389 ASMAtomicXchgSize(&pThis->hwndDeviceChange, hwnd);
1390 RTThreadUserSignal(ThreadSelf);
1391 if (!hwnd)
1392 {
1393 LogFlow(("%s-%d: drvHostBaseMediaThread: returns VERR_GENERAL_FAILURE\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance));
1394 return VERR_GENERAL_FAILURE;
1395 }
1396 LogFlow(("%s-%d: drvHostBaseMediaThread: Created hwndDeviceChange=%p\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance, hwnd));
1397
1398 /*
1399 * Message pump.
1400 */
1401 MSG Msg;
1402 BOOL fRet;
1403 while ((fRet = GetMessage(&Msg, NULL, 0, 0)) != FALSE)
1404 {
1405 if (fRet != -1)
1406 {
1407 TranslateMessage(&Msg);
1408 DispatchMessage(&Msg);
1409 }
1410 //else: handle the error and possibly exit
1411 }
1412 Assert(!pThis->hwndDeviceChange);
1413
1414#else /* !RT_OS_WINDOWS */
1415 bool fFirst = true;
1416 int cRetries = 10;
1417 while (!pThis->fShutdownPoller)
1418 {
1419 /*
1420 * Perform the polling (unless we've run out of 50ms retries).
1421 */
1422 if ( pThis->pfnPoll
1423 && cRetries-- > 0)
1424 {
1425
1426 int rc = pThis->pfnPoll(pThis);
1427 if (VBOX_FAILURE(rc))
1428 {
1429 RTSemEventWait(pThis->EventPoller, 50);
1430 continue;
1431 }
1432 }
1433
1434 /*
1435 * Signal EMT after the first go.
1436 */
1437 if (fFirst)
1438 {
1439 RTThreadUserSignal(ThreadSelf);
1440 fFirst = false;
1441 }
1442
1443 /*
1444 * Sleep.
1445 */
1446 int rc = RTSemEventWait(pThis->EventPoller, pThis->cMilliesPoller);
1447 if ( VBOX_FAILURE(rc)
1448 && rc != VERR_TIMEOUT)
1449 {
1450 AssertMsgFailed(("rc=%Vrc\n", rc));
1451 pThis->ThreadPoller = NIL_RTTHREAD;
1452 LogFlow(("drvHostBaseMediaThread: returns %Vrc\n", rc));
1453 return rc;
1454 }
1455 cRetries = 10;
1456 }
1457
1458#endif /* !RT_OS_WINDOWS */
1459
1460 /* (Don't clear the thread handle here, the destructor thread is using it to wait.) */
1461 LogFlow(("%s-%d: drvHostBaseMediaThread: returns VINF_SUCCESS\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance));
1462 return VINF_SUCCESS;
1463}
1464
1465/* -=-=-=-=- driver interface -=-=-=-=- */
1466
1467
1468/**
1469 * Done state load operation.
1470 *
1471 * @returns VBox load code.
1472 * @param pDrvIns Driver instance of the driver which registered the data unit.
1473 * @param pSSM SSM operation handle.
1474 */
1475static DECLCALLBACK(int) drvHostBaseLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
1476{
1477 PDRVHOSTBASE pThis = PDMINS2DATA(pDrvIns, PDRVHOSTBASE);
1478 LogFlow(("%s-%d: drvHostBaseMediaThread:\n", pThis->pDrvIns->pDrvReg->szDriverName, pThis->pDrvIns->iInstance));
1479 RTCritSectEnter(&pThis->CritSect);
1480
1481 /*
1482 * Tell the device/driver above us that the media status is uncertain.
1483 */
1484 if (pThis->pDrvMountNotify)
1485 {
1486 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
1487 if (pThis->fMediaPresent)
1488 pThis->pDrvMountNotify->pfnMountNotify(pThis->pDrvMountNotify);
1489 }
1490
1491 RTCritSectLeave(&pThis->CritSect);
1492 return VINF_SUCCESS;
1493}
1494
1495
1496/** @copydoc FNPDMDRVDESTRUCT */
1497DECLCALLBACK(void) DRVHostBaseDestruct(PPDMDRVINS pDrvIns)
1498{
1499 PDRVHOSTBASE pThis = PDMINS2DATA(pDrvIns, PDRVHOSTBASE);
1500 LogFlow(("%s-%d: drvHostBaseDestruct: iInstance=%d\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, pDrvIns->iInstance));
1501
1502 /*
1503 * Terminate the thread.
1504 */
1505 if (pThis->ThreadPoller != NIL_RTTHREAD)
1506 {
1507 pThis->fShutdownPoller = true;
1508 int rc;
1509 int cTimes = 50;
1510 do
1511 {
1512#ifdef RT_OS_WINDOWS
1513 if (pThis->hwndDeviceChange)
1514 PostMessage(pThis->hwndDeviceChange, WM_CLOSE, 0, 0); /* default win proc will destroy the window */
1515#else
1516 RTSemEventSignal(pThis->EventPoller);
1517#endif
1518 rc = RTThreadWait(pThis->ThreadPoller, 100, NULL);
1519 } while (cTimes-- > 0 && rc == VERR_TIMEOUT);
1520
1521 if (!rc)
1522 pThis->ThreadPoller = NIL_RTTHREAD;
1523 }
1524
1525 /*
1526 * Unlock the drive if we've locked it or we're in passthru mode.
1527 */
1528#ifdef RT_OS_DARWIN
1529 if ( ( pThis->fLocked
1530 || pThis->IBlock.pfnSendCmd)
1531 && pThis->ppScsiTaskDI
1532#else /** @todo Check if the other guys can mix pfnDoLock with scsi passthru.
1533 * (We're currently not unlocking the device after use. See todo in DevATA.cpp.) */
1534 if ( pThis->fLocked
1535 && pThis->FileDevice != NIL_RTFILE
1536#endif
1537 && pThis->pfnDoLock)
1538 {
1539 int rc = pThis->pfnDoLock(pThis, false);
1540 if (VBOX_SUCCESS(rc))
1541 pThis->fLocked = false;
1542 }
1543
1544 /*
1545 * Cleanup the other resources.
1546 */
1547#ifdef RT_OS_WINDOWS
1548 if (pThis->hwndDeviceChange)
1549 {
1550 if (SetWindowLongPtr(pThis->hwndDeviceChange, GWLP_USERDATA, 0) == (LONG_PTR)pThis)
1551 PostMessage(pThis->hwndDeviceChange, WM_CLOSE, 0, 0); /* default win proc will destroy the window */
1552 pThis->hwndDeviceChange = NULL;
1553 }
1554#else
1555 if (pThis->EventPoller != NULL)
1556 {
1557 RTSemEventDestroy(pThis->EventPoller);
1558 pThis->EventPoller = NULL;
1559 }
1560#endif
1561
1562#ifdef RT_OS_DARWIN
1563 /*
1564 * The unclaiming doesn't seem to mean much, the DVD is actaully
1565 * remounted when we release exclusive access. I'm not quite sure
1566 * if I should put the unclaim first or not...
1567 *
1568 * Anyway, that it's automatically remounted very good news for us,
1569 * because that means we don't have to mess with that ourselves. Of
1570 * course there is the unlikely scenario that we've succeeded in claiming
1571 * and umount the DVD but somehow failed to gain exclusive scsi access...
1572 */
1573 if (pThis->ppScsiTaskDI)
1574 {
1575 LogFlow(("%s-%d: releasing exclusive scsi access!\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
1576 (*pThis->ppScsiTaskDI)->ReleaseExclusiveAccess(pThis->ppScsiTaskDI);
1577 (*pThis->ppScsiTaskDI)->Release(pThis->ppScsiTaskDI);
1578 pThis->ppScsiTaskDI = NULL;
1579 }
1580 if (pThis->pDADisk)
1581 {
1582 LogFlow(("%s-%d: unclaiming the disk!\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
1583 DADiskUnclaim(pThis->pDADisk);
1584 CFRelease(pThis->pDADisk);
1585 pThis->pDADisk = NULL;
1586 }
1587 if (pThis->ppMMCDI)
1588 {
1589 LogFlow(("%s-%d: releasing the MMC object!\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
1590 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
1591 pThis->ppMMCDI = NULL;
1592 }
1593 if (pThis->MasterPort)
1594 {
1595 mach_port_deallocate(mach_task_self(), pThis->MasterPort);
1596 pThis->MasterPort = NULL;
1597 }
1598 if (pThis->pDASession)
1599 {
1600 LogFlow(("%s-%d: releasing the DA session!\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
1601 CFRelease(pThis->pDASession);
1602 pThis->pDASession = NULL;
1603 }
1604#else
1605 if (pThis->FileDevice != NIL_RTFILE)
1606 {
1607 int rc = RTFileClose(pThis->FileDevice);
1608 AssertRC(rc);
1609 pThis->FileDevice = NIL_RTFILE;
1610 }
1611#endif
1612
1613#ifdef RT_OS_SOLARIS
1614 if (pThis->FileRawDevice != NIL_RTFILE)
1615 {
1616 int rc = RTFileClose(pThis->FileRawDevice);
1617 AssertRC(rc);
1618 pThis->FileRawDevice = NIL_RTFILE;
1619 }
1620
1621 if (pThis->pszRawDeviceOpen)
1622 {
1623 RTStrFree(pThis->pszRawDeviceOpen);
1624 pThis->pszRawDeviceOpen = NULL;
1625 }
1626#endif
1627
1628 if (pThis->pszDevice)
1629 {
1630 MMR3HeapFree(pThis->pszDevice);
1631 pThis->pszDevice = NULL;
1632 }
1633
1634 if (pThis->pszDeviceOpen)
1635 {
1636 RTStrFree(pThis->pszDeviceOpen);
1637 pThis->pszDeviceOpen = NULL;
1638 }
1639
1640 /* Forget about the notifications. */
1641 pThis->pDrvMountNotify = NULL;
1642
1643 /* Leave the instance operational if this is just a cleanup of the state
1644 * after an attach error happened. So don't destry the critsect then. */
1645 if (!pThis->fKeepInstance && RTCritSectIsInitialized(&pThis->CritSect))
1646 RTCritSectDelete(&pThis->CritSect);
1647 LogFlow(("%s-%d: drvHostBaseDestruct completed\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance));
1648}
1649
1650
1651/**
1652 * Initializes the instance data (init part 1).
1653 *
1654 * The driver which derives from this base driver will override function pointers after
1655 * calling this method, and complete the construction by calling DRVHostBaseInitFinish().
1656 *
1657 * On failure call DRVHostBaseDestruct().
1658 *
1659 * @returns VBox status code.
1660 * @param pDrvIns Driver instance.
1661 * @param pCfgHandle Configuration handle.
1662 * @param enmType Device type.
1663 */
1664int DRVHostBaseInitData(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle, PDMBLOCKTYPE enmType)
1665{
1666 PDRVHOSTBASE pThis = PDMINS2DATA(pDrvIns, PDRVHOSTBASE);
1667 LogFlow(("%s-%d: DRVHostBaseInitData: iInstance=%d\n", pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, pDrvIns->iInstance));
1668
1669 /*
1670 * Initialize most of the data members.
1671 */
1672 pThis->pDrvIns = pDrvIns;
1673 pThis->fKeepInstance = false;
1674 pThis->ThreadPoller = NIL_RTTHREAD;
1675#ifdef RT_OS_DARWIN
1676 pThis->MasterPort = NULL;
1677 pThis->ppMMCDI = NULL;
1678 pThis->ppScsiTaskDI = NULL;
1679 pThis->cbBlock = 0;
1680 pThis->pDADisk = NULL;
1681 pThis->pDASession = NULL;
1682#else
1683 pThis->FileDevice = NIL_RTFILE;
1684#endif
1685#ifdef RT_OS_SOLARIS
1686 pThis->FileRawDevice = NIL_RTFILE;
1687#endif
1688 pThis->enmType = enmType;
1689 //pThis->cErrors = 0;
1690
1691 pThis->pfnGetMediaSize = drvHostBaseGetMediaSize;
1692
1693 /* IBase. */
1694 pDrvIns->IBase.pfnQueryInterface = drvHostBaseQueryInterface;
1695
1696 /* IBlock. */
1697 pThis->IBlock.pfnRead = drvHostBaseRead;
1698 pThis->IBlock.pfnWrite = drvHostBaseWrite;
1699 pThis->IBlock.pfnFlush = drvHostBaseFlush;
1700 pThis->IBlock.pfnIsReadOnly = drvHostBaseIsReadOnly;
1701 pThis->IBlock.pfnGetSize = drvHostBaseGetSize;
1702 pThis->IBlock.pfnGetType = drvHostBaseGetType;
1703 pThis->IBlock.pfnGetUuid = drvHostBaseGetUuid;
1704
1705 /* IBlockBios. */
1706 pThis->IBlockBios.pfnGetPCHSGeometry = drvHostBaseGetPCHSGeometry;
1707 pThis->IBlockBios.pfnSetPCHSGeometry = drvHostBaseSetPCHSGeometry;
1708 pThis->IBlockBios.pfnGetLCHSGeometry = drvHostBaseGetLCHSGeometry;
1709 pThis->IBlockBios.pfnSetLCHSGeometry = drvHostBaseSetLCHSGeometry;
1710 pThis->IBlockBios.pfnIsVisible = drvHostBaseIsVisible;
1711 pThis->IBlockBios.pfnGetType = drvHostBaseBiosGetType;
1712
1713 /* IMount. */
1714 pThis->IMount.pfnMount = drvHostBaseMount;
1715 pThis->IMount.pfnUnmount = drvHostBaseUnmount;
1716 pThis->IMount.pfnIsMounted = drvHostBaseIsMounted;
1717 pThis->IMount.pfnLock = drvHostBaseLock;
1718 pThis->IMount.pfnUnlock = drvHostBaseUnlock;
1719 pThis->IMount.pfnIsLocked = drvHostBaseIsLocked;
1720
1721 /*
1722 * Get the IBlockPort & IMountNotify interfaces of the above driver/device.
1723 */
1724 pThis->pDrvBlockPort = (PPDMIBLOCKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_BLOCK_PORT);
1725 if (!pThis->pDrvBlockPort)
1726 {
1727 AssertMsgFailed(("Configuration error: No block port interface above!\n"));
1728 return VERR_PDM_MISSING_INTERFACE_ABOVE;
1729 }
1730 pThis->pDrvMountNotify = (PPDMIMOUNTNOTIFY)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_MOUNT_NOTIFY);
1731
1732 /*
1733 * Query configuration.
1734 */
1735 /* Device */
1736 int rc = CFGMR3QueryStringAlloc(pCfgHandle, "Path", &pThis->pszDevice);
1737 if (VBOX_FAILURE(rc))
1738 {
1739 AssertMsgFailed(("Configuration error: query for \"Path\" string returned %Vra.\n", rc));
1740 return rc;
1741 }
1742
1743 /* Mountable */
1744 uint32_t u32;
1745 rc = CFGMR3QueryU32(pCfgHandle, "Interval", &u32);
1746 if (VBOX_SUCCESS(rc))
1747 pThis->cMilliesPoller = u32;
1748 else if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1749 pThis->cMilliesPoller = 1000;
1750 else if (VBOX_FAILURE(rc))
1751 {
1752 AssertMsgFailed(("Configuration error: Query \"Mountable\" resulted in %Vrc.\n", rc));
1753 return rc;
1754 }
1755
1756 /* ReadOnly */
1757 rc = CFGMR3QueryBool(pCfgHandle, "ReadOnly", &pThis->fReadOnlyConfig);
1758 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1759 pThis->fReadOnlyConfig = enmType == PDMBLOCKTYPE_DVD || enmType == PDMBLOCKTYPE_CDROM ? true : false;
1760 else if (VBOX_FAILURE(rc))
1761 {
1762 AssertMsgFailed(("Configuration error: Query \"ReadOnly\" resulted in %Vrc.\n", rc));
1763 return rc;
1764 }
1765
1766 /* Locked */
1767 rc = CFGMR3QueryBool(pCfgHandle, "Locked", &pThis->fLocked);
1768 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1769 pThis->fLocked = false;
1770 else if (VBOX_FAILURE(rc))
1771 {
1772 AssertMsgFailed(("Configuration error: Query \"Locked\" resulted in %Vrc.\n", rc));
1773 return rc;
1774 }
1775
1776 /* BIOS visible */
1777 rc = CFGMR3QueryBool(pCfgHandle, "BIOSVisible", &pThis->fBiosVisible);
1778 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1779 pThis->fBiosVisible = true;
1780 else if (VBOX_FAILURE(rc))
1781 {
1782 AssertMsgFailed(("Configuration error: Query \"BIOSVisible\" resulted in %Vrc.\n", rc));
1783 return rc;
1784 }
1785
1786 /* Uuid */
1787 char *psz;
1788 rc = CFGMR3QueryStringAlloc(pCfgHandle, "Uuid", &psz);
1789 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1790 RTUuidClear(&pThis->Uuid);
1791 else if (VBOX_SUCCESS(rc))
1792 {
1793 rc = RTUuidFromStr(&pThis->Uuid, psz);
1794 if (VBOX_FAILURE(rc))
1795 {
1796 AssertMsgFailed(("Configuration error: Uuid from string failed on \"%s\", rc=%Vrc.\n", psz, rc));
1797 MMR3HeapFree(psz);
1798 return rc;
1799 }
1800 MMR3HeapFree(psz);
1801 }
1802 else
1803 {
1804 AssertMsgFailed(("Configuration error: Failed to obtain the uuid, rc=%Vrc.\n", rc));
1805 return rc;
1806 }
1807
1808 /* Define whether attach failure is an error (default) or not. */
1809 bool fAttachFailError;
1810 rc = CFGMR3QueryBool(pCfgHandle, "AttachFailError", &fAttachFailError);
1811 if (VBOX_FAILURE(rc))
1812 fAttachFailError = true;
1813 pThis->fAttachFailError = fAttachFailError;
1814
1815 /* name to open & watch for */
1816#ifdef RT_OS_WINDOWS
1817 int iBit = toupper(pThis->pszDevice[0]) - 'A';
1818 if ( iBit > 'Z' - 'A'
1819 || pThis->pszDevice[1] != ':'
1820 || pThis->pszDevice[2])
1821 {
1822 AssertMsgFailed(("Configuration error: Invalid drive specification: '%s'\n", pThis->pszDevice));
1823 return VERR_INVALID_PARAMETER;
1824 }
1825 pThis->fUnitMask = 1 << iBit;
1826 RTStrAPrintf(&pThis->pszDeviceOpen, "\\\\.\\%s", pThis->pszDevice);
1827
1828#elif defined(RT_OS_SOLARIS)
1829 char *pszBlockDevName = getfullblkname(pThis->pszDevice);
1830 if (!pszBlockDevName)
1831 return VERR_NO_MEMORY;
1832 pThis->pszDeviceOpen = RTStrDup(pszBlockDevName); /* for RTStrFree() */
1833 free(pszBlockDevName);
1834 pThis->pszRawDeviceOpen = RTStrDup(pThis->pszDevice);
1835
1836#else
1837 pThis->pszDeviceOpen = RTStrDup(pThis->pszDevice);
1838#endif
1839
1840 if (!pThis->pszDeviceOpen)
1841 return VERR_NO_MEMORY;
1842
1843 return VINF_SUCCESS;
1844}
1845
1846
1847/**
1848 * Do the 2nd part of the init after the derived driver has overridden the defaults.
1849 *
1850 * On failure call DRVHostBaseDestruct().
1851 *
1852 * @returns VBox status code.
1853 * @param pThis Pointer to the instance data.
1854 */
1855int DRVHostBaseInitFinish(PDRVHOSTBASE pThis)
1856{
1857 int src = VINF_SUCCESS;
1858 PPDMDRVINS pDrvIns = pThis->pDrvIns;
1859
1860 /* log config summary */
1861 Log(("%s-%d: pszDevice='%s' (%s) cMilliesPoller=%d fReadOnlyConfig=%d fLocked=%d fBIOSVisible=%d Uuid=%Vuuid\n",
1862 pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, pThis->pszDevice, pThis->pszDeviceOpen, pThis->cMilliesPoller,
1863 pThis->fReadOnlyConfig, pThis->fLocked, pThis->fBiosVisible, &pThis->Uuid));
1864
1865 /*
1866 * Check that there are no drivers below us.
1867 */
1868 PPDMIBASE pBase;
1869 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBase);
1870 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
1871 {
1872 AssertMsgFailed(("Configuration error: No attached driver, please! (rc=%Vrc)\n", rc));
1873 return VERR_PDM_DRVINS_NO_ATTACH;
1874 }
1875
1876 /*
1877 * Register saved state.
1878 */
1879 rc = pDrvIns->pDrvHlp->pfnSSMRegister(pDrvIns, pDrvIns->pDrvReg->szDriverName, pDrvIns->iInstance, 1, 0,
1880 NULL, NULL, NULL,
1881 NULL, NULL, drvHostBaseLoadDone);
1882 if (VBOX_FAILURE(rc))
1883 return rc;
1884
1885 /*
1886 * Verify type.
1887 */
1888#ifdef RT_OS_WINDOWS
1889 UINT uDriveType = GetDriveType(pThis->pszDevice);
1890 switch (pThis->enmType)
1891 {
1892 case PDMBLOCKTYPE_FLOPPY_360:
1893 case PDMBLOCKTYPE_FLOPPY_720:
1894 case PDMBLOCKTYPE_FLOPPY_1_20:
1895 case PDMBLOCKTYPE_FLOPPY_1_44:
1896 case PDMBLOCKTYPE_FLOPPY_2_88:
1897 if (uDriveType != DRIVE_REMOVABLE)
1898 {
1899 AssertMsgFailed(("Configuration error: '%s' is not a floppy (type=%d)\n",
1900 pThis->pszDevice, uDriveType));
1901 return VERR_INVALID_PARAMETER;
1902 }
1903 break;
1904 case PDMBLOCKTYPE_CDROM:
1905 case PDMBLOCKTYPE_DVD:
1906 if (uDriveType != DRIVE_CDROM)
1907 {
1908 AssertMsgFailed(("Configuration error: '%s' is not a cdrom (type=%d)\n",
1909 pThis->pszDevice, uDriveType));
1910 return VERR_INVALID_PARAMETER;
1911 }
1912 break;
1913 case PDMBLOCKTYPE_HARD_DISK:
1914 default:
1915 AssertMsgFailed(("enmType=%d\n", pThis->enmType));
1916 return VERR_INVALID_PARAMETER;
1917 }
1918#endif
1919
1920 /*
1921 * Open the device.
1922 */
1923#ifdef RT_OS_DARWIN
1924 rc = drvHostBaseOpen(pThis, NULL, pThis->fReadOnlyConfig);
1925#else
1926 rc = drvHostBaseReopen(pThis);
1927#endif
1928 if (VBOX_FAILURE(rc))
1929 {
1930 char *pszDevice = pThis->pszDevice;
1931#ifndef RT_OS_DARWIN
1932 char szPathReal[256];
1933 if ( RTPathExists(pszDevice)
1934 && RT_SUCCESS(RTPathReal(pszDevice, szPathReal, sizeof(szPathReal))))
1935 pszDevice = szPathReal;
1936 pThis->FileDevice = NIL_RTFILE;
1937#endif
1938#ifdef RT_OS_SOLARIS
1939 pThis->FileRawDevice = NIL_RTFILE;
1940#endif
1941
1942 /*
1943 * Disable CD/DVD passthrough in case it was enabled. Would cause
1944 * weird failures later when the guest issues commands. These would
1945 * all fail because of the invalid file handle. So use the normal
1946 * virtual CD/DVD code, which deals more gracefully with unavailable
1947 * "media" - actually a complete drive in this case.
1948 */
1949 pThis->IBlock.pfnSendCmd = NULL;
1950 AssertMsgFailed(("Could not open host device %s, rc=%Vrc\n", pszDevice, rc));
1951 switch (rc)
1952 {
1953 case VERR_ACCESS_DENIED:
1954 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1955#ifdef RT_OS_LINUX
1956 N_("Cannot open host device '%s' for %s access. Check the permissions "
1957 "of that device ('/bin/ls -l %s'): Most probably you need to be member "
1958 "of the device group. Make sure that you logout/login after changing "
1959 "the group settings of the current user"),
1960#else
1961 N_("Cannot open host device '%s' for %s access. Check the permissions "
1962 "of that device"),
1963#endif
1964 pszDevice, pThis->fReadOnlyConfig ? "readonly" : "read/write",
1965 pszDevice);
1966 default:
1967 {
1968 if (pThis->fAttachFailError)
1969 return rc;
1970 int erc = PDMDrvHlpVMSetRuntimeError(pDrvIns,
1971 false, "DrvHost_MOUNTFAIL",
1972 N_("Cannot attach to host device '%s'"), pszDevice);
1973 AssertRC(erc);
1974 src = rc;
1975 }
1976 }
1977 }
1978#ifdef RT_OS_WINDOWS
1979 if (VBOX_SUCCESS(src))
1980 DRVHostBaseMediaPresent(pThis);
1981#endif
1982
1983 /*
1984 * Lock the drive if that's required by the configuration.
1985 */
1986 if (pThis->fLocked)
1987 {
1988 if (pThis->pfnDoLock)
1989 rc = pThis->pfnDoLock(pThis, true);
1990 if (VBOX_FAILURE(rc))
1991 {
1992 AssertMsgFailed(("Failed to lock the dvd drive. rc=%Vrc\n", rc));
1993 return rc;
1994 }
1995 }
1996
1997#ifndef RT_OS_WINDOWS
1998 if (VBOX_SUCCESS(src))
1999 {
2000 /*
2001 * Create the event semaphore which the poller thread will wait on.
2002 */
2003 rc = RTSemEventCreate(&pThis->EventPoller);
2004 if (VBOX_FAILURE(rc))
2005 return rc;
2006 }
2007#endif
2008
2009 /*
2010 * Initialize the critical section used for serializing the access to the media.
2011 */
2012 rc = RTCritSectInit(&pThis->CritSect);
2013 if (VBOX_FAILURE(rc))
2014 return rc;
2015
2016 if (VBOX_SUCCESS(src))
2017 {
2018 /*
2019 * Start the thread which will poll for the media.
2020 */
2021 rc = RTThreadCreate(&pThis->ThreadPoller, drvHostBaseMediaThread, pThis, 0,
2022 RTTHREADTYPE_INFREQUENT_POLLER, RTTHREADFLAGS_WAITABLE, "DVDMEDIA");
2023 if (VBOX_FAILURE(rc))
2024 {
2025 AssertMsgFailed(("Failed to create poller thread. rc=%Vrc\n", rc));
2026 return rc;
2027 }
2028
2029 /*
2030 * Wait for the thread to start up (!w32:) and do one detection loop.
2031 */
2032 rc = RTThreadUserWait(pThis->ThreadPoller, 10000);
2033 AssertRC(rc);
2034#ifdef RT_OS_WINDOWS
2035 if (!pThis->hwndDeviceChange)
2036 return VERR_GENERAL_FAILURE;
2037#endif
2038 }
2039
2040 if (VBOX_FAILURE(src))
2041 return src;
2042 return rc;
2043}
2044
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