There was a time when Linux was much simpler. You’d load a driver, it would find your device at boot up, or it wouldn’t. That was it. Now, though, people plug and unplug USB devices all the time and expect the system to react appropriately. [Arcanenibble] explains all “the gory details” about what really happens when you plug or unplug a device.
You might think, “Oh, libusb handles that.” But, of course, it doesn’t do the actual work. In fact, there are two possible backends: netlink or udev. However, the libusb developers strongly recommend udev. Turns out, udev also depends on netlink underneath, so if you use udev, you are sort of using netlink anyway.
If netlink sounds familiar, it is a generic BSD-socket-like API the kernel can use to send notifications to userspace. The post shows example code for listening to kernel event messages via netlink, just like udev does.
When udev sees a device add message from netlink, it resends a related udev message using… netlink! Turns out, netlink can send messages between two userspace programs, not just between the kernel and userspace. That means that the code to read udev events isn’t much different from the netlink example.
The next hoop is the udev event format. It uses a version number, but it seems stable at version 0xfeedcafe. Part of the structure contains a hash code that allows a bloom filter to quickly weed out uninteresting events, at least most of the time.
The post documents much of the obscure inner workings of USB hotplug events. However, there are some security nuances that aren’t clear. If you can explain them, we bet [Arcanenibble] would like to hear from you.
If you like digging into the Linux kernel and its friends, you might want to try creating kernel modules. If you get overwhelmed trying to read the kernel source, maybe go back a few versions.