linuxdiskcapacity

How does Linux Kernel know disk capacity? (at boot time)


I know that in linux environment, we can check the disk capacity (e.g. in units of the number of sectors) through commands such as df or fdisk.

But, as far as I know, such a command seems to "read disk capacity information already loaded in memory". (Not asking the disk directly for capacity)

If so, how is disk capacity calculated at the earliest (probably at boot time)?

Is the linux kernel driver asking the disk controller (inside the disk)?

Or, calculate the MAX LBA by scanning all the way from Disk LBA 0?

Also, I wonder if the method is different for each storage interface. (e.g., SCSi, ATA, NVMe)


Solution

  • How does Linux Kernel know disk capacity? (at boot time)

    This strongly depends on how the disc is connected. Kernel queries the disc capacity by executing specific communication using specific protocol with the controller on the disc.

    For example, if the disc is connected via ATA, we can look into ATA/ATAPI Command Set like https://people.freebsd.org/~imp/asiabsdcon2015/works/d2161r5-ATAATAPI_Command_Set_-_3.pdf . After short screening of the document I think I've found it - for example, you can take the disc capacity from Device Capacity field in Capacity log page (page 431) from IDENTIFY DEVICE data log using READ LOG EXT - 2Fh, PIO Data-In (page 182). Also 4.1.2 Capacity reporting page 19 and command IDENTIFY DEVICE - ECh, PIO Data-In on page 103 sound relevant.