3

My disk is sda. There is the size file /sys/dev/block/8:0/size. Its unit is sectors. When I run strace lsblk I can see it reading this file.

But how does lsblk get the sector size to later show the total disk size in bytes? Because I cannot see lsblk reading the file hw_sector_size nor physical_block_size.

zomega
  • 972

1 Answers1

4

It doesn't because it doesn't need to, the sector size used in /sys/block/<device>/size is always 512 regardless of the actual physical sector size of the device. I wasn't able to find a documentation for this, so I'll refer to this answer which also has some links to the kernel code in the comments where it is stated that

Linux always considers sectors to be 512 bytes long independently of the devices real block size.

And a quick test with loop devices also shows that this is true:

$ cat /sys/block/loop0/size 
204800
$ cat /sys/block/loop0/queue/physical_block_size 
512

$ cat /sys/block/loop1/size 204800 $ cat /sys/block/loop1/queue/physical_block_size 4096

and these are both 100 MiB devices

$ lsblk
NAME                                          MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINTS
loop0                                           7:0    0   100M  0 loop  
loop1                                           7:1    0   100M  0 loop 

(Note that if you ask lsblk to also include the physical sector size in the results using the -o+PHY-SEC, you can see it reads the queue/physical_block_size file when it actually needs the physical size.)

  • Indeed, in lsblk.c:initialize_device (ll. 1199-2000), one sees if (ul_path_read_u64(dev->sysfs, &dev->size, "size") == 0) /* in sectors */ dev->size <<= 9; /* in bytes */ with the sector size hardwired to 512 bytes. – NickD Dec 21 '22 at 03:00