Proper locking when writing drives

Hello, Since Vista volumes and (volume extents on) physical drives are protected from write access. Now locking or dismounting has to be used...
Proper locking when writing drives
Hello,

Since Vista volumes and (volume extents on) physical drives are
protected from write access. Now locking or dismounting has to be used
before accessing a disk.

I have experimented and found a solution but wonder why it’s working and
if it is the proper way of doing it.
Please note that I want to write a disk from user mode, i.e. from a
normal application, not a driver.

I created the following example code:
————————————-

<<<<<<<<<<<<<

// removed error handling in functions for simplicity

HANDLE OpenDrive(char* drivestr)
{
return CreateFile(drivestr, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_NO_BUFFERING |
FILE_FLAG_WRITE_THROUGH, 0);
}

void CloseDrive(HANDLE DriveHandle)
{
CloseHandle(DriveHandle);
}

void DismountVolume(HANDLE DriveHandle)
{
DWORD dummy;
DeviceIoControl(DriveHandle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0,
dummy, NULL);
}

void WriteProtectedSector(HANDLE DriveHandle)
{
// writes sector 1024, original code uses
// ReadFile/WriteFile/SetFilePointer
}

void test()
{
// In this test a physical disk is accessed (PhysicalDriveID) which
// hosts only one volume (LogicalDriveID).
// The disk/volume is *not* the system drive (i.e. can be
// dismounted/locked). Both IDs are hard coded constants to simplify
// testing.

HANDLE PhysicalDriveHandle = OpenDrive(PhysicalDriveID);
HANDLE LogicalDriveHandle = OpenDrive(LogicalDriveID);

DismountVolume(LogicalDriveHandle);

DismountVolume(PhysicalDriveHandle);

WriteProtectedSector(PhysicalDriveHandle);

CloseDrive(LogicalDriveHandle);

CloseDrive(PhysicalDriveHandle);
}
>>>>>>>>>>>>>

My questions:

Why is it not enough to dismount the logical disk (i.e. volume)?

It seems I always have to also dismount the physical disk. But how is it
possible a *physical* disk can be dismounted (the function
FSCTL_DISMOUNT_VOLUME explicitly has volume in its name)? Is this
behavior defined or am I just lucky?

The order in which I dismount makes no difference. Is this always the
case or is there a preferred order?

Thinking about sharing issues:

– If you dismount locking doesn’t seem to add anything. Handles opened
by other program become invalid. When is it useful?

– Should I try to acquire an exclusive lock for the sake of data
consistency (like exclusive access when writing files) or is dismounting
enough?

– Is it possible to detect when a volume/physical disk was dismounted by
another program so I can refresh my information about the drive?

I you reached until here thanks for having taken the time to read.
Looking forward to you suggestions/answers,
Regards, Maël Hörz

We will be happy to hear your thoughts

Leave a reply

TechEggs
Logo