09 | USB Interface Drivers: Enumeration and Hotplug

Use a test peripheral you control, such as an STM32 or RP2040 running custom USB device firmware. Verify that Linux binds your driver to the intended interface and calls disconnect() when it is removed.

1. Inspect the descriptors

On the Linux host, run these commands. Replace VID:PID with the actual hexadecimal pair.

lsusb
lsusb -t
sudo lsusb -v -d VID:PID
Field Purpose
idVendor and idProduct Identify the device
bInterfaceNumber Select the interface
Endpoint address, direction, and type Identify the data paths and transfer types

When using QEMU, pass the physical device through to the guest and run lsusb inside the guest. Select a custom test interface that is available for binding.

2. Write the USB interface driver

Create demo_usb.c and set the three DEMO_USB_* constants to match the test peripheral.

#include <linux/module.h>
#include <linux/usb.h>

#define DEMO_USB_VID       0x0000
#define DEMO_USB_PID       0x0000
#define DEMO_USB_INTERFACE 0

static const struct usb_device_id demo_usb_ids[] = {
    { USB_DEVICE_INTERFACE_NUMBER(DEMO_USB_VID, DEMO_USB_PID,
                                  DEMO_USB_INTERFACE) },
    { }
};
MODULE_DEVICE_TABLE(usb, demo_usb_ids);

static int demo_usb_probe(struct usb_interface *intf,
                          const struct usb_device_id *id)
{
    const struct usb_host_interface *alt = intf->cur_altsetting;

    dev_info(&intf->dev, "bound interface %u, endpoints %u\n",
             alt->desc.bInterfaceNumber, alt->desc.bNumEndpoints);
    return 0;
}

static void demo_usb_disconnect(struct usb_interface *intf)
{
    dev_info(&intf->dev, "interface disconnected\n");
}

static struct usb_driver demo_usb_driver = {
    .name = "demo_usb",
    .id_table = demo_usb_ids,
    .probe = demo_usb_probe,
    .disconnect = demo_usb_disconnect,
};

module_usb_driver(demo_usb_driver);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("USB interface driver lab");

Create the Makefile in the same directory.

obj-m := demo_usb.o

3. Verify plugging and unplugging

make -C "/lib/modules/$(uname -r)/build" M="$PWD" modules
sudo insmod ./demo_usb.ko
sudo dmesg -w

Plug in the peripheral and look for bound interface. In another terminal, verify that lsusb -t shows Driver=demo_usb for that interface. Unplug it and look for interface disconnected. Press Ctrl+C to leave the log viewer, then unload with sudo rmmod demo_usb.

Extension

With a test MCU that provides Bulk IN and Bulk OUT, implement a loopback that returns the received string. Check the descriptors, then try a transfer with a finite timeout using usb_bulk_msg(). Unplug the peripheral during I/O and verify that the caller receives an error. For asynchronous URBs, stop new requests during unbind, cancel and wait for pending URBs, and then release the buffers.

Reference Writing USB Device Drivers