Linux USB Device Driver Part 3 - Registering a USB Driver with Linux

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

MODULE_LICENSE("GPL");
#define USB_VENDOR_ID  0x18ec
#define USB_PRODUCT_ID 0x3299

static const struct usb_device_id usb_table[] = {
    { USB_DEVICE(USB_VENDOR_ID, USB_PRODUCT_ID) },
    { }
};
MODULE_DEVICE_TABLE(usb, usb_table);


static int usb_probe(struct usb_interface *interface,
                        const struct usb_device_id *id)
{
    dev_info(&interface->dev, "USB Driver Probed: Vendor ID:%02x\t"
             "Product ID:%02x\n", id->idVendor, id->idProduct);
    return 0;
}

static void usb_disconnect(struct usb_interface *interface)
{
    dev_info(&interface->dev, "USB Driver Disconected\n");
}

static struct usb_driver usb_hello_driver = {
    .name = "hello",
    .probe = usb_probe,
    .disconnect = usb_disconnect,
    .id_table = usb_table,
};
module_usb_driver(usb_hello_driver);

Steps for Registering your driver with USB Subsystem

1. Create struct usb_driver filling the following fields:
name -> Used in the message logs (dmesg)
probe -> Function called when the supported device is connected
disconnect -> Function called when the supported device is removed
id_table -> list of devices supported (vendor id, product id)

2. Register this structure with USB Subsystem by calling module_usb_driver which is a helper macro for registering a USB driver, creates init and exit function and calls usb_register in init and usb_deregister in exit

3. MODULE_DEVICE_TABLE is used for usb hotplugging

Steps for testing the driver

1. Connect the USB device and do insmod <driver.ko> and check dmesg, if there is already driver loaded for the device, remove it using rmmod
2. Remove the USB device from the host and check dmesg, you should observe disconnect function is called.

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto