5

I have a large storage device (flash memory) plugged onto my computer via the PCIe bus, I want to access such device directly, i.e., without any file system (e.g., NTFS or ext4) on it.

How can I do this using C/C++? (on both Windows 7 and Linux) I am wondering if I can 1) open the device just as a file, and then read and write binary data to it, or 2) allocate the whole device using some function like malloc, then each byte on the device have an address so that I can access them based on the addresses.

I prefer the second way if it possible, but I don't know if the OS supports this since it seems the address space needs to be shared with the main memory.

Peixu Zhu
  • 2,111
  • 1
  • 15
  • 13
Bloodmoon
  • 1,308
  • 1
  • 19
  • 34

2 Answers2

12

According to Microsoft documentation:

On Windows you can open a physical drive using CreateFile using a path of the form

\\.\PhysicalDriveN

where N is the device number or a logical drive using a path of the form

\\.\X:

You will need to seek, read and write in multiples of the sector size which can be retrieved using DeviceIoControl() with IOCTL_DISK_GET_DRIVE_GEOMETRY.

mclaassen
  • 5,018
  • 4
  • 30
  • 52
  • seems that the documentation is not detailed enough, how can I locate a block or sector in the disk? – Bloodmoon Nov 22 '14 at 12:05
  • What do mean by locate? You just seek to whatever sector you want seeking to position sector * sector size in the opened file. – mclaassen Nov 22 '14 at 22:37
10

On Linux each storage device ends up getting a device entry in /dev. The first storage device is typically /dev/sda, the second storage device, if one is present, is /dev/sdb. Note that an optical disk is a storage device, so a CD-ROM or a DVD-ROM drive, if one is present, would get a device node entry.

Some Linux distributions may use a different naming convention, but this is what it usually is. So, you'll need to figure out which device corresponds to your flash disk, and just open the /dev/sdX device, and simply read and write from it. Your reads and writes must be for even block (sector) sizes, and seeking the opened file governs which disk blocks/sectors the subsequent read or write will affect.

Generally, /dev/sdX will be owned by root, but there are usually some Linux distribution-specific ways to fiddle the userid that owns a particular device node.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • I see. So it is impossbile that I access in the unit of bytes but in the unit of sectors, right? In memory, I can locate a byte using an address, how can I locate a sector in the disk then? – Bloodmoon Nov 21 '14 at 10:46
  • The first sector (well, the 0th sector) on the disk is byte offset 0, the next sector is byte offset 512, and so on... You seek the file to the correct offset, for your Logical Block Address, and read the block. – Sam Varshavchik Nov 21 '14 at 11:29