Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Determining block device's sector size in Linux+Python
#!/usr/bin/python
import fcntl
import os
import struct
import array
import sys
BLKGETSIZE=0x1260
BLKGETSIZE64=0x80081272
BLKSSZGET=0x1268
BLKPBSZGET=0x127b
def ioctl_read_uint32(fd, req):
buf = array.array('c', [chr(0)] * 4)
fcntl.ioctl(fd, req, buf)
return struct.unpack('I',buf)[0]
def ioctl_read_uint64(fd, req):
buf = array.array('c', [chr(0)] * 8)
fcntl.ioctl(fd, req, buf)
return struct.unpack('L',buf)[0]
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: %s block_device" % sys.argv[0]
sys.exit(1)
device = sys.argv[1]
fd = os.open(device, os.O_RDONLY)
logical_sector_size = ioctl_read_uint32(fd, BLKSSZGET)
physical_sector_size = ioctl_read_uint32(fd, BLKPBSZGET)
try:
device_size = ioctl_read_uint64(fd, BLKGETSIZE64)
except IOError as e: # Some platform doesn't support BLKGETSIZE64
if e.errno == 25: # "Inappropreate ioctl for device"
device_size = ioctl_read_uint32(fd, BLKGETSIZE) * logical_sector_size
else: raise
os.close(fd)
print "Block device: %s" % device
print " Entire device capacity: %d" % device_size
print " Logical sector size: %d" % logical_sector_size
print " Physical sector size: %d" % physical_sector_size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment