如何在 Delphi 中获取 NVMe 驱动器的实际序列号?
可以继续使用 IOCTL_STORAGE_QUERY_PROPERTY。在 Windows 10 及以后的受支持环境中,获取设备所报告序列号的标准方式是通过 NVMe 协议专用查询发送 Identify Controller 请求,再读取返回结构中的 SN[20]。问题中的查询参数基本正确,主要问题在字符串复制和返回缓冲区的解析上。微软 NVMe 查询文档
SN 是厂商写入 NVM 子系统的序列号。如果正确读取后仍与标签上的号码不同,需要核对查询的设备,以及厂商对标签号码的定义。换用另一个 Windows API,并不保证能得到另一个“实际序列号”。SN 字段定义
原代码中的问题
1. Move 的复制方向反了
原代码是:
SetLength(Serial, 40);
Move(Serial, Data^.SN[0], 40);
Move 的参数顺序为:
Move(Source, Dest, Count);
原代码会向 Data^.SN 写入数据,没有将序列号复制到 Serial。Serial 是字符串变量,访问它的字符缓冲区时应使用 Serial[1]。System.Move 文档
使用 Move 时,应写成:
SetLength(Serial, SizeOf(Data^.SN));
Move(Data^.SN[0], Serial[1], SizeOf(Data^.SN));
也可以用 SetString:
SetString(Serial, PAnsiChar(@Data^.SN[0]), SizeOf(Data^.SN));
SetString 按指定长度复制字符,不要求源数据以 #0 结尾。System.SetString 文档
2. 序列号长度是 20 字节
Identify Controller 数据中的字段分别是:
SN[20] 序列号
MN[40] 型号
FR[8] 固件版本
读取 SN 时使用 40 字节,会连同后面的部分型号字段一起读出。SN 是固定长度的 ASCII 字段,应按 20 字节读取,再处理尾部填充。Identify Controller 结构定义
3. 应根据返回的偏移量定位数据
协议查询返回 STORAGE_PROTOCOL_DATA_DESCRIPTOR,其中包含 ProtocolSpecificData。
ProtocolDataOffset 以 ProtocolSpecificData 结构自身的地址为起点,不是整个输出缓冲区的起点。数据地址应这样计算:
Identify 数据地址 =
ProtocolSpecificData 的地址 + ProtocolDataOffset
原代码将数据地址固定在查询结构之后。在当前布局和常见返回值下,这个位置可能恰好正确,但仍应根据返回的偏移量定位数据,并检查长度。ProtocolDataOffset 定义
修正后的 Delphi 实现
保留问题中的类型声明、{$ALIGN 4}、{$Z4} 和常量定义,补充以下返回描述符类型,再替换 GetNVMeSerialNumber 函数。
type
TStorageProtocolDataDescriptor = record
Version: ULONG;
Size: ULONG;
ProtocolSpecificData: TStorageProtocolSpecificData;
end;
PStorageProtocolDataDescriptor = ^TStorageProtocolDataDescriptor;
function GetNVMeSerialNumber(hDevice: THandle): string;
var
Buffer: TBytes;
Query: PStorageProtocolSpecificQuery;
Descriptor: PStorageProtocolDataDescriptor;
ProtocolData: PStorageProtocolSpecificData;
Data: PNVMeIdentifyControllerData;
BytesReturned: DWORD;
ProtocolBase: NativeUInt;
Available: NativeUInt;
DataOffset: NativeUInt;
Serial: AnsiString;
begin
// 检查本例所使用的 Windows 结构布局。
if (SizeOf(TStorageProtocolSpecificData) <> 40) or
(SizeOf(TStorageProtocolSpecificQuery) <> 48) or
(SizeOf(TStorageProtocolDataDescriptor) <> 48) or
(SizeOf(TNVMeIdentifyControllerData) <> 4096) then
raise Exception.Create('Unexpected storage structure layout');
SetLength(Buffer,
SizeOf(TStorageProtocolSpecificQuery) +
SizeOf(TNVMeIdentifyControllerData));
ZeroMemory(@Buffer[0], Length(Buffer));
Query := PStorageProtocolSpecificQuery(@Buffer[0]);
Query^.PropertyId := StorageAdapterProtocolSpecificProperty;
Query^.QueryType := PropertyStandardQuery;
with Query^.SpecificData do
begin
ProtocolType := ProtocolTypeNvme;
DataType := Ord(NVMeDataTypeIdentify);
ProtocolDataRequestValue := NVME_IDENTIFY_CNS_CONTROLLER;
ProtocolDataRequestSubValue := 0;
ProtocolDataOffset := SizeOf(TStorageProtocolSpecificData);
ProtocolDataLength := SizeOf(TNVMeIdentifyControllerData);
end;
BytesReturned := 0;
if not DeviceIoControl(
hDevice,
IOCTL_STORAGE_QUERY_PROPERTY,
@Buffer[0],
DWORD(Length(Buffer)),
@Buffer[0],
DWORD(Length(Buffer)),
BytesReturned,
nil
) then
RaiseLastOSError;
if (BytesReturned < SizeOf(TStorageProtocolDataDescriptor)) or
(BytesReturned > DWORD(Length(Buffer))) then
raise Exception.Create('Invalid returned buffer length');
Descriptor := PStorageProtocolDataDescriptor(@Buffer[0]);
if (Descriptor^.Version <> SizeOf(TStorageProtocolDataDescriptor)) or
(Descriptor^.Size <> SizeOf(TStorageProtocolDataDescriptor)) then
raise Exception.Create('Invalid protocol descriptor');
ProtocolData := @Descriptor^.ProtocolSpecificData;
if (ProtocolData^.ProtocolType <> ProtocolTypeNvme) or
(ProtocolData^.DataType <> Ord(NVMeDataTypeIdentify)) then
raise Exception.Create('Unexpected protocol data');
if ProtocolData^.ProtocolDataOffset <
SizeOf(TStorageProtocolSpecificData) then
raise Exception.Create('Invalid protocol data offset');
// 偏移量以 ProtocolSpecificData 的起始地址为基准。
ProtocolBase :=
NativeUInt(ProtocolData) - NativeUInt(@Buffer[0]);
Available := NativeUInt(BytesReturned) - ProtocolBase;
if NativeUInt(ProtocolData^.ProtocolDataOffset) > Available then
raise Exception.Create('Protocol data offset exceeds buffer');
DataOffset :=
ProtocolBase + NativeUInt(ProtocolData^.ProtocolDataOffset);
Dec(Available, NativeUInt(ProtocolData^.ProtocolDataOffset));
if (ProtocolData^.ProtocolDataLength <
SizeOf(TNVMeIdentifyControllerData)) or
(NativeUInt(ProtocolData^.ProtocolDataLength) > Available) then
raise Exception.Create('Invalid Identify Controller data length');
Data := PNVMeIdentifyControllerData(@Buffer[DataOffset]);
SetString(
Serial,
PAnsiChar(@Data^.SN[0]),
SizeOf(Data^.SN)
);
Result := TrimRight(string(Serial));
end;
输入时,缓冲区开头存放查询参数;输出时,同一位置需要按返回描述符解析。代码中的描述符检查和数据定位方式与微软文档中的协议查询流程一致。返回描述符文档
原来的调用方式可以保留:
DrivePath := Format('\\.\PhysicalDrive%d', [DriveNumber]);
hDevice := CreateFile(
PWideChar(DrivePath),
0,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
0,
0
);
if hDevice = INVALID_HANDLE_VALUE then
RaiseLastOSError;
try
WriteLn('NVMe Serial Number: ', GetNVMeSerialNumber(hDevice));
finally
CloseHandle(hDevice);
end;
为什么两种查询可能返回相同结果
StorageDeviceProperty 返回通用存储设备描述符,协议专用查询返回 NVMe Identify Controller 数据。如果驱动用同一个设备序列号填充通用描述符,两种查询就可能得到相同的字符串。仅凭结果相同,无法判断序列号有误。
原来的 Move 没有正确提取 SN,需要先修正代码,再比较两种查询的结果。如果修正后仍与预期不符,可以按以下顺序排查:
- 确认
PhysicalDriveN对应目标设备,不要默认目标盘始终是PhysicalDrive0。同时核对容量、型号和固件版本。 - 保留
SN的原始 20 字节,以十六进制查看,排除显示或截断问题。NVMe 的该字段是 ASCII,不应直接套用 ATA 字符串的字节交换规则。 - 核对厂商工具与标签上号码的含义。设备序列号、包装编号和资产编号未必相同。
- 如果经过 RAID、USB 桥接或虚拟化层,需要确认该存储路径是否支持查询底层 NVMe 控制器。上述函数不能保证穿过这些中间层取得物理设备信息。
原程序读取 SerialNumberOffset、VendorIdOffset 等字段时,也应先确认偏移量非零且位于实际返回范围内,并确认字符串在缓冲区内结束,再将相应地址作为 PAnsiChar 使用。
对于标准 Identify 请求,优先使用这里的 IOCTL_STORAGE_QUERY_PROPERTY 协议查询方式。微软文档说明,标准 Identify 等命令应使用相应查询接口;IOCTL_STORAGE_PROTOCOL_COMMAND 的 NVMe 透传机制主要用于厂商专用命令。NVMe 命令使用说明
备注:内容仅供参考。
