How to query the list of disks/partitions for a certain volume (and viceversa)

A good comment in one of my previous posts:

>>> Any idea how to get a Volume Name ( \\?\Vol{GUID }) or drive letter for a given disk XX + partition XX? i.e. If I have a partition table for DiskDrive0 I need to find out what volume/drive letter is on DiskDrive0 Partition 1. I can't seem to find any API's or registry data which gets me there.

Interesting. I initially thought that a combination of Win32_LogicalDisk --> Win32_LogicalDiskToPartition --> Win32_DiskPartition Win32_LogicalDrive, Win32_DiskDriveToDiskPartition --> Win32_DiskDrive will give the right answer (as in the script sample presented in the WMI site). Unfortunately this does not work for volumes that do not have drive letters (for example mount points, or even volumes with only a volume name).

In this case, here is the method to get the list of disks and partitions that are associated with a volume:
1) Open a direct handle to the volume name (but WITHOUT the terminating backslash, for example "\\?\Volume{GUID}" and not "\\?\Volume{GUID}\")
2) Send down the IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS using the DeviceIoControl API. Make sure that you reserve a output buffer which is large enough (if the buffer is not large enough you will get the ERROR_INSUFFICIENT_BUFFER anyway and the required size will be returned.
3) This IOCTL will return VOLUME_DISK_EXTENTS structure which contains an internal array of DISK_EXTENT structures. Each disk extent contains a member called "DiskNumber" which is, obviously, the disk number. There is also another member called "StartingOffset" that identifies the partition offset.

Please note that you have two important cases:
1) For basic disks, you will always get a single disk extent, which identifies the partition & disk where the volume resides.
2) For dynamic volumes, you might get a list of one or more disk extents, each of them residing potentially on a different disk at a different offset. This is because dynamic volumes can span disks sometimes.

Now, there is the opposite question on how to get the list of volumes that reside on a certain disk. Assuming that you know the disk device, the answer is the following:
1) Get the Disk Number for your disk device. This is the number in the \\.\physicaldriveNN symbolic link, so for example the disk with the device \\.\physicaldrive3 has the Disk Number = 3. If you have the disk device in a different format, then you can get the Disk Number by sending down the IOCTL_STORAGE_GET_DEVICE_NUMBER ioctl using the same DeviceIoControl mentioned above.
2) Enumerate all volumes in the system using FindFirstVolume/FindNextVolume.
3) For each volume, enumerate all the disk extents as described above. If one of the disk extents have the same disk number as your disk, then you are done. You already have the volume name and the partition offset.