How is by-id created on Linux?

The file name is generated by udev, but the id inside it comes from the device itself:

if you run lsusb -v and search for it, you'll find it's the serial id of the device:

...
iManufacturer        MBED
iProduct             microcontrolleur
iSerial              10105a42e87da33c103dccfb6bc235360a97

or something similar.


How does this happen ?

Let's say the usb stick gets mounted on /mnt/tmp. On my system i get:

$ udevadm info --device-id-of-file /mnt/tmp
8:17

Now run this and search for 8:17:

$ udevadm info --export-db | less
...
P: /devices/pci0000:00/0000:00:1d.7/usb1/1-3/1-3:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1
N: sdb1
W: 61
S: block/8:17
S: disk/by-id/usb-pqi_IntelligentStick_AA04212900042956-0:0-part1

This gives us the device path to use with udevadm. Run this and search for for your device id (AA042... in my case)

$ udevadm test /devices/pci0000:00/0000:00:1d.7/usb1/1-3/1-3:1.0/host4/target4:0:0/4:0:0:0/block/sdb/sdb1 2>&1 | less
...
udev_rules_apply_to_event: LINK 'disk/by-id/usb-pqi_IntelligentStick_AA04212900042956-0:0-part1' /lib/udev/rules.d/60-persistent-storage.rules:31

That gives us all the udev rules + line numbers applied (60-persistent-storage.rules:31 etc)

And here's where the file name comes from:

$ /lib/udev/usb_id /devices/pci0000:00/0000:00:1d.7/usb1/1-3/1-3:1.0/host4/target4:0:0/4:0:0:0/block/sdb
pqi_IntelligentStick_AA04212900042956-0:0

by-id symlinks are created by udev rules (and are specific to OS'es using udev)

You can find the specific rules in /lib/udev/rules.d:

for serial devices in 60-persistent-serial.rules:

ENV{.ID_PORT}=="", SYMLINK+="serial/by-id/$env{ID_BUS}-$env{ID_SERIAL}-if$env{ID_USB_INTERFACE_NUM}"
ENV{.ID_PORT}=="?*", SYMLINK+="serial/by-id/$env{ID_BUS}-$env{ID_SERIAL}-if$env{ID_USB_INTERFACE_NUM}-port$env{.ID_PORT}"

and for the disk devices in 60-persistent-storage.rules:

KERNEL=="sd*|sr*|cciss*", ENV{DEVTYPE}=="disk", ENV{ID_SERIAL}=="?*", SYMLINK+="disk/by-id/$env{ID_BUS}-$env{ID_SERIAL}"