Why DeviceIoControl sometimes not working (error=2)? - c++

DISK_PERFORMANCE DiskPerformance = {0};
DWORD dwDiskInfoSize = 0;
for (int i = 0; i < 10; i++)
{
std::printf("Try %d th Open \\\\.\\c:\n", i);
HANDLE hDevice = CreateFile(L"\\\\.\\c:",
0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
//SYNCHRONIZE | FILE_READ_ATTRIBUTES,
NULL,
OPEN_EXISTING,
0,
NULL);
std::printf("hDevice = %p\n", hDevice);
if (hDevice == INVALID_HANDLE_VALUE)
{
std::printf("CreateFile failed = %d \n", GetLastError());
continue;
}
if (!DeviceIoControl(hDevice,
IOCTL_DISK_PERFORMANCE,
NULL,
0,
&DiskPerformance,
sizeof(DiskPerformance),
&dwDiskInfoSize,
NULL))
{
CloseHandle(hDevice);
std::printf("DeviceIoControl failed = %d \n", GetLastError());
continue;
}
std::printf("QuDeviceIoControlery Success\n");
CloseHandle(hDevice);
Sleep(1000);
std::printf("\n\n");
}
I restart the program and about 95% DeviceIoControl will get the error 2 and 5% get the correct result....
I can not reproduce the error for another machine because this code is 100% working on my laptop (win10).
My target OS is Windows Server 2016.

The disk performance counters in Windows Server 2016 are turned off by default.
You can run CMD as admin and enter diskperf -Y to enable the disk counter of the task manager.

Related

How to find all connected removable USB storage devices in Windows?

I'm writing a program that processes USB drives, to get information about connecting a new device, I signed up for a window message WM_DEVICECHANGE. But I, of course, do not receive messages about the devices that were connected before my program was launched. To process such devices, I wrote a search function, but I get a strange result. It finds my flash drive, but does not recognize it to be removable. Why?
Function
bool FindConnectedRemovableUsbstorDevices(std::list<std::wstring>& UsbList)
{
std::wstring ClassGuidString(L"{53F56307-B6BF-11D0-94F2-00A0C91EFB8B}");
GUID ClassGuid;
BYTE buf[1024];
PSP_DEVICE_INTERFACE_DETAIL_DATA_W pspdidd = reinterpret_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W>(buf);
SP_DEVICE_INTERFACE_DATA spdid;
SP_DEVINFO_DATA spdd;
DWORD size;
SP_DEVINFO_DATA dev_data;
DWORD properties;
if(NOERROR != CLSIDFromString(ClassGuidString.c_str(), &ClassGuid))
return false;
HDEVINFO dev_info = INVALID_HANDLE_VALUE;
dev_info = SetupDiGetClassDevs(&ClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (dev_info == INVALID_HANDLE_VALUE)
return false;
DWORD index = 0;
BOOL ret = FALSE;
spdid.cbSize = sizeof(spdid);
while (true)
{
ret = SetupDiEnumDeviceInterfaces(dev_info, NULL, &ClassGuid, index, &spdid);
if (!ret)
break;
size = 0;
SetupDiGetDeviceInterfaceDetail(dev_info, &spdid, NULL, 0, &size, NULL);
//Get required size
if (size == 0 || size >= sizeof(buf))
continue;
//prepare structs
ZeroMemory(reinterpret_cast<PVOID>(pspdidd), 1024);
pspdidd->cbSize = sizeof(*pspdidd); // 5 Bytes!
ZeroMemory(reinterpret_cast<PVOID>(&spdd), sizeof(spdd));
spdd.cbSize = sizeof(spdd);
BOOL res = SetupDiGetDeviceInterfaceDetail(dev_info, &spdid, pspdidd, size, &size, &spdd);
//Get info
if (!res)
continue;
HANDLE drive = CreateFileW(pspdidd->DevicePath, FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);//open device
if (drive == INVALID_HANDLE_VALUE)
continue;
printf("\n%S\r\n", pspdidd->DevicePath);
DWORD bytes_returned = 0;
BOOL b = DeviceIoControl(drive, IOCTL_STORAGE_CHECK_VERIFY2, NULL, 0, NULL, 0, &bytes_returned, NULL);
if (!b) //check is card reader?
{
printf("IOCTL_STORAGE_CHECK_VERIFY2 error = %d\r\n", GetLastError());
goto stop_process_device;
}
bytes_returned = 0;
STORAGE_DEVICE_NUMBER sdn;
//Get Drive number
b = DeviceIoControl(drive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &bytes_returned, NULL);
if (!b)
goto stop_process_device;
RtlZeroMemory(&dev_data, sizeof(SP_DEVINFO_DATA));
dev_data.cbSize = sizeof(dev_data);
if (SetupDiEnumDeviceInfo(dev_info, sdn.DeviceNumber, &dev_data))
{
//check property
b = SetupDiGetDeviceRegistryProperty(dev_info, &dev_data, SPDRP_REMOVAL_POLICY, NULL,
reinterpret_cast<PBYTE>(&properties), sizeof(properties), NULL);
if (b && properties != CM_REMOVAL_POLICY_EXPECT_NO_REMOVAL)
{
UsbList.push_back(pspdidd->DevicePath);
printf("REMOVAL\r\n");
}
}
stop_process_device:
CloseHandle(drive);
index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
return true;
}
And output
\\?\usbstor#disk&ven_generic-&prod_ms#ms-pro#hg&rev_1.00#20090703819900000&1#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
IOCTL_STORAGE_CHECK_VERIFY2 error = 21
\\?\ide#diskst3500418as_____________________________cc38____#5&5c6cfd6&0&1.0.0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
REMOVAL
\\?\usbstor#disk&ven_generic-&prod_sd#mmc&rev_1.00#20090703819900000&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
IOCTL_STORAGE_CHECK_VERIFY2 error = 21
\\?\scsi#disk&ven_ocz&prod_revodrive3_x2#5&19ad1f72&0&000000#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
\\?\ide#diskst1000lm014-1ej164______________________sm30____#5&2ea7e938&0&0.1.0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
\\?\usbstor#disk&ven_sandisk&prod_extreme&rev_0001#aa010823150434152862&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
\\?\ide#diskwdc_wd1002fbys-02a6b0___________________03.00c06#5&2ea7e938&0&0.0.0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
REMOVAL
Error 21 is empty card reader.
Sandisk is my flash. In Debug i saw that SetupDiGetDeviceRegistryProperty return property CM_REMOVAL_POLICY_EXPECT_NO_REMOVAL, but i really don't know why...
If you just want to find the connected removable devices, there's a much simpler alternative using GetLogicalDriveStrings() and GetDriveType():
#define MAX_DRIVES 256
bool FindConnectedRemovableUsbstorDevices(std::list<std::wstring>& UsbList)
{
wchar_t drives[MAX_DRIVES];
wchar_t* temp = drives;
if (GetLogicalDriveStringsW(MAX_DRIVES, drives) == 0)
return false;
while (*temp != NULL)
{
if (GetDriveTypeW(temp) == 2 /* DRIVE_REMOVABLE */)
UsbList.push_back(temp);
// Go to the next drive
temp += lstrlenW(temp) + 1;
}
return true;
}
I don't know why my fisrt method of detection removable media works so strange, but method of RbMm works great. I send IOCTL query to every found device with IOCTL_STORAGE_QUERY_PROPERTY with StorageDeviceProperty and look for STORAGE_DEVICE_DESCRIPTOR.RemovableMedia field. All my devices recognized successfully and right.

write file in raw usb c++

this is my code:
int main(int argc, CHAR* argv[]) {
using namespace std;
PVOID data[1024];
DWORD dwBytesRead = 0;
DWORD dwBytesWrite = 512;
HANDLE hFile = CreateFile(L"\\\\.\\E:", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);//open usb
if (hFile == INVALID_HANDLE_VALUE) {
printf("Error %x", GetLastError());
return 1;
}
printf ("created usb hendle\n");
LARGE_INTEGER a = { 50688 };
SetFilePointerEx(hFile, a,NULL,0); //set the pointer to c600
printf("got usb pointer set\n");
PVOID ToBe = ":) hello this is our file -> ";
if (WriteFile(hFile,ToBe,512 ,&dwBytesWrite, NULL) == 0)
{
printf("writeFile error: %x", GetLastError());
CloseHandle(hFile);
return 1;
}
printf("write the first string in isb\n");
HANDLE aFile = CreateFile(L"C:\\Users\\h7080y_dxlq\\Downloads\\Video\\88250.mp4", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); //open the file handle
printf("created mp4 hendle\n");
if (aFile == INVALID_HANDLE_VALUE) {
printf("Error %x", GetLastError());
return 1;
}
if (ReadFile(aFile, &data, 512, &dwBytesRead, NULL) == 0) {
printf("ReadFile error: %x", GetLastError());
return 1;
}
DWORD dwPos;
printf("checked for read errors in mp4 passed o.k.\n");
while (ReadFile(aFile, data,512, &dwBytesRead, NULL) && dwBytesRead > 0) //read file
{
dwPos = SetFilePointerEx(hFile, a, NULL, 0);
LockFile(hFile, dwPos, 0, dwBytesRead, 0);
WriteFile(hFile, data, 512, &dwBytesWrite, NULL); // write 512 bit chunk at the time to usb
UnlockFile(hFile, dwPos, 0, dwBytesRead, 0);
a = { 50688+512 }; // promot
}
printf("write all mp4 to the usb directtly\n");
ToBe = "<- this is the end of file , see you soon :)";
if (WriteFile(hFile, ToBe, 512, &dwBytesWrite, NULL) == 0)
{
printf("writeFile error: %x", GetLastError());
CloseHandle(hFile);
return 1;
}
printf("after end massage \n");
CloseHandle(hFile);
system("pause");
return 0;
}
I try to take a file (mp4 in this case) , and read it chunk by chunk (512 bit at the time) , take the chunk and write it to usb and so on till end of file .
Now, the problem is:
A the loop never ends.
B that it don't write the file to the USB, it looks like its write on the same spot again and again...
How can I fix it?
LARGE_INTEGER a = { 50688 };
while (ReadFile(aFile, data,512, &dwBytesRead, NULL) && dwBytesRead > 0)
{
dwPos = SetFilePointerEx(hFile, a, NULL, 0);
LockFile(hFile, dwPos, 0, dwBytesRead, 0);
WriteFile(hFile, data, 512, &dwBytesWrite, NULL);
UnlockFile(hFile, dwPos, 0, dwBytesRead, 0);
a = { 50688+512 };
}
The first time round the loop you set the file pointer to 50688 and write there. Each subsequent time round the loop you set the file pointer to 50688+512 and write there.
It looks like it writes to the same spot again and again.
Yes indeed. That's exactly what your code specifies. Your should set the file pointer on aFile outside the loop, and let it advance naturally as the file is written. Something like this:
dwPos = 50688;
LARGE_INTEGER a = { dwPos };
if (!SetFilePointerEx(hFile, a, NULL, 0))
{
// handle error
}
while (ReadFile(aFile, data, 512, &dwBytesRead, NULL) && dwBytesRead > 0)
{
LockFile(hFile, dwPos, 0, dwBytesRead, 0);
WriteFile(hFile, data, 512, &dwBytesWrite, NULL);
UnlockFile(hFile, dwPos, 0, dwBytesRead, 0);
dwPos += 512;
}
Note that your calls to LockFile, and the use of a DWORD for dwPos, means that you cannot write a file larger than 4GB.
It is also far from clear to me that the calls to LockFile are needed. Since your original code got the handling of dwPos wrong, it's clear that you weren't locking the parts of the file you intended to. It is my belief that you should simply remove them. In which case the code will become:
LARGE_INTEGER a = { 50688 };
if (!SetFilePointerEx(hFile, a, NULL, 0))
{
// handle error
}
while (ReadFile(aFile, data, 512, &dwBytesRead, NULL) && dwBytesRead > 0)
{
if (!WriteFile(hFile, data, 512, &dwBytesWrite, NULL))
{
// handle error
}
}
You have also omitted large amounts of error checking in this code. I would not be surprised to find that there are a number of other problems with it. I don't particularly want to try to find every single error in your code, and hope that what I have written is enough to help you on your way.

SECURITY_SET_PASSWORD using DeviceIoControl() with ATA_PASS_THROUGH_EX failed

I've tried ATA_PASS_THROUGH_EX or ATA_PASS_THROUGH_DIRECT in DeviceIoControl() function with ATA command SECURITY_SET_PASSWORD but it always failed with GetLastError()=87 (invalid parameter). But ATA command IDENTIFY always succeed.
OS Environment: Windows 8.1 64bit, Visual Studio 2010, my application has Administrator privillage.
My goal is issue SECURITY ERASE UNIt like this page in the 64bit Windows 8.1: https://ata.wiki.kernel.org/index.php/ATA_Secure_Erase
Like above web page, when I tried using 'hdparm' in the ubuntu live CD to issue secure erase has been no problem with same hardware, and same SSD.
Would you please guide me what's wrong with my code?
m_h = CreateFile("\\\\.\\PhysicalDrive1", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if ( m_h == INVALID_HANDLE_VALUE )
return 0;
#if 1
char buffer[512 + sizeof(ATA_PASS_THROUGH_EX)] = { 0 };
ATA_PASS_THROUGH_EX& PTE = *(ATA_PASS_THROUGH_EX *)buffer;
PTE.Length = sizeof(PTE);
PTE.DataTransferLength = 512;
PTE.DataBufferOffset = sizeof(ATA_PASS_THROUGH_EX);
PTE.TimeOutValue = 10;
PTE.AtaFlags = ATA_FLAGS_DATA_OUT | ATA_FLAGS_DRDY_REQUIRED;
IDEREGS* ir = (IDEREGS*)PTE.CurrentTaskFile;
ir->bCommandReg = 0xF1;
strcpy(buffer + sizeof(ATA_PASS_THROUGH_EX) + 2, "test");
DWORD bytes = 0;
if (DeviceIoControl(m_h, IOCTL_ATA_PASS_THROUGH, &buffer, sizeof(buffer), &buffer, sizeof(buffer), &bytes, 0) == 0 ) {
DWORD er = GetLastError();
printf("error: %d\n", GetLastError());
return false;
}
#else
DWORD dataSize = sizeof(ATA_PASS_THROUGH_DIRECT) + 512;
ATA_PASS_THROUGH_DIRECT* pPTD = (ATA_PASS_THROUGH_DIRECT*) VirtualAlloc(NULL, dataSize, MEM_COMMIT, PAGE_READWRITE);
pPTD->Length = sizeof(ATA_PASS_THROUGH_DIRECT);
pPTD->DataTransferLength = 512;
pPTD->DataBuffer = ((char*)pPTD) + sizeof(ATA_PASS_THROUGH_DIRECT); // sizeof(ATA_PASS_THROUGH_DIRECT);
pPTD->TimeOutValue = 10;
pPTD->AtaFlags = ATA_FLAGS_DATA_OUT | ATA_FLAGS_DRDY_REQUIRED;
pPTD->CurrentTaskFile[1] = 0x01;
pPTD->CurrentTaskFile[6] = 0xF1;
strcpy( ((char*)pPTD->DataBuffer) + 2, "test");
DWORD bytes = 0;
if (!DeviceIoControl(m_h, IOCTL_ATA_PASS_THROUGH_DIRECT, pPTD, dataSize, pPTD, dataSize, &bytes, NULL)) {
printf("error: %d\n", GetLastError());
return false;
}
#endif
return true;
I think these ATA command blocked by OS: SECURITY SET PASSWORD, SECURITY ERASE UNIT. Because I did successfully running above program at the Windows 7 32bit and Windows 7 64bit but in Windows 8 (32bit/64bit) and Windows 10 (32bit/64bit), the same program shows invalid parameter error(error code 87).

In C/C++ how to programmatically detect SATA SSD plug in and unplug in Windows?

I'm trying to write a C/C++ program to detect a new SATA SSD (solid-state drive) connection in Windows 7.
This SATA SSD also comes with a SATA-USB cable. I've connected the SATA end to the SATA SDD and the USB end into my computer. Doing this I've been able to detect the SATA SDD connection and removal by using the windows message system to detect WM_DEVICECHANGE message and the associatedDBT_DEVICEARRIVAL event. To do this I also used RegisterDeviceNotification to register the device (i.e. the SATA SSD) so the top-level window receives notifications for device types DBT_DEVTYP_DEVICEINTERFACE with the classguid for the SATA SSD.
However, when I try to connect the SATA SDD to a SATA port on my computer's motherboard, my program doesn't work.
In C/C++ how can I detect SATA SSD plug in and unplug in Windows?
In general connecting an SSD drive to a SATA port on a powered-up computer is a bad idea. The SATA controller must have hotplug functionality to do this. But you can scan deviceclass and find all devices from this class and it will able to you process all interesting devices. I post code sample that can do this:
bool FindConnectedRemovableUsbstorDevices(std::list<std::wstring>& UsbList)
{
std::wstring ClassGuidString(L"{53F56307-B6BF-11D0-94F2-00A0C91EFB8B}");
GUID ClassGuid;
BYTE buf[1024];
PSP_DEVICE_INTERFACE_DETAIL_DATA_W pspdidd = reinterpret_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W>(buf);
SP_DEVICE_INTERFACE_DATA spdid;
SP_DEVINFO_DATA spdd;
DWORD size;
SP_DEVINFO_DATA dev_data;
DWORD properties;
if(NOERROR != CLSIDFromString(ClassGuidString.c_str(), &ClassGuid))
return false;
HDEVINFO dev_info = INVALID_HANDLE_VALUE;
dev_info = SetupDiGetClassDevs(&ClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (dev_info == INVALID_HANDLE_VALUE)
return false;
DWORD index = 0;
BOOL ret = FALSE;
spdid.cbSize = sizeof(spdid);
while (true)
{
ret = SetupDiEnumDeviceInterfaces(dev_info, NULL, &ClassGuid, index, &spdid);
if (!ret)
break;
size = 0;
SetupDiGetDeviceInterfaceDetail(dev_info, &spdid, NULL, 0, &size, NULL);
//Get required size
if (size == 0 || size >= sizeof(buf))
continue;
//prepare structs
ZeroMemory(reinterpret_cast<PVOID>(pspdidd), 1024);
pspdidd->cbSize = sizeof(*pspdidd); // 5 Bytes!
ZeroMemory(reinterpret_cast<PVOID>(&spdd), sizeof(spdd));
spdd.cbSize = sizeof(spdd);
BOOL res = SetupDiGetDeviceInterfaceDetail(dev_info, &spdid, pspdidd, size, &size, &spdd);
//Get info
if (!res)
continue;
HANDLE drive = CreateFileW(pspdidd->DevicePath, FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);//open device
if (drive == INVALID_HANDLE_VALUE)
continue;
printf("\n%S\r\n", pspdidd->DevicePath);
DWORD bytes_returned = 0;
BOOL b = DeviceIoControl(drive, IOCTL_STORAGE_CHECK_VERIFY2, NULL, 0, NULL, 0, &bytes_returned, NULL);
if (!b) //check is card reader?
{
printf("IOCTL_STORAGE_CHECK_VERIFY2 error = %d\r\n", GetLastError());
goto stop_process_device;
}
bytes_returned = 0;
STORAGE_DEVICE_NUMBER sdn;
//Get Drive number
b = DeviceIoControl(drive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &bytes_returned, NULL);
if (!b)
goto stop_process_device;
RtlZeroMemory(&dev_data, sizeof(SP_DEVINFO_DATA));
dev_data.cbSize = sizeof(dev_data);
if (SetupDiEnumDeviceInfo(dev_info, sdn.DeviceNumber, &dev_data))
{
//check property
b = SetupDiGetDeviceRegistryProperty(dev_info, &dev_data, SPDRP_REMOVAL_POLICY, NULL,
reinterpret_cast<PBYTE>(&properties), sizeof(properties), NULL);
if (b && properties != CM_REMOVAL_POLICY_EXPECT_NO_REMOVAL)
{
UsbList.push_back(pspdidd->DevicePath);
printf("REMOVAL\r\n");
}
}
stop_process_device:
CloseHandle(drive);
index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
return true;
}

How to use IOCTL_DISK_GROW_PARTITION?

I'm trying to shrink my partition to the last used LCN. Has anybody used this control code?
I'm getting System Error code 87 every time in the following code:
HANDLE hDiskHandle = NULL;
DISK_GROW_PARTITION dgp;
DWORD dwBytesReturned = 0;
dgp.PartitionNumber = 2;
dgp.BytesToGrow.QuadPart = -1;
hDiskHandle = CreateFile(_T("\\.\PhysicalDrive0"), GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, NULL, NULL);
if (hDiskHandle == INVALID_HANDLE_VALUE) {
int err = GetLastError();
printf("Unable to get handle on Volume, error : %d", err);
}
if (!DeviceIoControl(
hDiskHandle,
IOCTL_DISK_GROW_PARTITION,
&dgp,
sizeof dgp,
NULL,
0,
&dwBytesReturned,
NULL
)) {
int err = GetLastError();
printf("DeviceIoControl Failed, error : %d", err);;
}
My hard drive has 3 partitions (C, D, E). The E: drive is practically empty.
[OP's solution converted to answer below]
It turns out my program was fine. It started working after changing access from
GENERIC_ALL
to
GENERIC_READ | GENERIC_WRITE